Django

Introduction 

  • High level python web framework
  • Free and open source
  • Rapid Application Development
  • Security
  • Scalable
The web framework for perfectionist with deadlines

Ridiculously fast
  • From concept to completion as quickly as possible
  • form for quick setup
  • Generic view to write less code

Fully loaded
  • Authentication
  • content administration
  • site maps
  • RSS feeds, and many more task
Reassuringly secure
  • SQL injection 
  • cross site scripting
  • cross site request forgery and clickjacking
Exceedingly scalable
some of the busiest sites on the planet use django's ability to quickly and flexibly scale to meet the heaviest traffic demands

Incredibly versatile
from content management system to social network to scientific computing platforms

Installation 
• Installing an official release with pip

#we will install with pip

pip install django

#confirm installation from pip

pip list
or
pip freeze



url is like a entry point for our applications

Architecture
Three major components: MVC 
1. Model 
• Mediator between website interface and database 
• Implements logic for application's data domain 
Eg: when you send information to the server, you are sending information to Controller which then sends it to the Model (which may apply business logics) and stores it to the database


2. View 
• User Interface of the web-application 
• Contains parts like HTML, CSS, JS . 
E.g.: when you go to any link, the new webpage that website generates is the View

3. Controller 
• Main control component 
• Handles user interaction, selects a View accordingly and also applying the Model component 
E.g.: When you go to a link, controller will process this request, applies necessary data from Model component and sends it to the View

MVT Pattern 
• Django is mainly an MVT(Model-View-Template) framework. 
• View = controller 
• Template = views



Creating a project
 • Let's create a project helloworld 
    • django-admin startproject helloworld




manage.py 
• manage.py is automatically created with new project 
• Command line utility for managing django (which could be done through django-admin as well)
 • Run manage.py 
• python manage.py [will give you list of commands that can be used] 
• Some useful commands 
• runserver [runs a local development server. python manage.py runserver] 
• startapp [creates a new app. python manage.py startapp world # will create a new app named world]

Running a development server 
• python manage.py runserver

Django Apps
 • python manage.py startapp world(app_name)

Registering apps
 • Register this newly created 'world' app to django project 'helloworld'


Creating hello world view 
• Let's assume a URL 
 ~/home • When calling this URL should return a simple response 
• So, Create a view which will return 'hello world'

# world/ views . py 
from django.http import HttpResponse 
def home( request):
     response = HttpResponse( ) 
     response. content = "Hello World" 
     return response 


# or can be written as # return HttpResponse( "Hello World" )

URL's designing 

• Keep mobile and desktop URL consistent as much as possible 
• Keep it short 
• Don't [/home/profile/all-users/self-user/details/address/] 
• Do [/home/profile/self-user/address] 
• or, [/profile/self-user/address] 
• Separate words with hyphens
 • Don't [ /home/profileaddress/] 
• Do [/home/profile-address/]
• Avoiding use of Database PK in URLs is always a good practice 
• Don't [/user/l/] [/user/2/] 
• Instead use slug, hashids or UUID 
• [/user/ram-bahadur/] 
• [/user/2h76bnv/]
 • [/user/6d414752-79a7-4846-a735-4288bc454b41/] 
Note: slugs are SEO friendly

• Pagination best practices
Don't 
    • [/users/page-1/] 

     [/users/page-2/] 
• Do 
    • [/users/?page=1] 
    • [/users/?page=2]

in above ?page=1 is called as query params 
Note: Limit Offset paginations can also be used [/users/?limit=100&offset=10]

• Other common approach 
• /profile/ram-bahadur/followers/ 
• profile/ram-bahadur/following/
• accounts/change-password/


Path Converters 
• str 
• slug 
• uuid 
• path 

Good news: You can create your own path converters

Using regular expressions

Including other URLconfs


Including other URLconfs


What the URLconf searches against 
• Doesn't include GET or POST parameter, or the domain name 
• https://example.com/helloworld/, URLconf will look for helloworld/ 
• https://example.com/helloworld/?page=l, URLconf will look for helloworld/ 
• Doesn't look for the HTTP request method. All request methods will land on the same view function


A simple view


Returning errors 404 ?



Allow HTTP methods on view function


customs error codes





HttpRequest objects 
• Attributes 
• HttpRequest.scheme (string to represent scheme of request. http or https)
 • HttpRequest.path (full path but not including scheme and domain) (string to represent HTTP method used in request) 
• HttpRequest.method (dict like obj containing all HTTP GET parameters) 
• HttpRequest.GET (dict like obj containing all HTTP POST parameters) 
• HttpRequest.POST (a dict like obj containing all uploaded files)
 • HttpRequest.FlLES 
• HttpRequest.headers, HttpRequest.COOKlES, HttpRequest.content_type

• Methods 
    • HttpRequest.get_host() 
        • Eg: 127.0.0.1:8000 
    • HttpRequest.get_port() 
    • HttpRequest.get_full_path() 
        • Eg: /profile/?username=ram 
    • HttpRequest.is_secure() [return True if request was made with HTTPS] 
    • HttpRequest.is_ajax()


serialization is the process of changing the object to the json response

Django Templating 
• Convenient way to generate HTML dynamically 
• A template contains the static parts of the desired HTML output as well as some special syntax describing how dynamic content will be inserted 
• Django ships built-in backends for its own template system, creatively called the Django template language (DTL), and for the popular alternative Jinja2





Note 
• To pass any value from view to the template we pass it as context. Context is a dict of key:value 
• You can always give as much template directory on your settings.py. But since, APP_DlRS=True, the template finder will search inside our INSTALLED_APPS and check if the template exists in templates folder

Loading template and returning to the client


thanks god django has got shortcuts

def index(request):
    return render(request, template_name, context)


Grabbing context in django
Variables 
• Outputs value from the context
 • Variable are surrounded by 
E.g.: My first name is {{ first_name}} My last name is {{ last_name }} 
// With a context of {'first_name': 'John', 'last_name': 'Doe'}, // this template renders to: My first name is John. My last name is Doe.

Tags 
• Tags provide arbitary logic in the rendering process 
• Tags are surrounded by {% E.g.: {% csrf_token %} 
# some tags require ending tags
 {% if user.is_authenticated %} Hello, {{ user.username }}.{% endif %}

Filters 
• Filters transform the values of variables and tag arguments {{ name Ititle # With a context of {name: 'ram bahadur'}, this template renders to: Ram Bahadur


Comments 
• Comments are placed in 
{# • Comments look like #}
 {# I am comment #}

Django Models 
• A model is the single, definitive source of information about your data. 
• It contains the essential fields and behaviors of the data you're storing
• Each model is a Python class that subclasses django.db.modeIs.ModeI 
• Each attributes of the model represents a database field 
• With all this, Django gives us an automatically generated database- access API that lets us create, retrieve, update and delete objects
• This example model defines a Person, which has a first_name and last_name: 
• Each field is specified as class attributes, and each attributes maps to a database column

Which would create database table like this
Notes: 
• The table name is automatically derived from model metadata which can be overridden 
• The id field is added automatically by default, but can be customized or this behavior can be overridden

Where are databases? 
• Django officially supports 
• PostgreSQL • PostgreSQL 9.5 and higher and psycopg2 2.5.4 or higher 
• MariaDB • Added in Django 3.0, Django. Supports MariaDB 10.1 
• MySQL • Django supports MySQL 5.6 and higher. and requires mysqlclient 1.3.13 .
Oracle • Django supports Oracle Database Server versions 12.2 and higher. Version 6.0 or higher of the cx Oracle Python driver is required. 
• SQlite • Django supports SQLite 3.8.3 and later.

SQlite DB connection

migrations 
• Migrations are Django's way of propagating changes you make to your models into your database schema 
• available commands: 
• migrate, which is responsible for applying and unapplying migrations.
• makemigrations, which is responsible for creating new migrations based on the changes you have made to your models. 
• sqlmigrate, which displays the SQL statements for a migration. 
• showmigrations, which lists a project's migrations and their status.

Model fields 
• models.CharField 
• models.BooleanField 
• models.DateField 
• models.DateTimeField 
• models.EmailField 
• models.FileField 
• models.lmageField 
• models.lntegerField and many more...

A simple model


Field options
• null (default=False) 
• blank (default=False) 
• db column 
• default (can be a value or a callable object)
• unique 
• validators 
• help_text (extra help text to be displayed with form widget) and ...


ORM (Object Relational Mapper) 
• ORM: able to write queries (simple or complicated) using the object- oriented paradigm of your preferred programming language 
• Abstracts away the database system, so switching from MySQL to PostgreSQL is pretty easy 
• But, initial configurations can be a headache [Thanks to Django, it does this for us]

Creating objects 
• ContactNumber.objects.create(number="984111111")

Retrieving objects 
• ContactNumber.objects.get(number="984111111") 
• Get a single object, will throw exception if multiple objects with 984111111 is found 
• ContactNumber.objects.all() 
• retrieve all
• ContactNumber.objects.filter(number="984111111") 
• Retrieve multiple objects with filter 

Updating 
• Obj = ContactNumber.objects.get(number="984111111")
• Obj.name = "Ram" # name should be a field on ContactNumber 
• Obj.save()

Deleting 
• Single object delete 
• Obj = ContactNumber.objects.get(number="984111111") 
• Obj.delete() 
• Delete can be used with .filter too 
• ContactNumber.objects.filter(number="98411411411").delete()

• You can always switch to Raw SQL 
• Person.objects.raw( 'SELECT id, first _ name, last_name, birth_date FROM myapp_person' )
Note: You can also execute SQL directly

Types of relationships in RD design 
• one-to-one 
• one-to-many (or many-to-one) 
• many-to-many


One-to-one 
• A row in table A can have only one matching row in table B 
• All data stored on table B could have been stored in table A

One-to-many 
• Most common, a row in table A can have many matching row in table B, but a row in table B can have only one matching row in table A

Many-to-many 
• Row in table A can have many matching rows in table B and vice versa 
• A one-to-many relationship linked by an intermediate table




Django relationship field 
• Models.ForeignKey 
 Models.OneToOneField 
• Models.ManyToManyField


one to one field

form django.db import models
  

class UserDetails(models.Model):
        first_name=models.CharField(max_length=250)
        last_name=models.CharField(max_length=250)
        address=models.CharField(max_length=250)

class User(models.Model):
        email= models.EmailField)
        password=models.CharField(max_length=250)
       user_detail=models.OneToOneField(UserDetail,on_delete=models.CASCADE)


Aruguments: on _ delete 
• When an object referenced by ForeignKey is deleted, Django will emulate the behaviour of SQL constraint specified by the on_delete argument 
• Possible values: 
    • models.CASCADE 
    • models.PROTECT 
    • models.SET NULL and .


• For e.g.: you have a nullable field, and you want to set it to null when the referenced object is deleted

user=models.ForeignKey(
    User,
    models.SET_NULL,
    blank=True,
    null=True
)

Foreign Key

form django.db import models

class Address(models.Model):
        name=models.CharField(max_length=250)
        lat=models.CharField(max_length=250)
        log=models.CharField(max_length=250)


class User(models.Model):
        email=models.EmailField()
        name=models.CharField(max_length=200)
      address=models.ForeignKey(Address,on_delete=models.SET_NULL,null=True)

ManyToManyield

form django.db import models

class Address(models.Model):
        name=models.CharField(max_length=250)
        lat=models.CharField(max_length=250)
        log=models.CharField(max_length=250)


class User(models.Model):
        email=models.EmailField()
        lat=models.CharField(max_length=200)
        address=models.ManyToMany(Address)


Arguments: related _ name
 • Specifies the name of the reverse relation 
• Defaults to [in lower case]: 
    • [name of class]_set for ForeignKey 
    • [name_of_classl for OneToOneField

Models meta 
• db table 
• ordering 
• abstract and


for example

class ContactNumber(models.Model):
        name=models.CharField(max_length=250)
        lat = models.CharField(max_length=250)
        long=models.CharField(max_length=250)

        class Meta:
                db_table='contact_numbers'    #table name will be contact_numbers
                ordering=['name]  #asc order , use - for desc ordering

Abstract model (abstract=True) 
• Useful when we want to put some common information into several other models • This model will not create any database table, instead when it is used as a base class for other models, its field will be added to those of the child class (simple python inheritance)


from django.db import models

class CommonInfo(modes.Model):
        name=models.CharField(max_length=100)
        age = models.PositiveIntegerField()

        class Meta:
                abstract = True

class Student(CommonInfo):
        home_group=models.CharField(max_length=5)

Static and media files

static files

Managing static files (images, JS, CSS) 
• Configuring static files 
• Make sure django.contrib.staticfiles is included in your INSTALLED APPS • In your settings.py file, add STATIC_URL 
• For e.g. STATIC_URL = '/static/' 
• Store your static files in folder called static in your app

• Serving static files 
• If we use django.contrib.staticfiles as explained in previous slides, runserver command will automatically serve static files when DEBUG is set to True DEBUG=True on settings.py ] 
• So this means, you do not need to create a new URL or view to serve these static files. Django does this for us 
• But this way is not suitable for production use. We will use a different technique to serve our static Note: if you don't have django.contrib.staticfiles in INSTALLED APPS the you can still manually serve the static files

Static files Deployment 
• django.contrib.staticfiles provides a command for gathering static files from different applications of the project in a single directory so you can serve them easily 
• Steps: 
•Set STATIC ROOT on settings.py 
• STATIC_ROOT = '/var/www/static/' 
•Run collectstatic command 
• python manage.py collectstatic 
•Use any webserver of your choice to serve the files from this single directory


Django Forms
HTML forms 
• A collection of elements inside <form> </form> 
• Which allows visitor to input data or manipulate data and send the information back to server 
• A form must specify two things 
    • The URL (action attribute) 
    • The HTTP (method attribute)

GET and POST 
• GET and POST are only HTTP methods to use when dealing with forms 
• POST 
• In which browser bundles up the form data, encodes it for transmission, and sends it to the server and receives back the response 
• GET 
• Bundles the submitted data into a string and composes a URL based on it. E.g. https://example.com/send?name=ram&age=30

In get there will be query params ?
in post there will be request body

Django forms 
• Prepare data to make it ready for rendering 
• Creating HTML forms for the data 
• Receiving and processing submitted forms and data from the client

Creating form in Django 
• It's good to place forms code on forms.py under your django application

• We defined a form class with a single field (name) 
• We added a human friendly label to the field. This will appear in the <label> when it's rendered 
• The field maximum allowed length is defined by max_length 
• puts maxlength=100 on the HTML <input> 
• When Django receives the data, it will validate the length of the data
• A Form instance has is_valid() method 
• which will run all validations. 
• When it's called, if all fields contain valid data then it will 
    • Return True 
    • Place the form's data in cleaned data attribute
• When rendering our form it will look like


But, • It doesn't include <form> tags or a submit button


to exclude csrf error
{% csrf_token %}
cross site request forgery protection
csrf_token is required when submitting form via POST
with csrf protection enable

{{ form }} in template is enough but, 
• There are other output options for <label> <input> pairs 
    • {{ form.as_table }} will render them as table cells wrapper in <tr> tags 
    • {{ form.as_p }} will render them wrapped in tags 
    • {{ form.as_ul will render them wrapped in <li> tags 

Note: You will have to provide surrounding <table> or <ul> tag yourself 
Note: Each form field has an ID attribute set to id <field-name>

Rendering fields manually 
• Each field is available as an attribute of form using: 
• {{ form.field_name }} 
• {{ form.non_field_errors }} used to output non_field_errors



Using form to validate data • Form.clean() [used to clean and validate fields that depends on each other]




for details go to ccbv.co.uk

Class base view
in path
path('pah_name',Class_base.as_view(),name='class')

class Class_base(ListView):
    queryset=Model_name.objects.all()
    template_name='user/user.html'
    context_object_name=obj



django class based biews


what are class based views ?(CBV's)

views - take in request and return response

class based views( implement view as python object)

Dont replace function based views
benefits;
promote code reuse -inheritance
mixins
DRY - help reduce code duplication
code structuring

Difficulties / challenges
level of abstraction (the magic)

django class based views
django provides example views classes
built in /Pre written views - (generic views)
accessed via ------> from django.views.generic


TemplateView()
when you might use Template.VIew()?
generic view to show static page
pages that use GET requests
not generally used
show a form on a page
create/updates information(better option)


using directly within URL Configuration

templateVIew()
pass changes to class based view as_view()
arguments passed to as_view() will override atributes set on the class
example 
we set template_name on the templateview

django.view.generic.base.TemplateResponseMixin
django.view.generic.base..ContextMixin
django.view.generic.base.View



RedirectView
redirect to a given URL
Inherited method and attributes
django.view.generic.base.View


DetailView
application
  • Present detail of a single model instance
  • intended to be used with one object only
  • must be called - object pk or a slug in the URLconf
  • path('list/<int:pk>/',views.ABCDetailView.as_view(),name="abc")
Not typically used for
  • Page has a form
  • used to return, update or data creation
  • DetailView shold not be paginated

Detail view is inherited from the following

• django.views.generic.detail.SingleObjectTemplateResponseMixin
• django.views.generic.base.TempIateResponseMixin 
• django.views.generic.detail.BaseDetailView 
• django.views.generic.detaiI.SingIeObjectMixin 
• django.views.generic.base.View


DetailView MRO 
• Method Flowchart 
• setup()
• dispatch() 
• http_method_not_allowed() 
• get_template_names()
• get_slug_field() 
• get_queryset() 
• get_object() 
• get_context_object_name() 
• get_context_data() get() 
• render_to_response()


Template Inheritance

The most powerful and the most complex part of Django template engine is template inheritance. Template inheritance allows us to build a base skeleton template that contains all common elements of your site and defines blocks that child templates can override

click here to learn more

Comments