Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 56

Chapter 3

Django Admin/Migrations and Form


Processing
Fullstack development – Front End

Technologies used for Front End

• Html

• CSS

• Javascript

• Ajax

• JQuery
Fullstack development – Back End

• Django

• Python
Dijango
Django Features
MVC Architecture
MVC

Model :- This handles your data representation, it serves as an interface to the data
stored in the database itself, and also allows you to interact with your data without
having to get perturbed with all the complexities of the underlying database.

View :- As the name implies, it represents what you see while on your browser for a
web application or In the UI for a desktop application.

Controller :- provides the logic to either handle presentation flow in the view or
update the model’s data i.e it uses programmed logic to figure out what is pulled
from the database through the model and passed to the view,also gets information
from the user through the view and implements the given logic by either changing
the view or updating the data via the model , To make it more simpler, see it as the
engine room.
Django MTV Architecture
MVT Architecture
MVT Architecture

1.Model : This is essentially the Database Layer. Every app in Django has a models.py file where we
define the structure and schema of the Database Tables. Django then applies this schema onto our actual
Database by generating SQL queries based on our configurations in models.py (this generation and
applications of SQL queries by Django is called “migration”)

2.Template : This is the Presentation Layer which contains the Front-end code of the site along with
gaps/ spaces for data to be filled in. These gaps are dynamically filled in by the view function, after
fetching data from the DB and processing it based on the HTTP request received.

3.View : This is Data preparation/ organisation layer and also the main controller in Django. The view
functions receive HTTP requests from the client and based on the request the view function will then
query required data from the database, organize it in the required format and send it to templates to fill
the gaps. In case of a POST HTTP request, the view function receives the data input by the user,
processes that input and performs Add, Update or Delete Operations on the Database.
Django Flow
Registering models in admin.py

from django.contrib import admin

from lab22.models import Students,Course

# Register your models here.

admin.site.register(Students)

admin.site.register(Course)
Create Admin User

py manage.py createsuperuser
Django Admin interface

 Automatically build CRUD for models


 Lot of repetitive tasks is avoided
 Can be customized
 It is an authentication based dashboard which
restricts to privileged administrators
 Has powerful features of search and filter
Admin GUI

Django Admin is a really great tool in Django, it is actually a CRUD* user interface of all your models!
Users
Admin Groups
Models
Add Data
Edit Data
History of data
Models

In Django, data is created in objects, called Models, and is actually tables in a database.

It describes the table fields.

class Project(models.Model):

student=models.ForeignKey(Students,on_delete=models.CASCADE)

topic=models.CharField(max_length=100) => Text Fields

languages=models.CharField(max_length=100)

duration=models.IntegerField() => Integer fields


Django Model Fields
Django Model Fields
Django Model Relationship Fields
Django Model Field Options
Migrations

Run migrate command to create the table in the database.

python manage.py makemigrations lab22

Django creates a file describing the changes and stores the file in the /migrations/ folder:
Migrations
Thee table is not created yet, you will have to run one more command, then Django will create and execute an SQL statement, based on the content of the new file in
the /migrations/ folder.

View the SQL

you can view the SQL statement that were executed from the migration above. All you have to do is to run this command, with the migration number:

python manage.py sqlmigrate lab22 0001

Migration command

Below command creates tables in the database

python manage.py migrate


Dijango ORM model
ORM Model
DB operations

Adding objects
modelobject.save()

Retrieving objects
modelobject.objects.all()
QuerySet with all records
modelobject.objects.filter(filter condition)
Query Set with filtered records
modelobject.objects.get(id condition)
Get specific record
DB operations

Modifying object
First get the object with
a=modelobject.objects.get(id condition)
Then call, a.save()

Deleting objects
First get the object with
a=modelobject.objects.get(id
condition)
Then call, a.delete()
Tables in the database
Model Forms
Sample html forms

<form action="/action_page" method=“post”>

<label for="fname">First name:</label><br>

<input type="text" id="fname" value="John"><br><br>

<input type="submit" value="Submit">

</form>
Forms – Get and Post

GET and POST are the only HTTP methods to use when dealing with forms.
Django’s login form is returned using the POST method, in which the browser
bundles up the form data, encodes it for transmission, sends it to the server, and
then receives back its response.

GET, by contrast, bundles the submitted data into a string, and uses this to
compose a URL. The URL contains the address where the data must be sent, as
well as the data keys and values. You can see this in action if you do a search in
the Django documentation, which will produce a URL of the
form https://docs.djangoproject.com/search/?q=forms&release=1.

GET and POST are typically used for different purposes.


Django Forms Flow
Django Forms

At the heart of this system of components is Django’s Form class. In much the same way that a Django model
describes the logical structure of an object, its behavior, and the way its parts are represented to us, a Form class
describes a form and determines how it works and appears.

A ModelForm maps a model class’s fields to HTML form <input> elements via a Form;

The Django's Form class gives a logical representation of an HTML form, defines how it should behave and how it
appears in the HTML.
Model Forms

Most of the times our user inputs are very close to our models, after all
the input data is stored in models. Django provides us with Model
Forms, the forms that can be built from models.

Building a form from a model is really easy. We just need to extend the
django.forms.ModelForm class, specify the model (that we want to built
the form from) in the Meta class and specify the fields to include
Templates

• Django provides a convenient way to generate dynamic HTML pages by using its
template system.

• A template consists of static parts of the desired HTML output as well as some
special syntax describing how dynamic content will be inserted. Introduction
OWASP Top 10
Web application without CSRF
Web application with CSRF
Templates
Templates Configuration in Settings.py
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,
'lab21/templates'),os.path.join(BASE_DIR,),os.path.join(BASE_DIR, 'lab31/templates'),],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
Template Tag functions
autoescape Specifies if autoescape mode is on or off
block Specifies a block section
comment Specifies a comment section
csrf_token Protects forms from Cross Site Request Forgeries
cycle Specifies content to use in each cycle of a loop
debug Specifies debugging information
extends Specifies a parent template
filter Filters content before returning it
firstof Returns the first not empty variable

for Specifies a for loop


if Specifies a if statement
ifchanged Used in for loops. Outputs a block only if a value has changed since the last iteration
include Specifies included content/template
load Loads template tags from another library
lorem Outputs random text
now Outputs the current date/time
regroup Sorts an object by a group
resetcycle Used in cycles. Resets the cycle
spaceless Removes whitespace between HTML tags
templatetag Outputs a specified template tag
url Returns the absolute URL part of a URL
Django Views
Django views are Python functions that takes http requests and
returns http response, like HTML documents.

A web page that uses Django is full of views with different tasks
and missions.
Django Urls

Django has his own way for URL mapping and it's done by editing
your project url.py file.

When a user makes a request for a page on your web app, Django
controller takes over to look for the corresponding view via the
url.py file, and then return the HTML response.
Lab Program – Changes to models.py in lab22
Make following changes to models.py in lab22 subfolder:
from django.db import models
from django.forms import ModelForm

# Create your models here.

class Project(models.Model):
student=models.ForeignKey(Students,on_delete=models.CASCADE)
topic=models.CharField(max_length=100)
languages=models.CharField(max_length=100)
duration=models.IntegerField()
def __str__(self):
return self.topic

class ProjectReg(ModelForm):
required_css_class = 'required'
class Meta:
model=Project
fields=('student','topic','languages','duration')
Migration of the models

python manage.py makemigrations lab22


python manage.py sqlmigrate lab22 0001
python manage.py migrate
Create a HTML file project_reg.html inside templates subfolder

{% if submitted %}
<p class="success">
Project Registration is successful. Thank you.
</p>
{% else %}
<form action="" method="post" novalidate>
<table>
{{ form.as_table }}
<tr>
<td>&nbsp;</td>
<td><input type="submit" value="Submit"></td>
</tr>
</table>
{% csrf_token %}
</form>
{% endif %}
Make following changes to views.py:

from django.shortcuts import render


from django.http import HttpResponse,HttpResponseRedirect,FileResponse
from lab22.models import ProjectReg

def add_project(request):
submitted = False
if request.method == 'POST':
form = ProjectReg(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/add_project/?submitted=True')
else:
form = ProjectReg()
if 'submitted' in request.GET:
submitted = True
return render(request, 'project_reg.html', {'form': form, 'submitted': submitted})
Make following changes to urls.py in first folder

from django.contrib import admin


from django.urls import path
from lab22.views import add_project
urlpatterns = [
path('admin/', admin.site.urls),
path('add_project/',add_project),
]

You might also like