Django II

Serie of articles about developing a Full Django Web Site.


MODELS

Goals:

  1. Create models
  2. Create databases behind them
  3. Populate the models:
    • Use shell to add something
    • Use admin interface, to do that we have to:
      1. register the models to our applications admin.py file
      2. create a superuser

CREATING MODELS

first_project/models.py

Models are creating through Object Oriented Programming (OOP). Models are Classes:

from django.db import models

# Create your models here.

class Topic(models.Model):
    top_name = models.CharField(max_length=264, unique=True)

    def __str__(self):
        return self.top_name

class Webpage(models.Model):
    topic = models.ForeignKey(Topic, on_delete=models.CASCADE,)
    name = models.CharField(max_length=264, unique=True)
    url = models.URLField(unique=True)

    def __str__(self):
        return self.name

class AccessRecord(models.Model):
    name = models.ForeignKey(Webpage, on_delete=models.CASCADE,)
    date = models.DateField()

    def __str__(self):
        return str(self.date)

Since Django 2.x, on_delete is required into models.ForeignKey parameters its values could be: models.CASCADE or models.DO_NOTHING

DATABASES

Create the sequel databases behind these models.

(MyDjangoEnv) antiax@debian:~/Desktop/Django-workspace/first_project$ python manage.py migrate
...
(MyDjangoEnv) antiax@debian:~/Desktop/Django-workspace/first_project$ python manage.py makemigrations first_app
No changes detected in app 'first_app'
(MyDjangoEnv) antiax@debian:~/Desktop/Django-workspace/first_project$ python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
  No migrations to apply.

Now all models are connected to the databases that Django has just created for us and register the changes to our application.

CREATE CONTENT (POPULATE)

WITH THE SHELL

(MyDjangoEnv) antiax@debian:~/Desktop/Django-workspace/first_project$ python manage.py shell
Python 3.5.6 |Anaconda, Inc.| (default, Aug 26 2018, 21:41:56)
[GCC 7.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from first_app.models import Topic
>>> print(Topic.objects.all())
<QuerySet []>
>>> t = Topic(top_name="Social Network")
>>> t.save()
>>> print(Topic.objects.all())
<QuerySet [<Topic: Social Network>]>

WITH THE ADMIN INTERFACE

  1. register our models:firs_app/admin.py
    from django.contrib import admin
    from first_app.models import AccessRecord, Topic, Webpage
    
    # Register your models here.
    
    admin.site.register(AccessRecord)
    admin.site.register(Topic)
    admin.site.register(Webpage)
    

    So these are registered and ready to be used with the admin interface.

  2. Create super user:
    (MyDjangoEnv) antiax@debian:~/Desktop/Django-workspace/first_project$ python manage.py createsuperuser
    Username (leave blank to use 'antiax'):
    Email address: training@antiax.org
    Password:
    Password (again):
    Superuser created successfully.
    
  3. running the server:
    (MyDjangoEnv) antiax@debian:~/Desktop/Django-workspace/first_project$ python manage.py runserver
    Performing system checks...
    
    System check identified no issues (0 silenced).
    June 08, 2019 - 19:55:50
    Django version 2.1.1, using settings 'first_project.settings'
    Starting development server at http://127.0.0.1:8000/
    Quit the server with CONTROL-C.
    
  4. access the admin interface:http://127.0.0.1:8000/admin

    Login. Access to the Panel.

WITH THE POPULATION SCRIPTS

How to create a script that will populate our models with some “dummy” data with Faker library.

  1. Install the library.activate the enviroment:
    antiax@debian:~/Desktop/Django-workspace$ source activate MyDjangoEnv
    (MyDjangoEnv) antiax@debian:~/Desktop/Django-workspace$
    

    Install:

    (MyDjangoEnv) antiax@debian:~/Desktop/Django-workspace$ pip install Faker

    documentation for Faker library: https://faker.readthedocs.io/en/master/

  2. Create the sprit:
    Into the home (top level) directory of our project:first_project/populate_first_app.py
  3. Running the script:
    (MyDjangoEnv) antiax@debian:~/Desktop/Django-workspace/first_project$ python populate_first_app.py
    populating script!
    populating complete!
    (MyDjangoEnv) antiax@debian:~/Desktop/Django-workspace/first_project$
    
  4. Testing:
    1. create the superuser if didnt
    2. register the models if didnt
    3. running the server:
                  (MyDjangoEnv) antiax@debian:~/Desktop/Django-workspace/first_project$ python manage.py runserver
                  Performing system checks...
      
                  System check identified no issues (0 silenced).
                  June 09, 2019 - 09:15:44
                  Django version 2.1.1, using settings 'first_project.settings'
                  Starting development server at http://127.0.0.1:8000/
                  Quit the server with CONTROL-C.
                  
    4. Access to the admin panel, and check the models content: http://127.0.0.1:8000/admin

 

Django Models-Templates-Views (MTV)

 

      1. In the views.py file we import any models that we will need to use.
      2. Use the view to query the model for data that we will need.
      3. Pass results from the model to the template.
      4. Edit the template so that it is ready to accept and display the data from the model.
      5. Map a URL to the view.

  • 1 & 2first_project/first_app/views.py
    from django.shortcuts import render
    from django.http import HttpResponse
    from first_app.models import AccessRecord, Topic, Webpage
    
    # Create your views here.
    def index(request):
        webpage_list = AccessRecord.objects.order_by('date')
        date_dict = {'access_records': webpage_list}
        return render(request, 'first_app/index.html', context=date_dict)
    
  • 3 & 4
    first_project/templates/first_app/index.html

    <!DOCTYPE html>
    {% load staticfiles %}
    <!DOCTYPE html>
    <html lang="en" dir="ltr">
      <head>
        <meta charset="utf-8">
        <title>Django Level Two</title>
        <link rel="stylesheet" href="{% static "css/style.css" %}">
      </head>
      <body>
        <h1>Hi welcome to Django Level two!</h1>
        <h2>Here are you access records:</h2>
    
        <div class="djangotwo">
          <!-- logical staff -->
          {% if access_records %}
            <table>
              <thead>
                <th>Site Name</th>
                <th>Date Accessed</th>
              </thead>
    
              {% for acc in access_records %}
                <tr>
                  <!--Injected data -->
                  <td>{{ acc.name }}</td>
                  <td>{{ acc.date }}</td>
                </tr>
              {% endfor %}
            </table>
          {% else %}
            <p>NO ACCESS RECORDS FOUND!</p>
          {% endif %}
        </div>
    
      </body>
    </html>
    
  • 5
    first_project/first_project/urls.py

    from django.contrib import admin
    from django.urls import path
    from first_app import views
    
    urlpatterns = [
        #  Add an import:  from first_app import views
        path('', views.index, name="index"),
        path('admin/', admin.site.urls),
    ]