My Django notes

Install Python 3
Install Django using pip install Django
Install your favourite editor (I have installed Notepad++)

To create new project, issue following command:
admin startproject <mysite>
Following structure gets created:
myproject/myproject
__init__.py
settings.py
urls.py
wsgi.py

"settings.py" contains Application definitions, that you need to change whenever you add an app.  It also contains encryption SECRET_KEY, which should not be shared in Production environment.

"urls.py" contains URL that routes to views.

To start python server, issue following command:
python manage.py runserver

To add another app, issue following command:
python manage.py startapp <webapp>

Following structure is created:
myproject/webapp
__init__.py
admin.py
apps.py
models.py
tests.py
views.py

After adding the app, add the same to settings.py in your project.
Also add in urls.py
url(r'^webapp/', include('webapp.url'))

in webapp/views.py, add index(request) function and to it, add and HttpResponse() which will return an HTML line.

Add a new webapp/urls.py file and import views from parent:

from . import views

and then add
url(r'^$', views.index, name='index')

"Jinja"

In the views.py call render function:
return render(request, 'personal/home.html')

create personal/home.html, which extends header.html

{% extends "personal/header.html" %}
{% block content %}
<p>Hey, welcome to my website.</p>
{% endblock %}

code within {% block content %} and {% endblock %} gets replaced in the header.html

<body>
    <div>
        {% block content %}
        {% endblock %}
    </div>
</body>

in home.html, we can also include logic from another file by
{% include "personal/snippet.html" %}
This will include the snippet in snippet.html where the above logic is written.

snippet.html:
{% block content %}
    <p>Hey, I'm included too!! Cool!</p>
{% endblock %}

This is called Jinja templating.

No comments:

Post a Comment