Initial Django

A useful tutorial i sin the djangoproject documentation. It will build a simple app and on the way provide proper explanation of backgrounds. For a quick overview of the general Django setup see Django at a glance.

Initial setup
Create an app
Add css
Add an additional page and a simple menu
 

Initial setup


Windows-x to start windows console. Setup in console:

> cd documents/#_python3/django
> md project_name
> cd project_name
> pipenv install django
> pipenv shell
> django-admin startproject name .
> md templates
> md static
> md lib
> python manage.py runserver

The project is called name. Don’t forget the dot in the django-admin command, or you will have a redundant level of name-directory. I use the subdirectory lib to house any supplementary code and modules that support the functionality of my applications. This is not core Django. The server runs at http://127.0.0.1:8000. Check it out, to see the Django rocket lift-off.


Edit name/settings.pi in two places:
1) Templates

...
TEMPLATES = [
    { 
      'BACKEND': '...',
      'DIRS': [os.path.join(BASE_DIR, 'templates')],
      '...'
    }
]
...

2) Static

...
STATIC_URL = '/static/'

STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]

top

Create an app


Create an app in the console:

> python manage.py startapp pages

The app is called pages. Register pages in name/settings.pi:

INSTALLED_APPS = [
    ...
    'django.contrib.staticfiles',
    'pages.apps.PagesConfig',
]    

This is the full reference to PagesConfig in pages/apps.py. For short, you can use:

INSTALLED_APPS = [
    ...
    'django.contrib.staticfiles',
    'pages',
]    

At first, the number of programme files that need to collaborate seems bewildering. A small adaptation at one place may require adjustments in three or more files. To know what is where and how things are related takes some time to get accustomed to.

Basically, the routing is not as complicated as it seems. It is just Python programming, similar to any other Python project. You can think of the url-structure as the platform from where the various parts of the programme will be launched. Once an urls has been interpreted, it will initiate the execution of a view-function. Executing a view will have a regular html-page in the browser as its end product. To do this, the view needs data (e.g. a model that represents a database-table) and an html-template. The template will use a basic templating language, similar to php, to decide how to select and where to include the data to be shown. The template will combine with regular css for the lay-out and a language like javascript to provide client-side functionality. The long story short, is that a Django project is a Python programme just like any other.

First, we need a url-structure in place that will call the various programme functions. The url-structure starts in name/urls.py, which is in the same directory as settings.py. This central urls-file registers the urls of the admin and of the various apps of the project.

# name/urls.py
from django.contrib import admin
from django.urls import path, include

urpatterns = [ 
    path('admin/', admin.site.urls), 
    path('', include('pages.urls')),
]

In this example, the reference to the urls of pages is included at the root-level (”) of the site. Alternatively, you could give the urls their own level (‘pages/’):

# name/urls.py
...
urpatterns = [ 
    path('admin/', admin.site.urls), 
    path('pages/', include('pages.urls')),
...

Next, we need to create app-level pages/urls.py. This will contain the urls for the various views of the appe.

# pages/urls.py
from django.urls import path
from . import views

urlpatterns = [ 
    path('', views.HomePageView.as_view(), name = 'home'),
]

We now have a url that will be recoginzed as ‘home’ and that will reside at pages/ (as defined in the second example of the initial urls-file). The url will execute HomePageView.as_view(), which we now will define in pages/views.py.

# pages/views.py
from django.views.generic import TemplateView

class HomePageView(TemplateView):
    template_name = 'home.html'

The view will generate an html-output of the type TemplateView, using the template in templates/home.html. TemplateView is one of the base views of Django. As a final step we now need create this file and place it in the templates directory.

<!-- templates/home.html -->
<h2>Under construction<h2>

top

Add css


To add css we should include a reference to a style sheet in the template. This is accomplished with the template language. The four elements of the Django template language are variables: {{ variable }}, tags: {% tag %}, filters: {{ variable|argument }} and comments: {# comment #}. The static directory and the style sheet are included using tags.

<!--templates/home.html-->
{% load static %}
<html>
    <head>
        <link rel="stylesheet" href="{% static 'css/base.css' %}">
    </head>

    <body>
        <h2>Under construction</h2>
    </body>
</html>

Create style sheet in static/css/base.css:

/* static/css/base.css */

h2 {
    color: blue;
    }


top


Adding a page, again requires 3 steps, to adjust urls, views and templates. The minimal templating language of Django allows the reuse of code, very similar to the include-statement in php.

1) Adjust app-level urls.py:

# pages/urls.py
from django.urls import path
from . import views

urlpatterns = [ 
    path('', views.HomePageView.as_view(), name = 'home'),
    path('about/', views.AboutPageView.as_view(), name = 'about'),
]

2) Adjust views.py:

# pages/views.py
from django.views.generic import TemplateView

class HomePageView(TemplateView):
    template_name = 'home.html'

class AboutPageView(TemplateView):
    template_name = 'about.html'

3a) Transform home.html into base.html, to include template instruction and a simple menu:

<!--templates/base.html-->
{% load static %}
<html>
    <head>
        <link rel="stylesheet" href="{% static 'css/base.css' %}">
    </head>

    <body>
        <header>
            <a href="{% url 'home' %}">Home</a> |
            <a href="{% url 'about' %}">About</a> |
        </header>
        {% block content %}
        {% endblock %}
    </body>
</html>

3b) Adapt home.html as an extension of base.html:

<!--templates/home.html-->
{% extends 'base.html' %}

{% block content %}
    <h2>Under construction</h2>

    <p>Thank you for your visit!</p> 
    <p>Not ready yet. Please, check back later.</p>
{% endblock %}

3c) Add about.html as a similar extension of base.html:

<!--templates/about.html-->
{% extends 'base.html' %}

{% block content %}
    <h2>About</h2>

    <p>Practice builds results</p> 
{% endblock %}

top

Leave a Reply

Your email address will not be published. Required fields are marked *