Dynamic Django

This is work in progress …

Connect to MySql database (local)
Models as respresentations of database tables
Using templates to display data
Using forms to interact with data
 

Connect to MySql database (local)


This is the local setup. For the external implementation see Setup Django on WebhostPython.

Preparation

Make sure the local server (e.g. xampp) is installed and activated (e.g. in the xampp panel).
Open localhost/phpadmin to create a database. Make sure there is a user with full privileges.

Install python modules

> pipenv shell
> pipenv install mysqlclient

If you want to have direct access to the database tables, it is convenient to also instal ipython. This will allow to run scripts from the python console. See: delaing with existing data.

> pipenv install ipython
Database credentials

Install python module mysqlclient

Include database credentials in project/settings.py

DATABASES = {
    'default': {
        'ENGINE'  : 'django.db.backends.mysql',
        'NAME'    : 'database_name',
        'USER'    : 'database_username',
        'PASSWORD': 'database_password',
    }
}

Migrate and create superuser

After getting the Django description of existing data, it is time to migrate the database and create a superuser.

> python manage.py migrate
> python manage.py createsuperuser
> python manage.py check
> python manage.py runserver

This will create the necessary tables that Django uses in the background. The command createsuperuser creates login-credentials for admin access. Login to confirm that it works.


top

Models as representations of databsae tables


Basically, a model is a Django-class that relates to a database. Models are derived from the Django-class django.db.models. The models of an app are stored in app/models.py. Generally, each model maps to a single database table.

Here is a simple model called Post. Post is a class that derives from django.db.models.Model. Post has three data-fields or variables. The first data-field is called title. It is a Charfield variable of length 200. The second is called author. It is the ForeingKey of the table and has various characteristics. The third data-field is called body and is a TextField variable.

# app/models.py
from django.db import models
class Post(models.Model):
    title  = models.CharField(max_length=200)
    author = models.ForeignKey('auth.User',
                                on_delete=models.CASCADE,
                              )
    body   = models.TextField()

    def __str__(self):
        return self.title

Synchronize the new model with the database with makemigrations (notes that Post has been added) and migrate (includes Post in the database)

> python manage.py makemigrations
> python manage.py migrate

And register Post in app/admin.py

# app/admin.py
from django.contrib import admin
from . models import Post

admin.site.register(Post)

top

Using templates to display data


The data from Post can be displayed in in a template using the Django template language. Templates are .html files stored in the template-directory.

In the example the data from the Post-model are displayed in the tags of a {% block content%}, that {% extends ‘base.html’ %}. All posts are selected from the post.object_list using the open and close-tags for a {% for [condition] %} – {% endfor %} loop.

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

{% block content %}
    {% for post in object_list %}
        <h2><a href="">{{ post.title }}</a></h2>
        <p>{{ post.body }}</p>
    {% endfor %}
{% endblock %}

An annoying feature might be that text that contains html-code might be autoescaped before dysplay. The consequence of this feature is that html-link show as bare text. To avoid this, autoescape can be turned of.

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

{% block content %}
    {% for post in object_list %}
        {% autoescape off %}
            <h2><a href="">{{ post.title }}</a></h2>
            <p>{{ post.body }}</p>
        {% endautoescape %}
    {% endfor %}
{% endblock %}

Next, to access the template we need to adjust app/views.py to include Post as a ListView (BlogListView) on home.html

# app/views.py
from django.views.generic import ListView
from . models import Post

class BlogListView(ListView):
    model = Post
    template_name = 'home.html'

Finally, app/urls.py needs adjustment to link views.BlogListView to the home-url

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

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

top

Using forms to interact with data


Working with forms


top