Category: Django

What is Django?

What is Django?

What is Django : Django is an free open source, web framework. Django was created in the fall of 2003. It is written in python and follows MVT ( Model, View , Template ) architectural pattern.

what is Django
what is Django

It is an high level python framework, designed to create rapid web-applications from concept to completion as quickly as possible. Now a days, various websites built in Django including Pinterest, Instagram, Bit Bucket and more.

It solves various problems and handles user’s code. We can connect front-end to the backend using this framework. There is also an  good written documentation for django, for more details you can check  on the official Django docs on  https://www.djangoproject.com/  .

The name Django comes from the guitarist Django Reinhardt.


Why we need Django?

As we know that python is an powerful and easy programming language. To make programming more easier, we need an framework. So know the question arises that what is an framework. Framework designed to make development faster and easy. They contains a set of predefined modules and functions that we just need to call and use rather than to create.

Django follows the statement “Don’t Repeat Yourself”. It means it avoids the duplication(repetition) of code and fast leads to fast development. So instead of writing all code yourself, Django provides various code modules and libraries, that makes a website more easier and faster to create.


Features of Django

Here are common features of Django:

  1. Fast web development
  2. Automatic Administration Interface
  3. Support Object Relational Mapper
  4. Code Reusability
  5. Various built in Modules
  6. Handles JSON, XML conversion
  7. Structured and Light-weighted etc.

How Django Works?

Here, i just give you an brief idea of how Django works. Here is the simple discussion, the way how Django works:

  1. An user requests a web page(send request)
  2. Server receives the request and then it will ask from Django
  3. In the request there will be an address of requested page. Django will matches this address to all addresses which it contains just like as an postman.
  4. This process is done by the Django’s URL resolver.
  5. The Django view will return the requested page if found otherwise 404 message.
  6. Then this page will served to the user

The above discussion is just let you know the basic idea of how Django works. I have mention above, that Django is an MVT system. If you want to learn Model View Template, visit the link below. Thanks!!!

Django Model Template and Views (Django MTV)

Django Model Template and Views (Django MTV)

Django Model Template and Views (Django MTV)

Django is often referred to as an MTV framework (Django MTV ) , where MTV works parallelly to develop a full stack web application. You can see the basic idea of MTV in diagram below:

Django MTV
Django MTV

Model

  M stands for Model. Model is an data access layer , where the application’s data stored . Basically django comes equipped with SQLlite whi ch is light weighted database, and is sufficient to stores application’s data. But if in case , other database required, then django can connect to a variety of SQL engine backends. In project’as settings.py file you can edit the ENGINE parameter used for Databases.

Django models created in app’s models.py file and then connected to the original database with admin.py file, we will briefly discuss about eeverything about models in further articles, But for now you can say that Model is an core part of MTV which which knows everything about data ,  how to access it, how to validate it, which behaviors it has, and the relationships between the data and all.


Template

T stands for template. It is an presentational layer which actually provide interface to the user.A Template contains everything about how data will show to user. It contains all the key parts of an web-page like colors, animations etc. As django provides an structured web-development process , templates stored in template folder which contain  html files,  Template further connected with Static files which are stored in Static folder . static folder may contain html, css, bootstrap, font, image files. All the connectivities to the static , template to the views are provide by the settings.py file. We will practically discuss all about that in further sections but for now you can say  Template actually decides , what and how should something  displayed on a web page.


View

V stands for view. Views is an business logic layer. It contain actual logic to access the models and delivered to the template. As  django is written in python, logics are also in the python (functions, classes, loops etc). These logics occurs in app’s views.py file. In simple words we can say that View is an interface between template  and models, which delivers data from models to template.

It is sufficient to understand MTV . For developing a full stack website, one should know all about how to connect Model Template and Views. In summary we can say Model contains database, Template contains html, css files and view contain python files.

How to use Command Prompt and Commands

Command Prompt is a command line interpreter application which allows us to make operating system operations using command line  interface rather than Graphical User Interface . It is used to perform different tasks including basic and advance tasks. To operate command prompt is not an difficult task, it needs only to keep in mind  a  little commands .The command line in windows provides access to over 250 commands!! but here we will discuss about some basic commands such as changing directory, view directories , creating, renaming and deleting folders:-

Let’s start it, to open command prompt, in search for command and click on Command Prompt:

Start Command Prompt
Starting Command Prompt

 

or go to following directory :-

 C:\Users\brar\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\System Tools

 

Command Prompt full Path
Command prompt Full Path

In the above directory there will be Command Prompt’s shortcut, double click on it r(Here i am using Window 10’s Command Prompt

1.Change Directories : 

This command enables you to change the current folder or, in other words, to navigate to another folder from your computer.This command  enables you to change the current folder or, in other words, to navigate to another folder from your computer.

  • The command “CD\”  takes you to the top of the directory tree. , to check it type ” CD\ ” you will see, it takes you to the top of the directory tree.
Change Directory Tree
Change directory

2.How to access sub-folders:  If you want to access sub-folders in a directory –

  1.  Type  cd and then it followed by a backslash ‘\’ or slash ‘/’ 
  2. After that type the name of the folder. 

Example: For ex. we want to go back in the above directory i.e  C:\Users\brar just type:

  • cd Users and press Enter (It will takes you ‘to C:\Users’
  • If you want to go inside multiple folders at once, just type name of folders and  separate them by slash or backslash and press enter. i.e “cd Users/brar/AppData”

Note: Command Prompt is not case-sensitive, i.e, we can use capital , lower  or combination of both. It means cd user , cd uSer or cd USER , all are acceptable.

Change directories
Change directories

3. Change Different Drives: There are different drives in our folder, you may need to access different folders of different drives, For example in my PC , There is C , E and F drives. 

  1. To change drive just type drive name, in which you want to go like C, D, E or F and then add : after it and press Enter.
  2. Example – ‘E:’ 
  3. If you want to change drive and access folder inside it at same time, you can do it by using cd command followed by “d”, “d” parameter is used to access another drive and directory at once.
  4.  If you want to go outside the folder “cd..” command is used, it will move you up one directory.
Change Drives
Change Drives

4.How to see Content of a folder / directory:   To see the available files and folders in a directory, DIR command is used, Just type DIR and press Enter, List of file and folders will appear, as shown in screenshot below: 

Directories
Available directories in current directory

5. How to Create Directory:  We are also able to create new folders using command  line interface, for that mkdir command is used , mkdir stands for make directory, it is followed by thee name of directory which we want to create.

  1. Select the folder/ directory in which we want to create a new folder
  2. Type mkdir newFolderName and press enter
  3. To chech whether it is created or not , try to go inside it using cd

Example: Here i am going to create a folder named MyFolder on desktop  as shown in screenshot below:

Create Folder
Create Folder using Command Prompt

 

6. Access File Inside Folder:  Here i am going to show you that how to access file, that is inside a folder, In the screenshot below, i have accessed a python file named first.py which is inside E drive’s python_programs named folder. 

  1. Go to the file’s directory
  2. Type name of the folder and its extension , example for python file, type fileName.py
  3. Press Enter the outcome of the file will show

 

Accessing Files

In the screenshot above, i have accessed  python file which have extension ( .py ).

So these are some basic commands of Command Prompt, that everyone should know. We have discussed about:

  1. cd
  2. cd..
  3. mkdir
  4. dir
  5. cd d/

Python Virtual Environment using Anaconda Distribution

Virtual Environment:

A Python virtual Environment allows us to have a virtual installation of Python and packages on our computer, python packages changes &  gets updated often! , there are changes that break backward compatibility, so we can create virtual environment that contains the newer version of the packages without break our web app using virtual environment.

virtualenv allows you to manage separate package installations for different projects. It essentially allows you to create a “virtual” isolated Python installation and install packages into that virtual installation. When you switch projects, you can simply create a new virtual environment and not have to worry about breaking the packages installed in the other environments. It is always recommended to use a virtualenv while developing Python applications.

In other words virtual Environment allows us to install all files and dependencies, packages in it that we need to execute python script rather than install them globally, virtual environment automatically installs them for us. It works same as they installed globally (On physical machine). The advantage of using virtual Environment is that we need not to have uninstall current version and install latest one , virtual environment automatically makes us updated with latest version.

Conda command is used in anaconda to install different packages. Here is the command for creating virtual environment on Anaconda :

CREATING VIRTUAL ENVIRONMENT : To use the virtual Environment with conda, we use the commands :

  1. conda create –name YourEnvironmentName django
Virtual Environment
Virtual Environment

2. As you can see in image above, there are list of packages along with their updated versions, that will install in Environment. After that type:  y than press Enter

 

Virtual Environment
Virtual Environment

3. Here Environment created successfully, it will automatically add into Anaconda3 > envs folder, no matter in which directory you are in, during installation. As you can see the image below, Environment, named EnvName  ( Our Environment Name )automatically added in envs, As you can, there are already four other environments in my system.

Environment Directory
Environment Directory

Note: You can create different environment for different projects, independently, Each particular project may need  particular packages, so we can go for it !!!

 

List of Commands :

  • To create environment, with specific version, you can:
conda create -n EnvName python=3.4
  • To activate environment:
conda activate EnvName
  • To deactivate environment:
conda deactivate
  • To remove Environment:
conda env remove --name EnvName
  • To see available Environments:
conda-env list
  • To update a package:
conda update -n EnvName packagename

Example:

Conda commands
Img 1: Conda commands for activate,update, deactivate and list of environments
remove packages
Img 2: remove packages

In example above (Img1) , Here django is the name of package, which try to update, but In my system it is up-to-dated , if there exists a newer version of django (or version you specify may be python or another one), then it will be upgrade using this command. So these are the basic steps and commands for Python Virtual Environment using Anaconda Distribution.

Django startapp

Installing Django : 

Here we are going to install django on anaconda

  •  You can install django with Anaconda by:
conda install django
  • Or for  normal python distributions :
pip install django
  • Or if you are using Virtual environment, it automatically installs django , python , pip for us( if you not know about virtual Environment ), you can see previous article on django.
  • Once you install django, it also installs a command line tool called-
django-admin
Now, let’s create our first project with django.

Creating Django Project

Choose your directory on which you want to start a project, You can also create a folder using Command Prompt by using  mkdir command .
  1. To create a django project type:
django-admin startproject ProjectNameGoesHere
Creating django project
Creating django project
          Img: Django Project Directory
Django project files
Django project files
2. Once project created, it contains following files:
  1.  __init__.py  :- This is a blank python script , due to its special name it let’s python know that this directory can be treated as a package.
  2.  settings.py :- This is where you will store all your project settings including, apps, templates, staticfiles etc.
  3. urls.py :-  This is a python script that will store all the url patterns for your project. Basically it will going to relate different web pages of your web applications and how to connect these web pages to user. This file will going to use a lot for rendering different web pages.
  4. wsgi.py :- This is a pyhton script that acts as the server gateway interface. It will later on help us to deploy our web app to production(on some online server).
  5. manage.py :- This is python script which used a lot. associated with many commands, as we build different apps.It can also be used to create app, As the name suggest it helps us to manage different process in our web development. Let’s use it:

3. Once project is created, Type:

python manage.py runserver
4.You will see a bunch of stuff there, but at the bottom, you will see something like:
Django version 2.0.5, using settings 'firstproject.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
5.Copy  http://127.0.0.1:8000/   and paste it on your browser.
Now you should see your very first webpage (welcome page of django) being locally hosted on your computer.
Django first page
Django first page

So now you can create, apps, views,templates, models in app whatever you want, by using its files settings.py , urls.py etc.  To check these files, open files in text editor, you will see python code here, because django is written in python.

Django example project

Django example project

A Django project is a collection of applications ( Django applications ) and configurations that when combined together will make up  the full stack web application.

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

These Django apps can then be plugged into other Django Projects, so you can reuse them, or can use other project’s app etc. In this article we will discuss about how to create an app and how to create view using views.py of an app.

Example

Lets’s create a simple application. Django example project will create app in the previous project which we have created in previous article. Following command is used to create an project:

django-admin startapp Appname
For more information about creating project you can visit   http://onlinetutorial.co.in/django-startapp/

Creating Django Application

1. If you have installed python and django on vierual environment, then first activate your environment. For more information about virtual  environment you can visit  http://onlinetutorial.co.in/creating-python-…nda-distribution/

2. Now create app using :

django-admin startapp Appname
Django Application
Creating django app
          In above snapshot

a.  Environment Name:  MyEnv

b. Project Name: firstproject

c. App Name: first app

3. Or we can alo create an app using :

python manage.py startapp appname
Django Application
django_app using manage.py
     In above snapshot:

a. Environment name:  MyEnv

b. Project Name: firstproject

c. App name: Myapp (which uses manage.py of project- firstapp)

4. Both methods are valid to create an app, whwn you will see in the project directory ( project/  ), there will be two apps ( firstapp and myapp )

Django Application
django project directory

5. After creating app , you will see here a number of python files, which are as follows:

Django Application
App directory
App Directory:

a. __init__.py : This is  blank python script that due to its special name ( constructor ) let’s python know that this directory can be treated as a package.

b. admin.py : You can register your models here which Django will then use them with django’s admin interface.

c. apps.py : Here you can place application specific configurations.

d. models.py : Here you can store the application’s data models i.e database part.

e. test.py : Here you can store test functions to test your code.

f. views.py : This is where you have functions that handle requests and return responses. (provides interface between models and templates). This file will use a lot.

Migration folder: This directory stores database specific info as it relates to the model. For example  for user model (It stores column names like name, roll number which are specified in models, and their update, delete information).

So, it is all about to create an app and its files, in further article we will discuss how to create views and setup these views.

Django urls

Django urls mapping

 

Django urls mapping is very essential when we have to create different apps in same project.Here is the full discussion about mapping urls. In our previous article we showed a very direct mapping from the views.py to urls.py If you have any doubts you can visit http://onlinetutorial.co.in/django-view/

There are various ways to mapping urls with views. Now we want to show  the ability of using the include function from django.conf.urls module.

Include() function

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 or a 404 not found error, if not found. In url.py.

The include() function allows us to look for a match with particular string resource (or regular expression ) and link back to our application’s own urls.py file. We will have to manually add  urls.py file in app’s folder.  Let’s start it.

Here we work continue on our previous project and app i.e Project Name – ‘firstproject’ and appname= ‘myapp’

Steps for mapping urls with views:

 

  1. First of all add new file named urls.py in your app’s folder.
For example: Here app name is myapp so create python file myapp > urls.py

Note: Save file with .py as it is python file

2. In project’s urls add following code:

firstproject > firstproject > urls.py

project urls
project urls

This would allow us to look for any url that has the pattern:

www.domainname.com/firstapp/..

If we match the above pattern, the include function basically tells django to go look at the urls.py file inside the firstapp folder. There may be different apps inside a single project, so we can include the function for different app’s urls. It is useful because there is no need to go to the app’s URLs.

 

3. Suppose we have the following views in our views.py file:

firstproject> myapp> views.py

App view
App view

4. Open urls.py file of your app and map these views with urls like given below:

firstproject> myapp> urls.py

App's urls.py
App’s urls.py

– Here django.conf.urls  is an django’s built in module and here we are using the url function of that module

– Second (In line 3) myapp is our app’s name and because we are using the views.py ‘s function (views) so here we need to import it on our app’s urls.py file.

– The most important thing is the  “urlpatterns”  tuple. It’s where you define the mapping between URLs and views. So django looks at appropriate views.

5. Runserver by python manage.py runserver and here the very first page ie index page returns the index view as shown below:

Django view
Django view

– In views. py. are there. We have done. Url mapping for these functions. Noew try to add / firstapp / first  to call other function. So it will look like

Django view
Django view

If we write something else except ‘firstapp’ Then there will be an 404 error which you can find here about namespaces of urls like:

Django views
Django views

So it’s all about url mapping, there are some other ways for mapping urls, which we discuss in the next articles.If you want to learn more

http://onlinetutorial.co.in/django-templates-tutorial/

 

django tutorial – django view

Django views and url mapping:

When a web page is requested, Django creates an HttpRequest for that django view then passes this request to the appropriate view function as a parameter. Here we will creating django’s very first view.

In our previous tutorials we discuss about how to create django  project and django app , for more information about creating apps you can visit:

http://onlinetutorial.co.in/django-website-templates/

After creating an project we have to setup views for that project. Here we will discuss about creating a very first view on django. So lets start it.

Steps for creating Django First view:

As in previous tutorials we have created project – firstproject and app myapp, here we work with the same project , you can use your own project and pp instead. Let’s go through the steps for setting first view with django.

  1. First of all open your project’s settings.py file and register your app  in installed apps list.(Don’t forget to save file) As shown in the screenshot below:
  • firstproject > firstproject > settings.py
Django app
Django app

2.  Now open your views.py file inside app’s folder and setup very first view as shown below:

  • firstproject > myapp > views.py
django views
django views

– Here we created an view named index . As we used python function to create view so these are called function based views in django.

– When a page is requested, Django creates an HttpRequest object that contains metadata about the request. Then Django loads the appropriate view, passing the HttpRequest as the first parameter to the view function(as in above screenshot request parameter). Each view is responsible for returning an HttpResponse object. For more information about django https you can visit  https://docs.djangoproject.com/en/2.0/ref/request-response/

– Here request is an variable you can use anything instead, but it is mandatory to pass(for an httprequest)

– In HttpResponse method i have passed an string “Hello it is my first view” you can pass html tags inside it.

3.  After creating view, now we have to map url for that view. As here we are ceating a very first view(for beginners) so we will use  very direct url mapping  later on we will discuss a lot about url mappings.

  • firstproject > firstproject > urls.py
django urls
django urls

–  Here in project’s urls.py first of all import the app’s views.py file and call the view function (As here our views name is index, and name that url path) inside urlpatterns list.

4. Open Anaconda prompt and Runserver for the project and check your first view :

django runserver
django runserver

 

5. Copy and paste the above url inside your browser and there will be your first view with django :

django first view
django first view

So, it is all about django first view and mapping url for that view, in further sections of  tutorial we will discuss a lot about views and mapping urls. Thanks

Django API

Django API : Creating APIs using Django

Creating APIs with django is very simple and easy process . We need to to create an different json or python format . Using Django  we can direct create APIs with Django database ( models ) .

What is API ?

API stands for Application Programming Interface . Basically the APIs are the set of rules or we can say code , which are written to provide the interaction between different applications . As the name suggest APIs are the interface between different applications .

In simple words we can say that APIs allows us to use the code , written by someone else . Let’s take an simple example , suppose you are going to develop an international shopping website . Here is large work that you have to do including getting product data , vendor data , upload data etc . Here also , you need a simple select option for all countries . Instead of adding all 196 countries manually one by one ,we need an interface which can automatically do this for us . This interface is actually an API . We can use APIs in  different applications including Web-apps , Mobile-apps etc, as shown in figure below:

 

django api

Mostly we create APIs in JSON or XML . If you want to learn more about JSON , then you can visit the link below:

JSON In Python

Creating Django API

Let’s creating an API from Django database (default is sql-lite3 ). I am creating simple API for adding multiple choice questions . Here is the complete process

Step 1

Create an django project using:

django-admin startproject projectName

Step 2

After that , inside project folder create an app using:

django-admin startapp appName

For example:

Django API
Django API

Step 3

Setup project , add app to project’s Settings.py file .For more details about creating project you can visit the link               below:

      Create Django Project

Step 4

Create an django model (which you want to create api) in app’s models.py file like this :

apiproject > api > models.py

from django.db import models
class addQuestion(models.Model):
    CHOICES = (
    ('a','A'),
    ('b','B'),
    ('c','C'),
    ('d','D')
    )

    question = models.CharField(max_length=500)
    option1 = models.CharField(max_length = 250)
    option2 = models.CharField(max_length = 250)
    option3 = models.CharField(max_length = 250)
    option4 = models.CharField(max_length = 250)
    answer = models.CharField(max_length= 1, choices = CHOICES, blank=True)
    description = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True, blank = True)

    def __str__(self):
        return self.question

Step 5

Add model to admin.py file

apiproject > api > admin.py

from django.contrib import admin
from .models import addQuestion

admin.site.register(addQuestion)

Step 6

Don’t forget to migrate the model changes. Like below:

Django API
Django API

Step 7

Create an superuser for admin panel .

Django API
Django API

After that run server by python manage.py runserver open url 127.0.0.1:8000/admin . Add data to models to create api like below :

Django API
Django API

Step 8 – Creating API

Here is the actual code for creating Django API using database :

apiproject > api > views.py

from django.shortcuts import render
from api.models import addQuestion
from django.core import serializers
from django.http import HttpResponse

def index(request):
    a = addQuestion.objects.all()
    serialized_obj = serializers.serialize('json',a)
    return HttpResponse(serialized_obj, content_type = 'application/json')

apiproject > apiproject> urls.py

from django.contrib import admin
from django.urls import path
from api import views
urlpatterns = [
    path('admin/', admin.site.urls),
    path('',views.index,name='index')
]

run python manage.py runserver  and here is the resulting Django API

Django API
Django API

What are serializers ?

Serializers allows us to convert complex data into plain text / simple accessible syntax . Complex syntax may be query sets or other database objects . It converts these object;s into python types (dictionary / list ) . And then can be converted to any content type like JSON. In django , serializers exists at core module . We uses serialize() function of it to convert data .

serialize()

serialize() is a method of serializers module which takes two arguments :

  • In which type , to convert example JSON
  • Complex Type / data to convert example query – sets .

Get data of API using unique id

Here is the final code to get specific data , by filling id to url .

apiproject > api > views.py

from django.shortcuts import render
from api.models import addQuestion
from django.core import serializers
from django.http import HttpResponse

def index(request):
        if request.method == 'GET':
            d = request.GET
            if 'id' in d:
                i = request.GET['id']
                dd = addQuestion.objects.filter(pk =i)
                serialized_obj = serializers.serialize('json',dd)
                return HttpResponse(serialized_obj, content_type = 'application/json')

            else:
                a = addQuestion.objects.all()
                serialized_obj = serializers.serialize('json',a)
                return HttpResponse(serialized_obj, content_type = 'application/json')

Output:

So , it is all about creating API with Django database . I hope you guys get it . Thanks !!!

PHP isset() alternative in python

PHP isset() alternative in python

In this tutorial, we will discuss about PHP isset() alternative in python Django. I think you all know about the importance of isset() method in python. If you don’t  know, no problem let’s discuss:

Why PHP isset()

The isset() method is used to check for a variable, whether set or not. In other words we can say that it checks whether a variable contains any value or not. The function returns true if a variable contains not null or not empty value. If a variable is null or empty the isset() returns false. For example:

Example

<?php
    $a = 10;
    isset($a);
?>
#It will return true because variable a is set with value 10

PHP isset() alternative in python :

The above code is for checking variable value existence in PHP. Now we will discuss how to use isset() in python. There are also various situations where we need to do checking for variable existence. Let’s take any situation:

Syntax

if 'variable' in request.POST:
    //code if variable set
#It also can be used with GET request

 

Why need to check variable existence ?

Let’s take an example of an simple Django application, which contains two buttons or we can say two submit requests. In this case, how to recognize at server side which button is clicked ? It is done with the help of checking for variable example. Let’s take example:

Suppose here is simple page with two forms:

PHP isset() equivalent in python
PHP isset() equivalent in python

In python, we get data in views file, so here now we need to get the data which we received from POST request. So here is the simple code to get the data:

views.py
from django.shortcuts import render
from django.http import HttpResponse

def index(request):
    if request.method == 'POST':
        name = request.POST['un']
        #Authenticate the data we will print data for 
        #demo purpose
        return HttpResponse(name)
    return render(request,'index.html')

Now the problem is:

  • In above code, we have get the variable ‘un’ from POST request
  • ‘un’ is value of the name attribute in Login form
  • Now try to fill contact form and submit
  • It will return error like this:
PHP isset() equivqlent in python
PHP isset() equivqlent in python
  • It is because it does not found ‘un’ in Contact form which is genuine
  • It is because there is no ‘un’ attribute in contact form
  • So now to get rid from this problem, we need to check if the value is set or not
  • If ‘un’ set only then this code should execute
  • This is how the isset works
Views.py
from django.shortcuts import render
from django.http import HttpResponse

def index(request):
    if request.method == 'POST':
        if 'un' in request.POST: # ISSET CHECK
            name = request.POST['un']
            print('Login form request')

        elif 'contact' in request.POST:
            print('Contact Form Request')

    return render(request,'index.html')

Output

PHP isset() equivqlent in python
PHP isset() equivqlent in python

Explanation

  • As you can see in the example above, we can handle POST or GET request from multiple forms in the same view
  • I just print it in console, you can control it further, get values and play with values
  • It is same for the GET request
  • This example is just for demo purpose to let you know, how isset works in python

Download Source Code :

So, it is all about PHP isset alternative in python. To download the entire source code you can click on button below. Stay connected to learn more about Django and python. Good Luck!!!

Django AJAX
Django AJAX download

 

Django Model Forms

As in Django Forms, we can grab data from form fields and can performs some actions on that data like validation, showing that data on console. Using django, it is also very easy to connect django models to django forms so that we can accept user input using forms and save data to a model.

Intead of inheriting forms from forms.Form class we will use forms.ModelForm in our forms.py file.This helper class allows us to create form from a Pre-existing model. This meta class provides information connecting the models.

Example :(forms.py)

from django import forms

from myapp.models import Mymodel

class MyNewForm(forms.ModelForm):

          #fields go here

          class Meta:                 # it really connect the form to a Model

                  model = MyModel

                  fields = ‘__all__’

  • The field attribute will connect the form fields to the model( There are various options for that, We can set it to all or choose specific fields.)
  • Fields must match  with models.
  • Form can be generate from model, it will save a lot of work, So we have not to write fields again, or we have to say class Meta:

Model = MyModel & connect fields.

  • But if we want some custom validators (form validators) , then we have to pass those fields,  where we provide the validator parameters.
  • Models also have their own constrains & those for validation just come automatically, when we call class Meta & connect that to model. There is code example to form with custom validation.

Example: (forms.py)

from django import forms
from django.core import validators
from Myapp.models import userdata
def nameValid(value):
if value[0].lower() != ‘a’:
raise forms.ValidationError(“Name must start with a”)
return nameValid

 

class UserForm(forms.ModelForm):
Name = forms.CharField(validators= [nameValid])
Email = forms.EmailField()
Password = forms.CharField(widget= forms.PasswordInput)
Confirm = forms.CharField(label=’Enter Password Again’)
Comment = forms.CharField(widget= forms.Textarea, validators=[validators.MaxLengthValidator(5)])
Url = forms.URLField()
botcatch = forms.CharField(widget = forms.HiddenInput, required=False)
Date_of_birth = forms.DateField()

class Meta():
model = userdata
fields = ‘__all__’ # to select all fields
#fields = (‘Name’,’Email’) To select specific fields

def clean(self):
cleanData = super().clean()
pwd = cleanData[‘Password’]
cpwd = cleanData[‘Confirm’]

if pwd != cpwd:
raise forms.ValidationError(“Password Didn’t Match”)

def clean_botcatch(self):
data = self.cleaned_data[‘botcatch’]
if len(data)>0:
raise forms.ValidationError(“Robot user found”)
return data

In example above, the table fields has their custom validators.

There is different ways for field attribute, that isinside the class Meta:

  1.  Option 1: Set it to : ‘__all__’ , it is used to grabing the all fields from model.
  2. Option 2: Include certain fields i.e  (‘field 1’ , ‘field 2’)

Let’s Create an model:

  1. Create the models im Models.py
  2. Create  form  in app’s > form.py
  3. Connect form.py to model.py , The attributes of form.py will inherit from forms.Modelform instead forms.Forms
  4. Edit the views.py to show the form . Views grabs the form data  in a variable  and perform some actions on that data i.e. variableName = formname
  5. Connect the form data to the template using views.py (using context dictionary).
  6. Setup views.py if request.method == “POST”
  7. Figure out how to save data
  8. Run server and check working ,if all steps done in correct way then data filled in form should save at backend (In models).

Tips: 

  • When one file is connected to other,  don’t forget to import it at first. for example, if we use models in forms. py  then the first step should be:

 from appname.models import ModelName

  • When using template tagging: don’t forget to load static-files at first example:

{% load staticfiles %}

  • Make sure that admin is registered  at admin.py and migrations are applied carefully for particular app, example:

from appname.models import ModelName1, ModelName2

              admin.site.register(ModelName1)

              admin.site.register(ModelName2)

  • If you have started a newapp don’t forget to add it in settings.py’s INSTALLED_APPS example:

INSTALLED_APPS = [
‘django.contrib.admin’,
‘django.contrib.auth’,
‘django.contrib.contenttypes’,
‘django.contrib.sessions’,
‘django.contrib.messages’,
‘django.contrib.staticfiles’,
‘Myapp’,
‘modelforms’
]

Here Myapp , modelforms are the names of new installed apps.

  • setup both urls.py (Project’s, app’s) very carefully.

CODE EXAMPLE OF MODELS:

Models.py

from django.db import models

class userdata(models.Model):
Name = models.CharField(max_length=250)
Email = models.EmailField(max_length=200)
Password = models.CharField(max_length=200)
ConfirmPassword = models.CharField(max_length=200)
Comment = models.CharField( max_length=200)
Url = models.URLField()

def __str__(self):
return self.Name

 

Forms.py

 

from django import forms
from django.core import validators
from Myapp.models import userdata
def nameValid(value):
if value[0].lower() != ‘a’:
raise forms.ValidationError(“Name must start with a”)
return nameValid

class UserForm(forms.ModelForm):
Name = forms.CharField(validators= [nameValid])
Email = forms.EmailField()
Password = forms.CharField(widget= forms.PasswordInput)
Confirm = forms.CharField(label=’Enter Password Again’)
Comment = forms.CharField(widget= forms.Textarea, validators=[validators.MaxLengthValidator(5)])
Url = forms.URLField()
botcatch = forms.CharField(widget = forms.HiddenInput, required=False)
Date_of_birth = forms.DateField()

class Meta():
model = userdata
fields = ‘__all__’ # to select all fields
#fields = (‘Name’,’Email’) To select specific fields

def clean(self):
cleanData = super().clean()
pwd = cleanData[‘Password’]
cpwd = cleanData[‘Confirm’]

if pwd != cpwd:
raise forms.ValidationError(“Password Didn’t Match”)

Views.py:

from Myapp.models import AccessRecord, Webpage
from django.shortcuts import render
from Myapp import forms
def index(request):
website = AccessRecord.objects.order_by(‘date’)
webpages = Webpage.objects.filter(id = 3)
my_dict ={‘insert’:’Hello there’,’records’:website,’wb’:webpages}

return render(request,’myfirst.html’,context = my_dict)

def form(request):
form_data = forms.UserForm()

if request.method == “POST”:
form_data = forms.UserForm(request.POST)

if form_data.is_valid():
form_data.save(commit= True)
return index(request)
print(“register Successfully”)

return render(request,’Uform.html’,context = {‘udata’:form_data})

#return index(request) Returns back to index page, if data added successfully.

Template: Myfirst.html:

<!DOCTYPE html>
{% load staticfiles %}
<html lang=”en” dir=”ltr”>
<head>
<link rel=”stylesheet” href=”{% static “bootstrap/css/bootstrap.min.css “%}”>
<link rel=’stylesheet’ href=”{% static “Myapp/css/style.css” %}”>
<title>Template</title>
</head>
<body>
<h1>{{ insert }}</h1>
<img src=”{% static “Myapp/images/nature.jpeg “%}” alt=”No Image”/>
<div class=’jumbotron’>
<h1 class=’text-danger bg-success’>Hello It is My First Template View</h1>
</div>
</body>
</html>

Template (Uform.html):

<!DOCTYPE html>
{% load staticfiles %}
<html lang=”en” dir=”ltr”>
<head>
<meta charset=”utf-8″>
<title>Django Forms</title>
<link rel=”stylesheet” href='{% static “bootstrap/css/bootstrap.min.css” %}’>
</head>
<body>
<div class=”jumbotron”>
<h1 class=’alert-info’>Fill out the details in the form</h1>
<form class=”form-group” method=”POST”>
<div class=”form-control”>
{{ udata.as_p }}
{% csrf_token %}
</div>
<input class=”btn btn-success” type=’submit’ value=’Register’>
</form>
</div>
</body>
</html>

admin.py :

from django.contrib import admin
from Myapp.models import userdata

admin.site.register(userdata)

urls.py:

from django.contrib import admin
from django.urls import path
from django.conf.urls import include
from Myapp import views

urlpatterns = [
path(‘admin/’, admin.site.urls),
path(”,views.index, name= ‘index’),
path(‘form/’,views.form, name=’form’)
]

Now go to command prompt and runserver:

(base) C:\Users\MyPc>E:

(base) E:\>cd Dproject/myproject

(base) E:\DProject\Myproject>activate myenv

(myenv) E:\DProject\Myproject>python manage.py runserver
Performing system checks…

System check identified no issues (0 silenced).
June 15, 2018 – 19:27:42
Django version 2.0.2, using settings ‘Myproject.settings’
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.

 

Django form Validation

Form Validation

Django form Validation: As the  data validation is the process of ensuring that the data is correct and useful, Similarly form validation ensures that the submitted data filled in the fields is true correct , and meets syntax and structure  requirement or not.

Django provides a strong form validation and built in validators , which imported from the django.core module, we can also use our custom validators. With Django’s form validators , form data is not only well organized  for user, but it is also prevents  from potential”bots” i.e automated scripting programs that come in fill junk info into forms. In form validation, sometimes hidden fields are used.

Hidden- Fields

Hidden fields are something that remains in HTML but is actually hidden from the user, and lot of times we can actually use these to catch malicious  bars on your website. It generates random value, and django

check matches of that at the back-end , on the basis of that match django provides validation.

botcatch = forms.CharField(required = False, widget = forms.HiddenInput)

csrf_token

 It is an template tag that provides security protection against CSRF( Cross Site Request Forgeries).

CSRF is an attack that may cause an website application to perform unwanted actions , the malicious websites may send an link to the user’s website and performs unwanted tasks using user’s credentials. csrf_token also protect from login csrf, that may login to user’s browser using someones credentials.

   {% csrf_token %}

Steps that we will follow

(for already created. app, project and templates )

  1. First of all In your app folder, create new file names forms.py. and import django’s modules:from django import forms       # for django forms
    from django.core import validators  # for validators

    1. In that code along like given below, we use here:                                                                    adding a check for empty fields(clean_botcatch)                                                adding a check for a bot                                                                                      adding a clean method for entire form(clean)                                                      adding validation if name must start with particular                          letter(nameValid)
  2. Create view for the forms in views.py and sent data through context dictionary in template tagging {udata}
  3. Create and template, to which data is sent from views.py i.e Uform.html
  4. Dont’t forget to register app, and setup template directory if new project is created
  5. Mapp urls.py for particular method in views.py i.e.(appname >views.py > functionName) form
  6. Runserver by :  >>python manage.py runserver in command shell
  7. If you done the same code like me put  /form in browser’s url
  8. Fill details in form and hit submit, data will printed into console if it is valid

forms.py(app’s)

from django import forms
from django.core import validators

def nameValid(value):
    if value[0].lower() != 'a':
        raise forms.ValidationError("Name must start with a")
    return nameValid

class UserForm(forms.Form):
    Name = forms.CharField(validators= [nameValid])
    Email = forms.EmailField()
    Password = forms.CharField(widget= forms.PasswordInput)
    Confirm = forms.CharField(label='Enter Password Again')
    Comment = forms.CharField(widget= forms.Textarea, validators=[validators.MaxLengthValidator(5)])
    Url = forms.URLField()
    botcatch = forms.CharField(widget = forms.HiddenInput, required=False)
   
    def clean(self):
        cleanData = super().clean()
        pwd = cleanData['Password']
        cpwd = cleanData['Confirm']

        if pwd != cpwd:
            raise forms.ValidationError("Password Didn't Match")

    def clean_botcatch(self):
        data = self.cleaned_data['botcatch']
        if len(data)>0:
            raise forms.ValidationError("Robot user found")
        return data

Views.py

from Myapp.models import AccessRecord, Webpage
from django.shortcuts import render
from Myapp import forms
def index(request):
    website = AccessRecord.objects.order_by('date')
    webpages = Webpage.objects.filter(id = 3)
    my_dict ={'insert':'Hello there','records':website,'wb':webpages}

    return render(request,'myfirst.html',context = my_dict)

def form(request):
    form_data = forms.UserForm()
    if request.method == "POST":
        form_data = forms.UserForm(request.POST)

        if form_data.is_valid():
            print("Validation Successfully!!!")
            print('Name:',form_data.cleaned_data['Name'])
            print('Email:',form_data.cleaned_data['Email'])
            print('Password:',form_data.cleaned_data['Password'])
            print('COMMENT:',form_data.cleaned_data['Comment'])
            print('Url:',form_data.cleaned_data['Url'])

    return render(request,'Uform.html',context = {'udata':form_data})

projectName > templates> Uform.html

Uform.html

<!DOCTYPE html>
{% load staticfiles %}
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Django Forms</title>
<link rel="stylesheet" href='{% static "bootstrap/css/bootstrap.min.css" %}'>
</head>
<body>
<div class="jumbotron">
<h1 class='alert-info'>Fill out the details in the form</h1>
<form class="form-group" method="POST">
<div class="form-control">
{{ udata.as_p }}
{% csrf_token %}
</div>
<input class="btn btn-success" type='submit' value='Register'>
</form>
</div>
</body>

</html>

myfirst.html

<!DOCTYPE html>
{% load staticfiles %}
<html lang="en" dir="ltr">
<head>
<link rel="stylesheet" href="{% static "bootstrap/css/bootstrap.min.css "%}">
<link rel='stylesheet' href="{% static "Myapp/css/style.css" %}">
<title>Template</title>
</head>
<body>
<h1>{{ insert }}</h1>
<img src="{% static "Myapp/images/nature.jpeg "%}" alt="No Image"/>
<div class='jumbotron'>
<h1 class='text-danger bg-success'>Hello It is My First Template View</h1>
</div>

{% if records %}
<h1 class='alert-success'>Here is record of webpages</h1>
<table class='table'>
<tr>
<th>Webpage name</th>
<th>Date accessed</th>
</tr>
{% for acc in records %}
<tr>
<td>{{ acc.name }}</td>
<td>{{ acc.date }}</td>
</tr>
{% endfor %}
</table>
{% else %}
<h1 class='text-danger'>No records here </h1>
{% endif %}
<h1 class='text-center bg-dark text-light '>Webpage Details</h1>
{% if wb %}
<table class='table table-striped'>
<tr>
<th>Id</th>
<th>Category</th>
<th>Webpage Name</th>
<th>Webpage Url</th>
</tr>
{% for items in wb %}
<tr>
<td>{{ items.id }}</td>
<td>{{items.category}} </td>
<td>{{ items.name }}</td>
<td>{{ items.Url }}</td>

</tr>
{% endfor %}
{% else %}
<h1 class='alert-info'>No Webpages Here</h1>
</table>

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

Project > urls.py

from django.contrib import admin
from django.urls import path
from django.conf.urls import include
from Myapp import views

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

Subscribe to our newsletter

Want to be notified when our article is published? Enter your email address and name below to be the first to know.