Writing

Basics of Django framework

DjangopythonCRUD in djangoCSSDjnago mtvHTMLadmin interfaceclass based viewsdata basedjango formsformsfunctions based viewsmixinspython3url mappingsuser authenticationuser interfacevirtual environment

So, to understand this blog you require a basic understanding of command line interface, SQL requests and Python.

Django is a free and open source web framework. It is used by many sites, including Pinterest, PBS, Instagram, BitBucket, Washington Times, Mozilla, and more!

The original documentation done for Django by Django and Mozilla community is so useful, that i have mostly always taken help from them.

Q.How do we have a steady version of any packages or software?

A self-contained directory tree, i.e a virtual environment

A virtual environment allows you to have a virtual installation of Python and packages on your computer.

1. Create a virtual environment for your project

  1. In the terminal client enter the following where yourenvname is the name you want to call your environment, and replace x.x with the Python version you wish to use. (To see a list of available python versions first, type conda search "^python$" and press enter.)
conda create -n yourenvname python=x.x anaconda

2. Activate your virtual environment.

  1. To activate or switch into your virtual environment, simply type the following where yourenvname is the name you gave to your environement at creation.
source activate yourenvname

To see a list of all your environments, use the command conda info -e.

3. Install additional Python packages to a virtual environment.

  1. To install additional packages only to your virtual environment, enter the following command where yourenvname is the name of your environemnt, and [package] is the name of the package you wish to install. Failure to specify “-n yourenvname” will install the package to the root Python installation.
conda install -n yourenvname [package]

4. Deactivate your virtual environment.

  1. To end a session in the current environment, enter the following. There is no need to specify the envname – which ever is currently active will be deactivated, and the PATH and shell variables will be returned to normal.
source deactivate

5. Delete a no longer needed virtual environment

  1. To delete a conda environment, enter the following, where yourenvname is the name of the environment you wish to delete.
conda remove -n yourenvname -all

For Information on how to install Django, https://docs.djangoproject.com/en/3.0/topics/install/

Try to always work inside in a virtual environment, to keep your project steady

Q.What do you mean by Django Project and Application?

A Django Project is a collection of applications and configurations that when combined together will make up the full web application (your complete website running with Django)

A Django application is created to perform a particular functionality for your entire web application. For example, you could have a registration app, a polling app, comments app, etc.

How to start a project ?

Now to start a project in Django, you have to type this in command line

django-admin startproject project_name

Now when you have done this, it should look something like this,

  1. __init__.py: This is a blank Python script that due to its special name lets Python know that this directory can be treated as a package
  2. settings.py: This is where you will store all your project settings
  3. urls.py: This is a Python script that will store all the URL patterns for your project. Basically the different pages of your web application.
  4. wsgi.py: This is a Python script that acts as the Web Server Gateway Interface. Help us deploy our web app to production
  5. manage.py: This is a Python script that we will use a lot. It will be associates with many commands as we build our web app!

Q. How to check if everything is running correctly ?

Run the server and check, it can be done with

python manage.py runserver

Q. What do the red warnings mean ?

That there is no connection between database and Django, this can be solved by Migration

Migration allows you to move databases from one design to another, this is also reversible. So you can “migrate” your database.

How to start a project ?

You can create a Django app, by writing

python manage.py startapp first_app

  1. __init__.py: This is a blank Python script that due to its special name lets Python know that this directory can be treated as a package
  2. admin.py: You can register your models here which Django will then use them with Django’s admin interface.
  3. apps.py: Here you can place application-specific configurations
  4. models.py: Here you store the application’s data models
  5. tests.py: Here you can store test functions to test your code
  6. views.py: This is where you have functions that handle requests and return responses
  7. Migrations folder: This directory stores database specific information as it relates to the models

When ever you make an app, always specify it in the Project settings folder,

The flow of data is transferred in Django is

[Image no longer available]

Hello world App

Let’s go step by step to create a basic, “Hello World” Http Response ,

1.You have to define your views.py file in the app directory

from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.

#A view function is index, 
#by convention we call the parameter request
def index(request):
    return HttpResponse("Hello World")

You can also insert direct HTML Code there,

def index(request):
    return HttpResponse("<em>Hello World!</em>")

2. Now you have to link it to a url by using urls.py in project directory,

Django gives you a few lines to help you understand how to get started with linking views.py to urls

"""new_project URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from first_app import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',views.index,name='index')
]

The end result will be a hello world app,

URL mappings :

Previously showed a very direct mapping from the views.py to the urls.py, but what we want is a ability to map project urls to app urls, and then maps it to app views, it just systematic.

The include() function allows us to look for a match with regular expressions and link back to our application’s own urls.py file.

Let’s go step by step,

1.We have to project urls.py a path to app urls.py

from django.contrib import admin
from django.urls import path, include
from first_app import views

urlpatterns = [
    path('', views.index, name="index"),
    path('first_app/', include('first_app.urls')),
#include here gives path to the app urls.py file
    path('admin/', admin.site.urls),
]

2.Now by default we don’t have a urls.py file in the app, but we can create one urls.py file in app

from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name='index'),
]

Q.How can we integrate this with HTML & CSS ?

Templates are a key part to understanding how Django really works and interacts with your website.

To get started with templates you first need to create a templates directory and then a sub directory for each specific app’s templates.

first_project/first_app/templates/first_app

If instead of following this convention, you want to create a global templates folder and then create app folders inside it and then store inside it.

first_project/templates/first_app

In this case, we want our Django Project to be easily transferable from one computer to another, but the DIR key will require a “hard-coded” path

We can use Python’s os module to dynamically generate the correct file path strings, regardless of the computer! We will use this os module to feed the path to the DIR key inside of the TEMPLATES dictionary. Now if you have templates folder inside the app folder, then you won’t have to deal with this. But what if you have a general templates, which are present in

Well to solve this issue, you have to go to project settings.py and modify the Template part of it

Once we’ve done that we can create an Html file called index.html. Inside this HTML file, we will insert template tags (a.k.a Django Template Variable). This will make Django able to inject content into the HTML.

Your file directory should look something to this ,

  1. static folder: contains your static content such as CSS, JS or your pictures.
  2. templates/app_name folder: contains the HTML files for a particular app

A basic display app using this information

Let’s assume this is was the HTML text

<!DOCTYPE html>
{% load staticfiles %}
{% comment %} load static file {% endcomment %}
<html>
  <head>
    <meta charset="utf-8">
    <title>This is me</title>
    <link rel="stylesheet" href="{% static "first_app/css/mystyle.css" %}"/>
  </head>
  <body>
    <h1>Hi, this is a picture of myself!</h1>
    <h2>This is the injection from views.py file   {{ insert_me }}</h2>
    <img src="{% static "first_app/images/me.jpg" %}" alt="Uh Oh, didn't show!">
  </body>
</html>

Now we have to modify our views.py file, to point it towards our HTML file,

from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def index(request):
    my_dict = {'insert_me':"Hello I am from views.py!"}
    return render(request,'first_app/index.html',context=my_dict)

If you notice, my header is red. As i have used a CSS file

Now if you notice, we can also insert static files, such as CSS files or JS files, even pictures. It has the same procedure as templates, now I recommend it to a static folder inside a particular app, otherwise, we will have to link it to static files in project settings.py,

An essential part of any website is the ability to accept information from a user and input it into a database and retrieve information from a database and use it to generate content for the user.

Django Model Template View (MTV) :

[Image no longer available]

Models define the structure of stored data, including the field types and possibly also their maximum size, default values, selection list options, help text for documentation, label text for forms, etc. The definition of the model is independent of the underlying database — you can choose one of several as part of your project settings. Once you’ve chosen what database you want to use, you don’t need to talk to it directly at all — you just write your model structure and other code, and Django handles all the dirty work of communicating with the database for you.

Django can have a variety of database options, the default option being SQLite

  1. A primary key is a unique identifier for each row in a table
  2. A foreign key just denotes that the column coincides with a primary key of another table

[Image no longer available]

An example of models.py file can be,

from django.db import models

class MyModelName(models.Model):
    """A typical class defining a model, derived from the Model class."""

    # Fields
    my_field_name = models.CharField(max_length=20, help_text='Enter field documentation')
    ...

    # Metadata
    class Meta: 
        ordering = ['-my_field_name']

    # Methods
    def get_absolute_url(self):
        """Returns the url to access a particular instance of MyModelName."""
        return reverse('model-detail-view', args=[str(self.id)])
    
    def __str__(self):
        """String for representing the MyModelName object (in Admin site etc.)."""
        return self.my_field_name

After we’ve set up the models we can migrate the database, Dango can do this entire process with a simple command:

python manage.py migrate

Then register the changes to your app, shown here with some generic “app1”:

python manage.py makemigrations app1

Then migrate the database one more time:

python manage.py migrate

For these models to be displayed in our Admin interface we need to register them to our application’s admin.py file

from django.contrib import admin
from .models import Model1,Model2,Model3
# Register your models here.
admin.site.register(Model1)
admin.site.register(Model2)
admin.site.register(Model3)

In order to interact with the admin interface, we need to create a superuser, which can be done using

python manage.py createsuperuser

It even suggests that password is either weak or strong

A simple model based app:

1.We will have to follow all the previous steps, until we have a similar directory tree to

2.Now we will work on models.py file in the app,

models have predefined filed types, which basically help us a lot, we can even further we can use specifications on predefined types such as max_length, unique, etc

class User(models.Model):
    first_name = models.CharField(max_length=128)
    last_name = models.CharField(max_length=128)
    email = models.EmailField(max_length=254,unique=True)

3.After this we will have to migrate our changes to data base ,

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

4.We can Also interact with data base via command line

5.register my model in admin .py file

from django.contrib import admin
from .models import User
# Register your models here.
admin.site.register(User)

6.Now create a super user,

python manage.py createsuperuser

7.Run the server , and got to sever/admin

python manage.py runserver

Under my application name, i see the db fields i set

It has the fields we set

8.Now if you want to populate your model with fake data to test your app,

We often sometimes need to populate or fill in the database to see how our app will act with some data, it can be done by Faker library, we can make a python script to do this,

For more info, https://faker.readthedocs.io/en/master/

import os
# Configure settings for project
# Need to run this before calling models from application!
os.environ.setdefault('DJANGO_SETTINGS_MODULE','ProTwo.settings')

import django
# Import settings
django.setup()

import random
from appTwo.models import User
from faker import Faker

fakegen = Faker()

def populate(N=5):
    '''
    Create N Entries of Dates Accessed
    '''

    for entry in range(N):

        # Create Fake Data for entry
        fake_name = fakegen.name().split()
        fake_first_name = fake_name[0]
        fake_last_name = fake_name[1]
        fake_email = fakegen.email()

        # Create new User Entry
        user = User.objects.get_or_create(first_name=fake_first_name,
                                          last_name=fake_last_name,
                                          email=fake_email)[0]

if __name__ == '__main__':
    print("Populating the databases...")
    populate(20)
    print('Populating Complete')

The function get_or_create basically get the fields from models,py and if fields are not present in models, it just creates them

Templates integration with database :

There are a few basics steps to achieving the goal of serving dynamic content to a user based off the connection of the models, views , and templates.

  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.

Template tagging :

Now i am going to define a function in app views.py

def users(request):
    user_list = User.objects.order_by('first_name')
    user_dict = {"users":user_list}
    return render(request,'appTwo/users.html',context=user_dict)

users.html page looks like,

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Users</title>
  </head>
  <body>
    <h1>Here are your users:</h1>

    {% if users %}
    <!-- To check if there are users  -->
    <ol>
      {% for person in users %}
        <!-- Iterate through Users  -->
        <li>User Info</li>
        <ul>
          <li>First Name: {{person.first_name}}</li>
          <li>Last Name: {{person.last_name}}</li>
          <li>Email: {{person.email}}</li>
          <!-- Access there fields -->
        </ul>
      {% endfor %}
    </ol>

    {% endif %}
  </body>
</html>

If all this woks properly then , it should be something like this

Django forms:

Q.Why do we need Django forms?

  1. Quickly generate HTML form widgets
  2. Validate data and process it into a Python data structure
  3. Create form versions of our Models, quickly update models from Forms

The first thing we need to do is create a forms.py file inside the application!

Then inside forms.py give fields we want inside our form

from django import forms
class FormName(forms.Form):
    name = forms.CharField()
    email = forms.EmailField()
    text = forms.CharField(widget=forms.Textarea)

Now we need to link our forms.py to views.py so we can create a view with them,

from . import forms
def form_name_view(request):
    form = forms.FormName()
    return render(request,’form_name.html’,
                            {‘form’:form})

Then we need to add the view to the app’s urls,

from basicapp import views
urlpatterns = [
url(r’formpage/’,views.form_name_view,
    name = ‘form_name’),
]

There are several ways you can “inject” the form using template tagging. You can just pass in the key from the context dictionary, some basic terminologies:

  1. HTTP stands for Hypertext Transfer Protocol and is designed to enable communication between a client and a server. The client submits a request, the server then responds.
  2. GET – requests data from a resource
  3. POST – submits data to be process to a resource.
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Forms</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
    integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
    <!-- Calling bootstrap API -->
  </head>
  <body>

    <h1>Fill out the form!</h1>
    <div class="container">
      <form method="POST">
          {{ form.as_p }}
          <!-- If you dont use .as_p it will display the form in a bit of ugly format -->
          {% csrf_token %}
          <!--Cross-Site Request Forgery (CSRF) token, which secures the HTTP POST action that is initiated on the subsequent submission of a form. 
  -->
        <input type="submit" class="btn btn-primary" value="Submit">
      </form>
    </div>

  </body>
</html>

The Django framework requires the CSRF token to be present. As, Cross-Site Request Forgery (CSRF) token, which secures the HTTP POST action that is initiated on the subsequent submission of a form.

A basic forms Application :

1.We will make a new app

2.Create a forms.py inside the app, and start to fill it

class FormName(forms.Form):
    name = forms.CharField()
    email = forms.EmailField()
    verify_email = forms.EmailField(label='Enter your email again:')
    text = forms.CharField(widget=forms.Textarea)

3. Now we will start working to create a view for it,

from django.shortcuts import render
from . import forms
# Create your views here.

def index(request):
    return render(request,'basicapp/index.html')

def form_name_view(request):
    form = forms.FormName()

    if request.method == 'POST':
        # If some one posted something back
        form = forms.FormName(request.POST)

        if form.is_valid():
            # If form is valid 
            # DO SOMETHING CODE
            print("VALIDATION SUCCESS!")
            print("NAME: "+form.cleaned_data['name'])
            print("EMAIL: "+form.cleaned_data['email'])
            print("TEXT: "+form.cleaned_data['text'])

    return render(request,'basicapp/form_page.html',{'form':form})

4..We will integrate it with urls.py of the app,

from django.urls import path
from . import views

urlpatterns = [
    path('',views.index,name='index'),
path('formpage/',views.form_name_view,name='form_name'),
]

5.Now we will go and work on HTML templates and tags

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Forms</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
    integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
    <!-- Calling bootstrap API -->
  </head>
  <body>

    <h1>Fill out the form!</h1>
    <div class="container">
      <form method="POST">
          {{ form.as_p }}
          <!-- If you dont use .as_p it will display the form in a bit of ugly format -->
          {% csrf_token %}
          <!-- It's for security of data  -->
        <input type="submit" class="btn btn-primary" value="Submit">
      </form>
    </div>

  </body>
</html>

Django has built-in validators you can conveniently use to validate your forms or to check for bots trying to disrupt your web project

Q.what if we wanted to save it to a model?

Django makes accepting form input and passing it to a model very simple!

Instead of inheriting from the forms.Forms class, we will use forms.ModelForm in our forms.py file. This helper class allows us to create a form from a pre-existing model

We then add an inline class (something we haven’t seen before) called Meta This Meta class provides information connecting the model to the form.

from django import forms
from myapp.models import MyModel
class MyNewForm(forms.ModelForm):
    # Form Fields go here
        class Meta:
            model = MyModel
        fields = # Let’s see the options!

You can choose the fields you want to modify,

  1. fields = “__all__”
  2. exclude=[‘field1’,..]
  3. fields=(“field1”,..)

You can make something like a sign up page, with a little twerks in the views.py file

from django.shortcuts import render
from .forms import NewUserForm

def index(request):
    return render(request,'appTwo/index.html')

def users(request):
    form = NewUserForm()

    if request.method == "POST":
        form = NewUserForm(request.POST)
        if form.is_valid():
            form.save(commit=True)
#If you don't want to save data put, commit=False
            return index(request)
        else:
            print('ERROR FORM INVALID')

    return render(request,'appTwo/users.html',{'form':form})

Then check if it is visible in admin interface

Templates :

We can actually use templates to have a “base” template and inherit that template in the html files. This saves you a lot of time and will help create a unified look and feel across every page of your website!

Templates are also used to solve issues with relative paths and working with variables. Templates can also help solve issues by avoiding hard-coded URL paths. Templates also come with built-in filter capabilities so you can adjust variables on the actual individual page.

Relative URLS,

How can we replace a hard coded URL path in an href with a URL Template?

The best way to use URL templates:
<a href=”basicapp/thankyou”>Thanks</a>
Can be changed to:
<a href=”{% url‘basicapp:thankyou’%}”>
   Thanks</a> 
This method requires that app_name variable to be created inside the urls.py file!

Now an simple example would be to just fix some HTML files with views and link it with urls.py

1.make html files

2.make views for them in views.py

from django.shortcuts import render

# Create your views here.
def index(request):
    context={'text':"hello world", 'number':100}
    return render(request,'basic_app/index.html', context)

def other(request):
    return render(request,'basic_app/other.html')

def relative(request):
    return render(request,'basic_app/relative_url_templates.html')

3.Connect it to urls

from django.urls import path
from . import views

# SET THE NAMESPACE!, for TEMPLATE TAGGING
app_name = 'basic_app'

urlpatterns=[
    path('relative/',views.relative,name='relative'),
    path('other/',views.other,name='other'),
]

4.connect all the HTML files with base.HTML file for a flow

base HTML file

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Base</title>
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
    integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

  </head>
  <body>
    <nav class="navbar navbar-expand-lg navbar-light bg-light">
      <div class="navbar-nav">
        <a class="navbar-brand" href="{% url 'index' %}">DJANGO</a>
        <a class="nav-item nav-link" href="{% url 'admin:index' %}">Admin</a>
        <a class="nav-item nav-link" href="{% url 'basic_app:other' %}">Other</a>
      </div>
    </nav>

    <div class="container">
    {% block body_block %}
    {# Anything outside of this will be inherited if you use extend.#}
    {% endblock %}
    </div>

  </body>
</html>

index HTML file,

{% extends "basic_app/base.html" %}

    {% block body_block%}

    <h1>Hello and welcome to the site!</h1>
      <!-- <h1>This is the index.html page</h1> -->
    <h1>{{ text }}</h1>
    
{% endblock %}

views.py file

from django.shortcuts import render

# Create your views here.
def index(request):
    context={'text':"hello world"}
    return render(request,'basic_app/index.html', context)

Inheriting HTML file :

Template inheritance allows us to create a base template we can inherit fromThis saves us a lot of repetitive work and makes it much easier to maintain the same base look and feel across our entire website!

Here are the main steps for inheritance:

  • Find the repetitive parts of your project
  • Create a base template of them
  • Set the tags in the base template
  • Extend and call those tags anywhere

Base html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Base</title>
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
    integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

  </head>
  <body>
    <nav class="navbar navbar-expand-lg navbar-light bg-light">
      <div class="navbar-nav">
        <a class="navbar-brand" href="{% url 'index' %}">DJANGO</a>
        <a class="nav-item nav-link" href="{% url 'admin:index' %}">Admin</a>
        <a class="nav-item nav-link" href="{% url 'basic_app:other' %}">Other</a>
      </div>
    </nav>

    <div class="container">
    {% block body_block %}
    {# Anything outside of this will be inherited if you use extend.#}
    {% endblock %}
    </div>

  </body>
</html>

inherited HTML file,

<!DOCTYPE html>
{% extends "basic_app/base.html" %}
    {% block body_block %}
    <h1>This is an example of template inheritance!</h1>
    <h2>Officially this is the other.html page!</h2>
    {% endblock %}

views.py file

from django.shortcuts import render

# Create your views here.
def index(request):
    context={'text':"hello world"}
    return render(request,'basic_app/index.html', context)

def other(request):
    return render(request,'basic_app/other.html')

Template Filter:

Imagine that you had some information from your model that you wished to use across various views/pages. But perhaps you wanted to make a slight edit to the information before injecting it, like string operations, or arithmetic.

Luckily Django provides a ton of easy to implement template filters that allow you to effect the injection before displaying it to the user.

This allows for flexibility from a single source!

The general form for a template filter is:
{{ value | filter:”parameter” }}

Filter HTML file

{% extends "basic_app/base.html" %}
{% load my_extras %}

    {% block body_block%}

    <h1>Hello and welcome to the site!</h1>
      <!-- <h1>This is the index.html page</h1> -->
    <h1>{{ text|cutout:"hello" }}</h1>
    <h1>{{ number|add:99 }}</h1>
    {% endblock %}

User Authentication :

This is one of the aspects of Django where there are lots of built in available tools as well as plenty of external packages that enhance functionality.

We will focus mainly on the built-in tools:

  • Users and the User Model
  • Permissions
  • Groups
  • Passwords and Authentication
  • Logging In and Out

1.Passwords :

The first thing we need to take care of is setting up our ability to authenticate a User.

  1. To do this we need to use some built-in apps and make sure they are under the INSTALLED_APPS list in settings.py

The next thing we need to do is make sure we store our passwords safely.

  1. Never store passwords as plain text!
  2. We use the default PBKDF2 algorithm with a SHA256 hash that is built-in to Django.

But if you want more security you can upgrade to even more secure hashing algorithms like bcrypt or argon2

We can also add in validator options to prevent a user from doing that.

After all these changes please migrate, make migrations and migrate again.

2.User Authorization Models:

Django’s built in tools to create User Authorization Models.

The User object has a few key features:

  • Username
  • Email
  • Password
  • First Name
  • Surname

We don’t directly inherit from user we create a one to one relationship, you can extend the basic user model.

Typically images, CSS, JS, etc. all go in the static folder of your app, User-uploaded content will go to the media folder.

A lot of the coding for working with Users and Authorization happens in the views.py file. The basic idea is that we check if there is a POST request and then perform some sort of action based off that information. Sometimes we will want to save that information directly to the database. Other times, we will set commit=False so we can manipulate the data before saving it to the database.

model.py file example.

from django.db import models
from django.contrib.auth.models import User

# Create your models here.
class UserProfileInfo(models.Model):

    # Create relationship (don't inherit from User!)
    user = models.OneToOneField(User, on_delete=models.CASCADE)

    # Add any additional attributes you want
    portfolio_site = models.URLField(blank=True)
    # pip install pillow to use this!

    profile_pic = models.ImageField(upload_to='basic_app/profile_pics',blank=True)

    def __str__(self):
        # Built-in attribute of django.contrib.auth.models.User !
        return self.user.username

3.Logins :

Once a user is registered, we want to make sure that they can log in and out of the site.

This process involves:

  • Using built-in decorators for access
  • Adding the LOGIN_URL in settings
  • Creating the login.html
  • Editing the urls.py files

There are a lot of inbuilt decorators and functionality ,

  1. from django.contrib.auth import authenticate, login, logout : used to help user login, authenticate and then logout .
  2. from django.http import HttpResponseRedirect, HttpResponse : used to display or return Http Response
  3. from django.urls import reverse : to take reverse path in the HTML file,when ever a action take place in the application
  4. from django.contrib.auth.decorators import login_required : Asking user to login before viewing an app

An example of views.py file,

from django.shortcuts import render
from .forms import UserForm,UserProfileInfoForm

# Extra Imports for the Login and Logout Capabilities
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponseRedirect, HttpResponse
from django.urls import reverse
from django.contrib.auth.decorators import login_required

# Create your views here.
def index(request):
    return render(request,'basic_app/index.html')

@login_required
def special(request):
    # Remember to also set login url in settings.py!
    # LOGIN_URL = '/basic_app/user_login/'
    return HttpResponse("You are logged in. Nice!")

@login_required
def user_logout(request):
    # Log out the user.
    logout(request)
    # Return to homepage.
    return HttpResponseRedirect(reverse('index'))

def register(request):

    registered = False

    if request.method == 'POST':

        # Get info from "both" forms
        # It appears as one form to the user on the .html page
        user_form = UserForm(data=request.POST)
        profile_form = UserProfileInfoForm(data=request.POST)

        # Check to see both forms are valid
        if user_form.is_valid() and profile_form.is_valid():

            # Save User Form to Database
            user = user_form.save()

            # Hash the password
            user.set_password(user.password)

            # Update with Hashed password
            user.save()

            # Now we deal with the extra info!

            # Can't commit yet because we still need to manipulate
            profile = profile_form.save(commit=False)

            # Set One to One relationship between
            # UserForm and UserProfileInfoForm
            profile.user = user

            # Check if they provided a profile picture
            if 'profile_pic' in request.FILES:
                print('found it')
                # If yes, then grab it from the POST form reply
                profile.profile_pic = request.FILES['profile_pic']

            # Now save model
            profile.save()

            # Registration Successful!
            registered = True

        else:
            # One of the forms was invalid if this else gets called.
            print(user_form.errors,profile_form.errors)

    else:
        # Was not an HTTP post so we just render the forms as blank.
        user_form = UserForm()
        profile_form = UserProfileInfoForm()

    # This is the render and context dictionary to feed
    # back to the registration.html file page.
    return render(request,'basic_app/registration.html',
                          {'user_form':user_form,
                           'profile_form':profile_form,
                           'registered':registered})

def user_login(request):

    if request.method == 'POST':
        # First get the username and password supplied
        username = request.POST.get('username')
        password = request.POST.get('password')

        # Django's built-in authentication function:
        user = authenticate(username=username, password=password)

        # If we have a user
        if user:
            #Check it the account is active
            if user.is_active:
                # Log the user in.
                login(request,user)
                # Send the user back to some page.
                # In this case their homepage.
                return HttpResponseRedirect(reverse('index'))
            else:
                # If account is not active:
                return HttpResponse("Your account is not active.")
        else:
            print("Someone tried to login and failed.")
            print("They used username: {} and password: {}".format(username,password))
            return HttpResponse("Invalid login details supplied.")

    else:
        #Nothing has been provided for username or password.
        return render(request, 'basic_app/login.html', {})

The general flow should during user authentication should be:

  1. First user signs up on the website
  2. User then logins in to the website
  3. Then we is able to see specific content for the user

Class-based views:

Django provides really powerful tools to use OOP and classes to define views. The CBV offers great functionality and for most experienced users of Django, it is their default choice for creating views.

Hello world Class Based View app

1.Template views :

We need to add in a .as_view() call off the class, this is an inherited method from the View

Function Based View
def index(request):
return render(request,'index.html')

Class Based Template View
 class IndexView(TemplateView):
template_name = 'index.html'

2.Class vs function views :

Original Function View:
#
# def index(request):
#     return render(request,'index.html')

class IndexView(TemplateView):
    # Just set this Class Object Attribute to the template page.
    # template_name = 'app_name/site.html'
    template_name = 'index.html'

Now in urls.py, we need to use .as_view()

#function view
path(' 'views.index)

#class view
path(' ',views.IndexView.as_view())

Class based methods to help you :

  1. get_context_data(**kwargs): Returns a dictionary representing the template context. The keyword arguments provided will make up the returned context. Example usage in views.py file
class IndexView(TemplateView):
    # Just set this Class Object Attribute to the template page.
    # template_name = 'app_name/site.html'
    template_name = 'index.html'

    def get_context_data(self,**kwargs):
        context  = super().get_context_data(**kwargs)
        context['injectme'] = "Basic Injection!"
        return context

Detail and List View :

Often when we have models, we want to either list the records from the model, or show details of a single record.So common that Django has some generic view classes you can inherit to very quickly display information from your model.

They return class as class_list context dictionary or you could use

context_object_name='word followed by _ list'

An example views.py file,

from django.views.generic import (View,TemplateView,
                                ListView,DetailView)
                             
class SchoolListView(ListView):
    # If you don't pass in this attribute,
    # Django will auto create a context name
    # for you with object_list!
    # Default would be 'school_list'

    # Example of making your own:
    # context_object_name = 'schools'
    model = models.School

class SchoolDetailView(DetailView):
    context_object_name = 'school_details'
    model = models.School
    template_name = 'basic_app/school_detail.html'

school list html file

{% extends "basic_app/basic_app_base.html" %}
{% block body_block %}
  <div class="jumbotron">

    <h1>Welcome to the List of Schools Page!</h1>
      <ol>
        {% for school in school_list %}
          <h2><li><a href="{{school.id}}/">{{school.name}} </a></li></h2>
        {% endfor %}
      </ol>

  </div>

{% endblock %}

school detail html file

{% extends "basic_app/basic_app_base.html" %}
{% block body_block %}
  <div class="Sjumbotron">
    <h1>Welcome to the School Detail Page</h1>
    <h2>School Details:</h2>
    <p>Id_num: {{school_details.id}}</p>
    <p>Name: {{school_details.name}}</p>
    <p>Principal: {{school_details.principal}}</p>
    <p>Location: {{school_details.location}}</p>
    <h3>Students:</h3>

      {% for student in school_details.students.all %}
        <p>{{student.name}} who is {{student.age}} years old.</p>
      {% endfor %}

  </div>

{% endblock %}

Settings up app_name in urls.py file is really important, as it helps during injection of content into HTML files

Now we can also set up primary keys in the fields and access information based on a particular primary key similar like regular expressions

  path('<int:pk>/',views.SchoolDetailView.as_view(),name='detail'),

CRUD functionality :

Django has class based views to simplify this entire process for you!

There will be a lot of interaction between your urls.py, views.py, models.py, and template files!there will be a lot of interaction between your urls.py, views.py, models.py, and template files!

The modified views.py, use1.def get_absolute_url(self): it tells django to go to a view after any crud functions is performed :

from django.db import models
from django.urls import revers

# Create your models here.
class School(models.Model):
    name = models.CharField(max_length=256)
    principal = models.CharField(max_length=256)
    location = models.CharField(max_length=256)

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse("basic_app:detail",kwargs={'pk':self.pk})

class Student(models.Model):
    name = models.CharField(max_length=256)
    age = models.PositiveIntegerField()
    school = models.ForeignKey(School,related_name='students',on_delete=models.CASCADE)

    def __str__(self):
        return self.name
  1. create: specify the fields user can create and model
  2. update: specify the fields user can modify and model
  3. delete: specify the sucess url and model

success url means once you have deleted the models, go to that url. WE use reverse_lazy as we only want to go back to url after it has sucessfuly been deleted

views.py file,

from django.shortcuts import render
from django.urls import reverse_lazy
from django.http import HttpResponse
from django.views.generic import (View,TemplateView,ListView,DetailView,                               CreateView,DeleteView,                       UpdateView)

class IndexView(TemplateView):
    # Just set this Class Object Attribute to the template page.
    # template_name = 'app_name/site.html'
    template_name = 'index.html'

    def get_context_data(self,**kwargs):
        context  = super().get_context_data(**kwargs)
        context['injectme'] = "Basic Injection!"
        return context

class SchoolListView(ListView):
    # If you don't pass in this attribute,
    # Django will auto create a context name
    # for you with object_list!
    # Default would be 'school_list'

    # Example of making your own:
    # context_object_name = 'schools'
    model = models.School

class SchoolDetailView(DetailView):
    context_object_name = 'school_details'
    model = models.School
    template_name = 'basic_app/school_detail.html'

class SchoolCreateView(CreateView):
    fields = ("name","principal","location")
    model = models.School

class SchoolUpdateView(UpdateView):
    fields = ("name","principal")
    model = models.School

class SchoolDeleteView(DeleteView):
    model = models.School
    success_url = reverse_lazy("basic_app:list")

urls.py file

from django.urls import path
from . import views

app_name = 'basic_app'

urlpatterns = [
    path('',views.SchoolListView.as_view(),name='list'),
    path('<int:pk>/',views.SchoolDetailView.as_view(),name='detail'),
    path('create/',views.SchoolCreateView.as_view(),name='create'),
    path('update/<int:pk>/',views.SchoolUpdateView.as_view(),name='update'),
    path('delete/<int:pk>/',views.SchoolDeleteView.as_view(),name='delete')
]

It should look similar to this,

Using primary keys to access values of particular instance or object of the class

Debug toolbar :

Firstly install django-debug -toolbar, then add it into project settings.py file

Then we will got into urls.py, add settings .Debug into url paterns

from django.contrib import admin
from django.urls import path, include
from appTwo import views
from django.conf import settings

urlpatterns = [
    path('', include('appTwo.urls')),
    path('admin/', admin.site.urls),
]

if settings.DEBUG:
    import debug_toolbar
    urlpatterns=[
        path('debug/',include(debug_toolbar.urls))
    ] +urlpatterns

After this we will go back into settings.py file in project folder

Then finally we hace to declare internal_ips

Customizing Admin interface :

We have created simple app for videos , the admin interface will look like

Now instead of showing object numbers it’s showing different data if we modify the models.py in the app

class Customer(models.Model):
    first_name=models.CharField(max_length=256)
    last_name=models.CharField(max_length=256)
    phone=models.PositiveIntegerField()

    def __str__(self):
        return self.first_name+' '+ self.last_name

We can modify

  1. admin’s base html page
  2. order of fields
  3. adding search bar
  4. add filters
  5. allowing editable list view
  6. adding fields
from django.contrib import admin

# Register your models here.
from . import models
class MovieAdmin(admin.ModelAdmin):
    fields=['release_year','title','length']

    search_fields=['title']

    list_filter=['release_year','length']

    list_display=['release_year','title','length']

    list_editable=['length']

admin.site.register(models.Customer)
admin.site.register(models.Movie,MovieAdmin)

For more information,

  1. https://docs.djangoproject.com/en/3.0/
  2. https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Introduction

For checking out actual code for all these examples, check my GitHub repositories

  1. Basic coding example, each folder has a specific demo which can be found in their commits.
  2. Advanced Django projects, which involve CSS + JS +Media.