Web Application Development using Python and Django PDF

Summary

This document provides an introduction to web application development using Python and the Django framework.

Full Transcript

Unit-II Introduction To Web Development And Django Web Application: The applications which will provide services over the web are called web applications.Eg: gmail.com, facebook.com, durgasoftvideos.com etc Every web application contains 2 main components 1) Front-End 2) Back-End 1)...

Unit-II Introduction To Web Development And Django Web Application: The applications which will provide services over the web are called web applications.Eg: gmail.com, facebook.com, durgasoftvideos.com etc Every web application contains 2 main components 1) Front-End 2) Back-End 1) Front-End: It represents what user is seeing on the website We can develop Front-End content by using the following technologies: HTML, JS, CSS, JQuery and BootStrap JQuery and Bootstrap are advanced front-end technologies, which are developed byusing HTML, CSS and JavaScript only. HTML: HyperText Markup Language Every web application should contain HTML. i.e HTML is the mandatory technology forweb development.It represents structure of web page CSS: Cascading Style Sheets It is optional technology, still every web application contains CSS. The main objective of CSS is to add styles to the HTML Pages like colors, fonts, bordersetc. Java Script: It allows to add interactivity to the web application including programming logic. The main objective of Java Script is to add functionality to the HTML Pages. ie to adddynamic nature to the HTML Pages. HTML → Meant for Static Responses HTML+JS → Meant for Dynamic Responses Eg 1: To display "Welcome to DURGASOFT" response to the end user only HTML isenough,b'z it is static response. Eg 2: To display current server date and time to the end user, only HTML is not enoughwe required to use some extra technology like JavaScript,JSP,ASP,PHP etc as it is dynamic response. Static Response vs Dynamic Response: If the response is not varied from time to time and person to person then it is considered as static response. Eg: Login Page of Gmail Home Page of ICICI Bank If the response is varied from time to time and person to person then it is considered as dynamic response. Eg: Inbox Page of Gmail Balance Page of ICICI Bank 2) Back End: It is the technology used to decide what to show to the end user on the Front-End. ie Backend is responsible to generate required response to the end user,which is displayed by the Front-End. Back-End has 3 important components: 1) The Language like Java,Python etc 2) The Framework like DJango,Pyramid,Flask etc 3) The Database like SQLite,Oralce,MySQL etc For the Backend language Python is the best choice b'z of the following reasons: Simple and easy to learn, libraries and concise code. For the Framework DJango is the best choice b'z it is Fast, Secure and Scalable. Django is the most popular web application framework for Python. DJango provides inbuilt database which is nothing but SQLite, which is the best choice for database. The following are various popular web applications which are developed by using Python and DJango YouTube, Dropbox, Quora, Instagram, Reddit, Yahoo Maps etc DJango: ⚽ Django is a free and open-source web framework. ⚽ It is written in Python. ⚽ It follows the Model-View-Template (MVT) architectural pattern. ⚽ It is maintained by the Django Software Foundation (DSF) ⚽ It is used by several top websites like Youtube,Google,Dropbox,Yahoo Maps, Mozilla,Instagram,Washington Times,Nasa and many more ⚽ https://www.shuup.com/blog/25-of-the-most-popular-python-and-django-websites/ ⚽ Django was created in 2003 as an internal project at Lowrence Journal-World News Paper for their web development. ⚽ The Original authors of Django Framework are: Adrian Holovaty, Simon Willison ⚽ After Testing this framework with heavy traffics, Developers released for the public as open source framework on July 21st 2005. ⚽ The Django was named in the memory of Guitarist Django Reinhardt. ⚽ Official website: djangoproject.com Top 5 Features of Django Framework: Django was invented to meet fast-moving newsroom deadlines, while satisfying the tough requirements of experienced Web developers. The following are main important features of Django 1) Fast: Django was designed to help developers take applications from concept to completion as quickly as possible. 2) Fully loaded: Django includes dozens of extras we can use to handle common Web development tasks. Django takes care of user authentication, content administration, site maps, RSS feeds, and many more tasks. 3) Security: Django takes security seriously and helps developers avoid many common security mistakes, such as SQL injection, cross-site scripting, cross-site request forgery and clickjacking. Its user authentication system provides a secure way to manage user accounts and passwords. 4) Scalability: Some of the busiest sites on the planet use Django’s ability to quickly and flexibly scale to meet the heaviest traffic demands. 5) Versatile: Companies, organizations and governments have used Django to build all sorts of things — from content management systems to social networks to scientific computing platforms. Note: 1) As Django is specially designed web application framework, the most commonly required activities will takes care automatically by Django and Hence Developer's life will be simplified and we can develop applications very easily. 2) As Django invented at news paper,clear documentation is avilable including a sample polling application. 3) https://docs.djangoproject.com/en/2.1/contents/ How to install django: 1. Make sure Python is already installed in our system python --version 2. Install django by using pip pip install django pip install django == 1.11.9 D:\>pip install django Collecting django Downloading https://files.pythonhosted.org/packages/51/1a/6153103322/Django-2.1-py3-none- any.whl (7.3MB) 100% || 7.3MB 47kB/s Collecting pytz (from django) Downloading https://files.pythonhosted.org/packages/30/4e/ 53b898779a/pytz-2018.5-py2.py3-none-any.whl (510kB) 100% || 512kB 596kB/s Installing collected packages: pytz, django Successfully installed django-2.1 pytz-2018.5 You are using pip version 9.0.3, however version 18.0 is ava You should consider upgrading via the 'python -m pip install 3. To check django version: py -m django --version VS Code IDE/Editor: Install VScode IDE Speciality of VS Code IDE: It is freeware. It is open source. It supports cross platform. It provides several auto completion short-cuts for easy development etc Django Project vs Django Application: A Django project is a collection of applications and configurations which forms a full web application. Eg: Bank Project A Dango Application is responsible to perform a particular task in our entire web application. Eg: loan app registration app polling app etc Loan Configurations App Investment Insurance App App Customer App Bank Project Project = Several Applications + Configuration Information Note: 1) The Django applications can be plugged into other projects.ie these are reusable. (Pluggable Django Applications) 2) Without existing Django project there is no chance of existing Django Application. Before creating any application first we required to create project. How to create Django Project: Once we installed django in our system, we will get 'django-admin' command line tool, which can be used to create our Django project. django-admin startproject firstProject D:\>mkdir djangoprojects D:\>cd djangoprojects D:\djangoprojects>django-admin start-project firstProject The following project structure will be created D:\djangoprojects> | +---firstProject ¦ ¦---manage.py ¦ +---firstProject ¦---settings.py ¦---urls.py ¦--wsgi.py ¦-- init.py init.py: It is a blank python script.Because of this special file name, Django treated this folder as python package. Note: If any folder contains init.py file then only that folder is treated as Python package.But this rule is applicable until Python 3.3 Version. settings.py: In this file we have to specify all our project settings and and configurations like installed applications, middileware configurations, database configurations etc urls.py: Here we have to store all our url-patterns of our project. For every view (web page), we have to define separate url-pattern. End user can use url-patterns to access our webpages. wsgi.py: wsgi → Web Server Gateway Interface. We can use this file while deploying our application in production on online server. manage.py: The most commonly used python script is manage.py It is a command line utility to interact with Django project in various ways like to run development server, run tests, create migrations etc. How to Run Django Development Server: We have to move to the manage.py file location and we have to execute the following command. py manage.py runserver D:\djangoprojects\firstProject>py manage.py startserver Performing system checks... System check identified no issues (0 silenced). You have 13 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. August 03, 2018 - 15:38:59 Django version 1.11, using settings 'firstProject.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Now the server started. How to Send First Request: Open browser and send request: http://127.0.0.1:8000/ The following should be response if everything goes fine. ------------------------------------------------------------------------------ It worked! Congratulations on your first Django-powered page. Next, start your first app by running python manage.py startapp [app_label]. You're seeing this message because you have DEBUG = True in your Django settings file and you haven't configured any URLs. Get to work! ----------------------------------------------------------- Role of Web Server: Web Server provides environment to run our web applications. Web Server is responsible to receive the request and forward request to the corresponding web component based on url-pattern and to provide response to the end user. Django framework is responsible to provide development server. Even Django framework provides one inbuilt database sqlite. Special Thanks to Django. Note: Once we started Server a special database related file will be generated in our project folder structure. db.sqlite3 Creation of First Web Application: Once we creates Django project, we can create any number of applications in that project. The following is the command to create application. python manage.py startapp firstApp D:\djangoprojects\firstProject>python manage.py startapp firstApp The following is the folder structure got created. D:\djangoprojects> └───firstProject │ db.sqlite3 │ manage.py │ ├───firstApp │ │ admin.py │ │ apps.py │ │ models.py │ │ tests.py │ │ views.py │ │ init.py │ │ │ └───migrations │ __init.py │ └───firstProject │ settings.py │ urls.py │ wsgi.py │ init.py │ Note: Observe that Application contains 6 files and project contains 4 files+ one special file: manage.py 1) init.py: It is a blank Python script. Because of this special name,Python treated this folder as a package. 2) admin.py: We can register our models in this file. Django will use these models with Django's admin interface. 3) apps.py: In this file we have to specify application's specific configurations. 4) models.py: In this file we have to store application's data models. 5) tests.py: In this file we have to specify test functions to test our code. 6) views.py: In this file we have to save functions that handles requests and return required responses. 7) Migrations Folder: This directory stores database specific information related to models. Note: The most important commonly used files in every project are views.py and models.py Activities required for Application: Activity-1: Add our application in settings.py,so that Django aware about our application. In settings.py: 1) INSTALLED_APPS = [ 2) 'django.contrib.admin', 3) 'django.contrib.auth', 4) 'django.contrib.contenttypes', 5) 'django.contrib.sessions', 6) 'django.contrib.messages', 7) 'django.contrib.staticfiles', 8) 'firstApp' 9) ] Activity-2: Create a view for our application in views.py. View is responsible to prepare required response to the end user. i.e view contains business logic. There are 2 types of views. 1) Function Based Views 2) Class Based Views In this application we are using Function based views. views.py: 1) from django.shortcuts import render 2) from django.http import HttpResponse 3) 4) # Create your views here. 5) def display(request): 6) s='Hello Students welcome to DURGASOFT Django classes!!!' 7) return HttpResponse(s) Note: 1) Each view will be specified as one function in views.py. 2) In the above example display is the name of function which is nothing but one view. 3) Each view should take atleast one argument (request) 4) Each view should return HttpResponse object with our required response. Request View Response View can accept request as input and perform required operations and provide proper response to the end user. Activity-3: Define url-pattern for our view in urls.py file. This url-pattern will be used by end-user to send request for our views. The 'urlpatterns' list routes URLs to views. For functional views we have to do the following 2 activities: 1) Add an import: from firstApp import views 2) Add a URL to urlpatterns: url(r'^greeting/', views.display) urls.py: 1) from django.conf.urls import url 2) from django.contrib import admin 3) from firstApp import views 4) 5) urlpatterns = [ 6) url(r'^admin/', admin.site.urls), 7) url(r'^greetings/', views.display), 8) ] Whenever end user sending the request with urlpattern: greeting then disply() function will be executed and provide required response. Activity-4: Start Server and Send the request py manage.py runserver http://127.0.0.1:8000/greetings Http Request flow in Django Application: Request greeting def display() display urls.py views.py Response End User Django Server 1. Whenever end user sending the request first Django development server will get that request. 2. From the Request django will identify urlpattern and by using urls.py, the corresponding view will be identified. 3. The request will be forwared to the view. The corresponding function will be executed and provide required response to the end user. Summary of Sequence of Activities related to Django Project: 1) Creation of Django project django-admin startproject firstProject 2) Creation of Application in that project py manage.py startapp firstApp 3) Add application to the Project (inside settings.py) 4) Define view function inside views.py 5) Define url-pattern for our view inside urls.py 6) Start Server py manage.py runserver 7) Send the request How to change Django Server Port: By default Django develoment server will run on port number: 8000. But we can change port number based on our requirement as follows. py manage.py runserver 7777 Now Server running on port number: 7777 We have to send the request with this port number only http://127.0.0.1:7777/greetings/ http://127.0.0.1:8000/time/ Various Practice Applications: 1. Write Django Application just to send Helloworld message as response. 2. Write Django application to send server time as response 3. Single application with multiple views views.py: 1) from django.shortcuts import render 2) from django.http import HttpResponse 3) 4) # Create your views here. 5) def good_morning_view(request): 6) return HttpResponse('Hello Friend Good Morning!!!') 7) 8) def good_evening_view(request): 9) return HttpResponse('Hello Friend Good Evening !!!') 10) 11) def good_afternoon_view(request): 12) return HttpResponse('Hello Friend Good Afternoon!!!') urls.py 1) from django.conf.urls import url 2) from django.contrib import admin 3) from testapp import views 4) 5) urlpatterns = [ 6) url(r'^admin/', admin.site.urls), 7) url(r'^morning/', views.good_morning_view), 8) url(r'^afternoon/', views.good_afternoon_view), 9) url(r'^evening/', views.good_evening_view), 10) ] 4. Single project with multiple applications: greetingapp: views.py 1) from django.shortcuts import render 2) from django.http import HttpResponse 3) 4) # Create your views here. 5) def greetings_view(request): 6) #total html code 1000 lines of code 7) return HttpResponse('Hello Friends Good Morning...Have a Nice Dayadd application name 2. urls.py --->just add: url(r'^urlApp/',include('urlApp.urls'), Advantages: The main advantages of defining urlpatterns at application level instead of project level are 1) It promotes reusability of Django Applications across multiple projects 2) Project level urls.py file will be clean and more readable Unit-III Django Templates And Static Files Django Templates: It is not recommended to write html code inside python script (views.py file) because: 1) It reduces readability because Python code mixed with html code 2) No seperation of roles. Python developer has to concentrate on both python code and HTML Code. 3) It does not promote reusability of code We can overcome these problems by seperating html code into a seperate html file.This html file is nothing but template. From the Python file (views.py file) we can use these templates based on our requirement. We have to write templates at project level only once and we can use these in multiple applications. Python Stuff required to develop Template Based Application: 1) To know the current Python file name print( file ) #test.py 2) To know absolute path of current Python File Name import os print(os.path.abspath( file )) Output: D:\durgaclasses\test.py 3) To know Base Directory name of the current file print(os.path.dirname(os.path.abspath( file ))) Output: D:\durgaclasses 4) Inside D:\durgaclasses there is one folder named with templates. To know its absolute path import os BASE_DIR=os.path.dirname(os.path.abspath( file )) TEMPLATE_DIR=os.path.join(BASE_DIR,'templates') print(TEMPLATE_DIR) Output: D:\durgaclasses\templates Note: The main advantage of this approach is we are not required to hard code system specific paths (locations) in our python script. Steps to develop Template Based Application: 1) Creation of Project django-admin startproject templateProject 2) Creation of Application py manage.py startapp testApp 3) Add this application to the project in settings.py file,so that Django aware of application 4) Create a 'templates' folder inside main project folder. In that templates folder create a seperate folder named with testApp to hold that particular application specific templates. 5) Add templates folder to settings.py file so that Django can aware of our templates. TEMPLATES = [ {..., 'DIRS': ['D:\djangoprojects\templateProject\templates'], },] It is not recommended to hard code system specific locations in settings.py file. To overcome this problem, we can generate templates directory path programatically as follows. import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath( file ))) TEMPLATE_DIR = os.path.join(BASE_DIR,'templates') Specify this TEMPLATE_DIR inside settings.py as follows TEMPLATES = [ {..., 'DIRS': [TEMPLATE_DIR,], },] 6) Create html file inside templateProject/templates/testApp folder. This html file is nothing but template. wish.html: 1) 2) 3) 4) 5) First Template Page 6) 7) 8) Hello welcome to Second Hero of MVT: Templates 9) 10) 7) Define Function based view inside views.py file 1) from django.shortcuts import render 2) def wish(request): 3) return render(request,'testApp/wish.html') 8) Define URL Pattern either at application level or at project level. 9) Run Server and send Request. Template Tags: From Python views.py we can inject dynamic content to the template file by using template tags. Template Tags also known as Template Variables. Take special care about Template tag syntax it is not python syntax and not html syntax. Just it is special syntax. Template Tag Syntax for inserting Text Data: { {insert_date} } This template tag we have to place inside template file (ie html file) and we have to provide insert_date value from python views.py file. Template Template Tags (Jinja2) views.py wish.html To insert dynamic Content inside Templates Application to send Date and Time from views.py to Template File: wish.html 1) 2) 3) 4) 5) First Template Page 6) 7) h1{ 8) color:white; 9) background: red; 10) } 11) 12) 13) 14) Hello Server Current Date and Time : 15) {{insert_date}} 16) 17) 18) views.py 1) from django.shortcuts import render 2) import datetime 3) def wish(request): 4) date=datetime.datetime.now() 5) my_dict={'insert_date':date} 6) return render(request,'testApp/wish.html',context=my_dict) Note: The values to the template variables should be passed from the view in the form of dictionary as argument to context. Application To display date, time and student information: views.py 1) from django.shortcuts import render 2) import datetime 3) 4) # Create your views here. 5) def template_view(request): 6) dt=datetime.datetime.now() 7) name='Durga' 8) rollno=101 9) marks=100 10) my_dict={'date':dt,'name':name,'rollno':rollno,'marks':marks} 11) return render(request,'testapp/results.html',my_dict) results.html 1) 2) 3) 4) 5) 6) body{ 7) background: green; 8) color:white; 9) } 10) h1{ 11) border:10px solid yellow; 12) } 13) 14) 15) 16) Hello this response from Template File.I will take care everything about pres entation 17) The Server Date and Time is:{{date}} 18) 19) Name:{{name}} 20) Rollno:{{rollno}} 21) Marks:{{marks}} 22) 23) 24) 25) Application to wish End User based on Time wish.html 1) 2) 3) 4) 5) First Template Page 6) 7) #h11{ 8) color:red; 9) } 10) #h12{ 11) color:green; 12) } 13) 14) 15) 16) {{insert_msg}} 17) Current Date and Time : {{insert_date}} 18) 19) views.py 1) from django.shortcuts import render 2) import datetime 3) 4) # Create your views here. 5) def wish(request): 6) date=datetime.datetime.now() 7) msg='Hello Guest !!!! Very Very Good ' 8) h=int(date.strftime('%H')) 9) if h> c = connection.cursor() ☕ If we are not getting any error means our database configurations are proper. nd DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 34 Configuration of MySQL Database: ☕ First we have to create our own logical database in the mysql. mysql> create database employeedb; ☕ We have to install mysqlclient by using pip as follows pip install --only-binary :all: mysqlclient settings.py 1) DATABASES = { 2) 'default': { 3) 'ENGINE': 'django.db.backends.mysql', 4) 'NAME': 'employeedb', 5) 'USER':'root', 6) 'PASSWORD':'root' 7) } 8) } Checking Configurations: D:\djangoprojects\modelProject>py manage.py shell >>> from django.db import connection >>> c = connection.cursor() Configuration of Oracle Database: 1) DATABASES = { 2) 'default': { 3) 'ENGINE': 'django.db.backends.oracle', 4) 'NAME': 'XE', 5) 'USER':'scott', 6) 'PASSWORD':'tiger' 7) } 8) } Note: We can find oracle database name by using the following command. SQL> select * from global_name; Model Class: ☕ A Model is a Python class which contains database information. ☕ A Model is a single, definitive source of information about our data. It contains fields and behavior of the data what we are storing. ☕ Each model maps to one database table. ☕ Every model is a Python class which is the child class of (django.db.models.Model) ☕ Each attribute of the model represents a database field. ☕ We have to write all model classes inside ‘models.py’ file. 1. Create a project and application and link them. django-admin startproject modelProject cd modelProject/ python manage.py startapp testApp After creating a project and application, in the models.py file, write the following code: models.py 1) from django.db import models 2) 3) # Create your models here. 4) class Employee(models.Model): 5) eno=models.IntegerField() 6) ename=models.CharField(max_length=30) 7) esal=models.FloatField() 8) eaddr=models.CharField(max_length=30) Note: This model class will be converted into Database table. Django is responsible for this. table_name: appName_Employee fields: eno, ename, esal and eaddr. And one extra field: id behaviors: eno is of type Integer, ename is of type Char and max_length is 30 characters. Hence, Model Class = Database Table Name + Field Names + Field Behaviors Converting Model Class into Database specific SQL Code: Once we write Model class, we have to generate the corresponding SQL Code. For this, we have to use “makemigrations” command. Python manage.py make migrations It results the following: Migrations for 'testApp': testApp/migrations/0001_initial.py - Create model Employee How to see corresponding SQL Code of Migrations: To see the generated SQL Code, we have to use the following command “sqlmigrate” python manage.py sqlmigrate testApp 0001 1) BEGIN; 2) -- 3) -- Create model Employee 4) -- 5) CREATE TABLE "testApp_employee" ("id" integer NOT NULL PRIMARY KEY AUTOIN CREMENT, "eno" integer NOT NULL, "ename" varchar(30) NOT NULL, "esal" real N OT NULL, "eaddr" varchar(30) NOT NULL); 6) COMMIT; Note: Here 0001 is the file passed as an argument “id” field: 1) For every table(model), Django will generate a special column named with “id”. 2) ID is a Primary Key. (Unique Identifier for every row inside table is considered as a primary key). 3) This field(id) is auto increment field and hence while inserting data, we are not required to provide data for this field. 4) This id field is of type “AutoField” 5) We can override the behavior of “id” field and we can make our own field as “id”. 6) Every Field is by default “NOT NULL”. How to execute generated SQL Code (migrate Command): After generating sql code, we have to execute that sql code to create table in database. For this, we have to use ‘migrate’ command. python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, testApp Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying sessions.0001_initial... OK Applying testApp.0001_initial... OK Note: Now tables will be created in the database. What is the Advantage of creating Tables with ‘migrate’ Command If we use ‘migrate’ command, then all Django required tables will be created in addition to our application specific tables. If we create table manually with sql code, then only our application specific table will be created and django my not work properly. Hence it is highly recommended to create tables with ‘migrate’ command. How to Check created Table in Django admin Interface: We have to register model class in ‘admin.py’ file. admin.py 1) from django.contrib import admin 2) from testApp.models import Employee 3) 4) # Register your models here. 5) 6) admin.site.register(Employee) Creation of Super User to login to admin Interface: ☕ We can create super user with the following command by providing username, mailid, password. python manage.py createsuperuser ☕ We can login to admin interface → Start the server and login to admin interface using the created credentials. ☕ python manage.py runserver ☕ Open the following in browser: http://127.0.0.1:8000/admin/ Difference between makemigrations and migrate: “makemigrations” is responsible to generate SQL code for Python model class whereas “migrate” is responsible to execute that SQL code so that tables will be created in the database. To Display Data in admin Interface in Browser: models.py 1) from django.db import models 2) 3) # Create your models here. 4) 5) class Employee(models.Model): 6) eno=models.IntegerField() 7) ename=models.CharField(max_length=30) 8) esal=models.FloatField() 9) eaddr=models.CharField(max_length=30) 10) def str (self): 11) return 'Employee Object with eno: +str(self.no)' admin.py 1) from django.contrib import admin 2) from testApp.models import Employee 3) 4) # Register your models here. 5) 6) class EmployeeAdmin(admin.ModelAdmin): 7) list_display=['eno','ename','esal','eaddr'] 8) 9) admin.site.register(Employee,EmployeeAdmin) Note: We should do this registration in a single line otherwise we are getting error. admin.site.register(Employee) admin.site.register(EmployeeAdmin) Practice Activity: Create the following tables and populate with some sample data 1. Job(posting date,location,offeredsalary,qualification) 2. Book(number,title,author,publisheddate) 3. Customer(name,ano,mailid,phonenumber,age) Now we can write views to get data from the database and send to template. Before writing views.py file, create “templates” and “static” folder with respective application folders and HTML and CSS files and link them in settings.py file. Views.py 1) from django.shortcuts import render 2) from testApp.models import Employee 3) 4) # Create your views here. 5) def empdata(request): 6) emp_list=Employee.objects.all() 7) my_dict={'emp_list':emp_list} 8) return render(request, 'testApp/emp.html', context=my_dict) emp.html 1) 2) {% load staticfiles %} 3) 4) 5) 6) 7) 8) 9) 10) 11) The employees list is : 12) 13) {% if emp_list %} 14) 15) 16) eno 17) ename 18) esal 19) eaddr 20) 21) 22) {% for emp in emp_list %} 23) 24) {{emp.eno}} 25) {{emp.ename}} 26) {{emp.esal}} 27) {{emp.eaddr}} 28) 29) {% endfor %} 30) 31) 32) {%else%} 33) No records found 34) {% endif %} 35) 36) 37) MVT Diagram Requesting Data Request Sending Data Views.py Models.py DB Sending Data Response User Templates Important FAQs Related to Model and database configurations: 1) How to configure database inside settings.py? 2) How to check connections? 3) How to define Model class inside models.py 4) How we can perform makemigrations? 5) How we can perform migrate? 6) How to add our model to admin interface inside admin.py 7) To display total data how to write ModelAdmin class inside admin.py 8) How to createsuperuser? 9) How to login to admin interface and add data to our tables? 10) How to see generated sqlcode b'z of makemigrations Faker Module: We can use Faker Module to generate fake data for our database models. 1) from faker import Faker 2) from random import * 3) fakegen=Faker() 4) name=fakegen.name() 5) print(name) 6) first_name=fakegen.first_name() 7) last_name=fakegen.last_name() 8) print(first_name) 9) print(last_name) 10) date=fakegen.date() 11) print(date) 12) number=fakegen.random_number(5) 13) print(number) 14) email=fakegen.email() 15) print(email) 16) print(fakegen.city()) 17) print(fakegen.random_int(min=0, max=9999)) 18) print(fakegen.random_element(elements=('Project Manager', 'TeamLead', 'Softwa re Engineer'))) Working with MYSQL Database (studentinfo project): settings.py 1) TEMPLATE_DIR=os.path.join(BASE_DIR,'templates') 2) INSTALLED_APPS = [ 3)...., 4) 'testapp' 5) ] 6) TEMPLATES = [ 7) { 8) 'BACKEND': 'django.template.backends.django.DjangoTemplates', 9) 'DIRS': [TEMPLATE_DIR], 10).... 11) } 12) ] 13) DATABASES = { 14) 'default': { 15) 'ENGINE': 'django.db.backends.mysql', 16) 'NAME': 'studentdb', 17) 'USER':'root', 18) 'PASSWORD':'root' 19) } 20) } models.py 1) from django.db import models 2) 3) # Create your models here. 4) class Student(models.Model): 5) name=models.CharField(max_length=30) 6) marks=models.IntegerField() admin.py 1) from django.contrib import admin 2) 3) # Register your models here. 4) from testapp.models import Student 5) class StudentAdmin(admin.ModelAdmin): 6) list_display=['name','marks'] 7) 8) admin.site.register(Student,StudentAdmin) views.py 1) from django.shortcuts import render 2) from testapp.models import Student 3) 4) # Create your views here. 5) def studentview(request): 6) student_list=Student.objects.order_by('marks') 7) my_dict={'student_list':student_list} 8) return render(request,'testapp/students.html',context=my_dict) students.html 1) 2) 3) 4) 5) 6) 7) 8) {%if student_list %} 9) 10) 11) Name 12) Marks 13) 14) {% for student in student_list %} 15) 16) {{student.name}} 17) {{student.marks}} 18) 19) {% endfor %} 20) 21) {% else %} 22) No Studetns found 23) {% endif %} 24) 25) urls.py 1) from django.conf.urls import url 2) from django.contrib import admin 3) from testapp import views 4) 5) urlpatterns = [ 6) url(r'^admin/', admin.site.urls), 7) url(r'^$', views.studentview), 8) ] Working with MYSQL Database and Faker Module (studentinfo Project): nd DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 45 settings.py 1) TEMPLATE_DIR=os.path.join(BASE_DIR,'templates') 2) STATIC_DIR=os.path.join(BASE_DIR,'static') 3) INSTALLED_APPS = [ 4)...., 5) 'testapp' 6) ] 7) TEMPLATES = [ 8) { 9) 'BACKEND': 'django.template.backends.django.DjangoTemplates', 10) 'DIRS': [TEMPLATE_DIR], 11).... 12) } 14) DATABASES = { 15) 'default': { 16) 'ENGINE': 'django.db.backends.mysql', 17) 'NAME': 'studentdb', 18) 'USER':'root', 19) 'PASSWORD':'root' 20) } 22) STATIC_URL = '/static/' 23) STATICFILES_DIRS=[ 24) STATIC_DIR, models.py 1) from django.db import models 2) 3) # Create your models here. 4) class Student(models.Model): 5) rollno=models.IntegerField() 6) name=models.CharField(max_length=30) 7) dob=models.DateField() 8) marks=models.IntegerField() 9) email=models.EmailField() 10) phonenumber=models.IntegerField(15) 11) address=models.TextField() admin.py 1) from django.contrib import admin 2) from testapp.models import Student 3) 4) # Register your models here. 5) class StudentAdmin(admin.ModelAdmin): 6) list_display=['rollno','name','dob','marks','email','phonenumber','address'] 7) 8) admin.site.register(Student,StudentAdmin) populate_student_info.py 1) import os 2) os.environ.setdefault('DJANGO_SETTINGS_MODULE','studentinfoproject.settings') 3) import django 4) django.setup() 5) 6) from testapp.models import Student 7) from faker import Faker 8) from random import * 9) fake=Faker() 10) def phonenumbergen(): 11) d1=randint(6,9) 12) num=''+str(d1) 13) for i in range(9): 14) num=num+str(randint(0,9)) 15) return int(num) 16) def populate(n): 17) for i in range(n): 18) frollno=fake.random_int(min=1,max=999) 19) fname=fake.name() 20) fdob=fake.date() 21) fmarks=fake.random_int(min=1,max=100) 22) femail=fake.email() 23) fphonenumber=phonenumbergen() 24) faddress=fake.address() 25) student_record=Student.objects.get_or_create(rollno=frollno,name=fname,do b=fdob,marks=fmarks,email=femail,phonenumber=fphonenumber,address=faddre ss) 26) populate(30) views.py 1) from django.shortcuts import render 2) from testapp.models import Student 3) 4) # Create your views here. 5) def home_page_view(request): 6) students=Student.objects.all() 7) #students=Student.objects.filter(marks lt=35) 8) #students=Student.objects.filter(name startswith='A') 9) #students=Student.objects.all().order_by('marks') 10) #students=Student.objects.all().order_by('-marks') 11) return render(request,'testapp/index.html',{'students':students}) index.html 1) 2) {%load staticfiles%} 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) Student Information 13) {% if students%} 14) {%for student in students%} 15) {{student.name}} Information 16) 17) Student Rollno:{{student.rollno}} 18) Student DOB:{{student.dob}} 19) Student Marks:{{student.marks}} 20) Student Email:{{student.email}} 21) Student Phone Number:{{student.phonenumber}} 22) Student Address:{{student.address}} 23) 24) 25) {%endfor%} 26) {%else%} 27) Student Records Are Not Available 28) {%endif%} 29) 30) 31) sinfo.css 1) body.container{ 2) background: red; 3) color:white; 4) } 5) h1{ 6) text-align: center; 7) } 8) h2{ 9) color:yellow; 10) } urls.py 1) from django.conf.urls import url 2) from django.contrib import admin 3) from testapp import views 4) 5) urlpatterns = [ 6) url(r'^admin/', admin.site.urls), 7) url(r'^$', views.home_page_view), 8) ] Unit-IV Working with Django Forms Django Forms: ☕ It is the very important concept in web development. ☕ The main purpose of forms is to take user input. Eg: login form, registration form, enquiry form etc ☕ From the forms we can read end user provided input data and we can use that data based on requirement. We may store in the database for future purpose. We may use just for validation/authentication purpose etc ☕ Here we have to use Django specific forms but not HTML forms. Advantages of Django Forms over HTML Forms: 1) We can develop forms very easily with python code 2) We can generate HTML Form widgets/components (like textarea, email, pwd etc) very quickly 3) Validating data will become very easy 4) Processing data into python data structures like list, set etc will become easy 5) Creation of Models based on forms will become easy etc. Process to generate Django Forms: Step-1: Creation of forms.py file in our application folder with our required fields. forms.py: 1) from django import forms 2) class StudentForm(forms.Form): 3) name=forms.CharField() 4) marks=forms.IntegerField() Note: name and marks are the field names which will be available in html form Step-2: usage of forms.py inside views.py file: views.py file is responsible to send this form to the template html file views.py: 1) from django.shortcuts import render 2) from. import forms 3) 4) # Create your views here. 5) def studentinputview(request): 6) form=forms.StudentForm() 7) my_dict={'form':form} 8) return render(request,'testapp/input.html',context=my_dict) # Alternative Short Way: 1) def studentinputview(request): 2) form=forms.StudentForm() 3) return render(request,'testapp/input.html',{'form':form}) Note: context parameter is optional.We can pass context parameter value directly without using keyword name 'context' Step-3: Creation of html file to hold form: Inside template file we have to use template tag to inject form {{form}} It will add only form fields. But there is no tag and no submit button. Even the fields are not arranged properly.It is ugly form. We can make proper form as follows 1) Registration Form 2) 3) 4) {{form.as_p}} 5) 6) 7) input.html: 1) 2) {%load staticfiles%} 3) 4) 5) 6) 7) 8) 9) 10) 11) Registration Form 12) 13) 14) {{form.as_p}} 15) 16) 17) 18) 19) If we submit this form we will get 403 status code response Forbidden (403) CSRF verification failed. Request aborted. Help Reason given for failure: CSRF token missing or incorrect. CSRF (Cross Site Request Forgery) Token: Every form should satisfy CSRF (Cross Site Request Forgery) Verification, otherwise Django won't accept our form. It is meant for website security. Being a programmer we are not required to worry anything about this. Django will takes care everything. But we have to add csrf_token in our form. 1) Registration Form 2) 3) 4) {{form.as_p}} 5) {% csrf_token %} 6) 7) 8) If we add csrf_token then in the generate form the following hidded field will be added,which makes our post request secure The value of this hidden field is keep on changing from request to request.Hence it is impossible to forgery of our request. If we configured csrf_token in html form then only django will accept our form. How to process Input Data from the form inside views.py File: We required to modify views.py file. The end user provided input is available in a dictionary named with 'cleaned_data' views.py: 1) from django.shortcuts import render 2) from. import forms 3) 4) # Create your views here. 5) def studentinputview(request): 6) form=forms.StudentForm() 7) if request.method=='POST': 8) form=forms.StudentForm(request.POST) 9) if form.is_valid(): 10) print('Form validation success and printing data') 11) print('Name:',form.cleaned_data['name']) 12) print('Marks:',form.cleaned_data['marks']) 13) return render(request,'testapp/input.html',{'form':form}) Student Name and Marks Submission Form Project (formproject1): forms.py 1) from django import forms 2) class StudentForm(forms.Form): 3) name=forms.CharField() 4) marks=forms.IntegerField() views.py 1) from django.shortcuts import render 2) from testapp.forms import StudentForm 3) # Create your views here. 4) def student_input_view(request): 5) sent=False 6) if request.method=='POST': 7) form=StudentForm(request.POST) 8) if form.is_valid(): 9) print('Form Validation Success and printing data') 10) print('Name:',form.cleaned_data['name']) 11) print('Marks:',form.cleaned_data['marks']) 12) sent=True 13) form=StudentForm() 14) return render(request,'testapp/input.html',{'form':form,'sent':sent}) input.html 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) {% if sent %} 12) Thanks for Providing Information 13) Enter Next Student Marks 14) {%else%} 15) Student Marks Submit Form 16) {%endif%} 17) 18) {{form.as_p}} 19) {%csrf_token%} 20) 21) 22) 23) 24) thankyou.html 1) 2) 3) 4) 5) 6) 7) 8) Thanks for providing your Name and Marks 9) 10) urls.py 1) from django.conf.urls import url 2) from django.contrib import admin 3) from testapp import views 4) 5) urlpatterns = [ 6) url(r'^admin/', admin.site.urls), 7) url(r'^input/', views.student_input_view), 8) ] Student FeedBack Form Project forms.py: 1) from django import forms 2) 3) class FeedBackForm(forms.Form): 4) name=forms.CharField() 5) rollno=forms.IntegerField() 6) email=forms.EmailField() 7) feedback=forms.CharField(widget=forms.Textarea) views.py 1) from django.shortcuts import render 2) from import forms 3) 4) def feedbackview(request): 5) form=forms.FeedBackForm() 6) if request.method=='POST': 7) form=forms.FeedBackForm(request.POST) 8) if form.is_valid(): 9) print('Form Validation Success and printing information') 10) print('Name:',form.cleaned_data['name']) 11) print('Roll No:',form.cleaned_data['rollno']) 12) print('Email:',form.cleaned_data['email']) 13) print('FeedBack:',form.cleaned_data['feedback']) 14) return render(request,'testapp/feedback.html',{'form':form}) feedback.html 1) 2) {% load staticfiles%} 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) Student Feedback Form 13) 14) {{form.as_p}} 15) {% csrf_token %} 16) 17) 18) 19) 20) Form Validations: Once we submit the form we have to perform validations like 1) Length of the field should not be empty 2) The max number of characters should be 10 3) The first character of the name should be 'd' etc We can implement validation logic by using the following 2 ways. 1) Explicitly by the programmer by using clean methods 2) By using Django inbuilt validators Note: All validations should be implemented in the forms.py file 1) Explicitly by the Programmer by using Clean Methods: The syntax of clean method: clean_fieldname(self) In the FormClass for any field if we define clean method then at the time of submit the form, Django will call this method automatically to perform validations. If the clean method won't raise any error then only form will be submitted. 1) from django import forms 2) 3) class FeedBackForm(forms.Form): 4) name=forms.CharField() 5) rollno=forms.IntegerField() 6) email=forms.EmailField() 7) feedback=forms.CharField(widget=forms.Textarea) 8) 9) def clean_name(self): 10) inputname=self.cleaned_data['name'] 11) if len(inputname) < 4: 12) raise forms.ValidationError('The Minimum no of characters in the name field should be 4') 13) return inputname The returned value of clean method will be considered by Django at the time of submitting the form. forms.py 1) from django import forms 2) from django.core import validators 3) 4) class FeedBackForm(forms.Form): 5) name=forms.CharField() 6) rollno=forms.IntegerField() 7) email=forms.EmailField() 8) feedback=forms.CharField(widget=forms.Textarea) 9) 10) def clean_name(self): 11) print('validating name') 12) inputname=self.cleaned_data['name'] 13) if len(inputname) < 4: 14) raise forms.ValidationError('The Minimum no of characters in the name field should be 4') 15) return inputname+'durga' 16) def clean_rollno(self): 17) inputrollno=self.cleaned_data['rollno'] 18) print('Validating rollno field') 19) return inputrollno 20) def clean_email(self): 21) inputemail=self.cleaned_data['email'] 22) print('Validating email field') 23) return inputemail 24) def clean_feedback(self): 25) inputfeedback=self.cleaned_data['feedback'] 26) print('Validating feedback field') 27) return inputfeedback Server Console: validating name Validating rollno field Validating email field Validating feedback field Form Validation Success and printing information Name: Durgadurga Roll No: 101 Email: [email protected] FeedBack: This is sample feedback Note: 1) Django will call these filed level clean methods automatically and we are not required to call explicitly. 2) Form validation by using clean methods is not recommended. 2) Django's Inbuilt Core Validators: ☕ Django provides several inbuilt core validators to perform very common validations. We can use these validators directly and we are not required to implement. ☕ Django's inbuilt validators are available in the django.core module. ☕ from django.core import validators ☕ To validate Max number of characters in the feedback as 40,we have to use inbuilt validators as follows. forms.py 1) from django import forms 2) from django.core import validators 3) 4) class FeedBackForm(forms.Form): 5) name=forms.CharField() 6) rollno=forms.IntegerField() 7) email=forms.EmailField() 8) feedback=forms.CharField(widget=forms.Textarea,validators= [validators.MaxLengthValidator(40)]) Note: We can use any number of validators for the same field feedback = forms.CharField(widget = forms.Textarea,validators = [validators.MaxLengthValidator(40),validators.MinLengthValidator(10)]) Note: Usage of built in validators is very easy when compared with clean methods. How to implement Custom Validators by using the same Validator Parameter: The value of name parameter should starts with 'd' or 'D'. We can implement this validation as follows 1) def starts_with_d(value): 2) if value.lower() != 'd': 3) raise forms.ValidationError('Name should be starts with d | D') 4) 5) class FeedBackForm(forms.Form): 6) name=forms.CharField(validators=[starts_with_d]) 7) rollno=forms.IntegerField() Validation of Total Form directly by using a Single Clean Method: Whenever we are submitting the form Django will call clean() method present in our Form class. In that method we can implement all validations. forms.py 1) from django import forms 2) from django.core import validators 3) 4) class FeedBackForm(forms.Form): 5) name=forms.CharField() 6) rollno=forms.IntegerField() 7) email=forms.EmailField() 8) feedback=forms.CharField(widget=forms.Textarea) 9) 10) def clean(self): 11) print('Total Form Validation...') 12) total_cleaned_data=super().clean() 13) inputname=total_cleaned_data['name'] 14) if inputname.lower() != 'd': 15) raise forms.ValidationError('Name parameter should starts with d') 16) inputrollno=total_cleaned_data['rollno'] 17) if inputrollno 7) Now define ModelForm class as: class MoviesForm(forms.ModelForm): movie_name=forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'})) release_date=forms.DateField(widget=DateInput(attrs={'class':'form-control'})) hero_name=forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'})) heroine_name=forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'})) director_name=forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'})) movie_ratings=forms.FloatField(widget=forms.TextInput(attrs={'class':'form-control'})) class Meta: model=MoviesModel fields=['movie_name','release_date','hero_name','heroine_name','director_name','movie _ratings'] --> Here 'class':'form-control' is a bootstrap class used to format the date field --> link Advanced Templates: 1) Template Inheritance 2) Template Filters 3) Template tags for relative URLs 1)Template Inheritance: ☕ If multiple template files have some common code,it is not recommended to write that common code in every template html file. It increases length of the code and reduces readability. It also increases development time. ☕ We have to seperate that common code into a new template file,which is also known as base template. The remaining template files should required to extend base template so that the common code will be inherited automatically. ☕ Inheriting common code from base template to remaining templates is nothing but template inheritance. How to implement Template Inheritane: base.html 1) 2) html,css,bootstrap links 3) 4) common code required for every child tempalte 5) {% block child_block%} 6) Anything outside of this block available to child tag. 7) in child template the specific code should be in this block 8) {%endblock%} 9) 10) child.html 1) 2) {%extends 'testapp/base.html'%} 3) {% block child_block %} 4) child specific extra code 5) {%endblock%} ------------------------ 1) body{ 2) background: url(https://images.unsplash.com/photo-1460650671472- ba449b1a6f10?ixlib=rb- 0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=daeb797a01124d5e37bdb0f543314f90&au to=format&fit=crop&w=666&q=80); 3) background-repeat: no-repeat; 4) background-size: cover; 5) 6) } 7).navbar{ 8) background:orange; 9) } 10).navbar a{ 11) color:white; 12) } 13) img{ 14) height: 200px; 15) width: 30%; 16) margin:1.5%; 17) border:2px orange solid; 18) } 19) #home{ 20) font-size: 100px; 21) font-weight: 900; 22) color:white; 23) text-align: center; 24) } 25) h1{ 26) font-size: 40px; 27) font-weight: 900; 28) color:white; 29) text-align: center; 30) } 31) li{ 32) color:yellow; 33) font-size: 30px; 34) } Advantages of Template Inheritance: 1) What ever code available in base template is by default available to child templates and we are not required to write again.Hence it promotes Code Reusability (DRY). 2) It reduces length of the code and improves readability. 3) It reduces development time. 4) It provides unique and same look and feel for total web application. Note: Based on our requirement we can extend any number of base templates.i.e Multiple Inheritance is applicable for templates. How to Add Seperate CSS Files to Child Templates? base.html 1) 2) {%load staticfiles %} 3) 4) 5) 6) 7) 8) 9) {% block xyz %}{% endblock %} 10) 11) 12) 13) 14) 15) 16) DURGA NEWS 17) 18) 19) Home 20) Movies 21) Sports 22) Politics 23) 24) 25) 26) {% block body_block %} 27) {% endblock %} 28) 29) child.html 1) 2) {% extends 'testapp/base.html'%} 3) {%load staticfiles%} 4) {% block xyz %} 5) 6) {%endblock%} 7) {% block body_block %} 8) Welcome to DURGA NEWS PORTAL 9) {% endblock %} User Authentication and Authorization Authentication: The process of validating user is called authentication. Authorization: The process of validating access permissions of user is called authorization. Generally our web pages can be accessed by any person without having any restrictions. But some times our business requirement is to access a web page compulsory we have to register and login.Then only end user can able to access our page. To fulfill such of requirements we should go for Django authentication and authorization module. (auth application) Django provides the following 2 in built applications for user authentication. 1) django.contrib.auth 2) django.contrib.contenttypes auth application is authentication application of Django. This auth application internally uses contenttypes application to track models installed in our database. Note: To use Django in built authentication facility, compulsory these 2 applications should be in INSTALLED_APPS list. But from Django 1.10 onwards automatically these are available and we are not required to add explicitly. Django uses PBKDF2_Sha256 algorithm to encrypt passwords and hence passwords won't be stored in plain text form and we can expect more security. Even superuser also cannot see any user's password. Based on our requirement, we can use more secure hashing algorithms also like bcrypt and argon2. We can install with pip as follows. pip install bcrypt pip install django[argon2] More secured algorithm is argon2 and then bcrypt followed PBKDF2. In settings.py we have to configure password hashers as follows. 1) PASSWORD_HASHERS=[ 2) 'django.contrib.auth.hashers.Argon2PasswordHasher', 3) 'django.contrib.auth.hashers.BCryptSHA256PasswordHasher', 4) 'django.contrib.auth.hashers.BCryptPasswordHasher', 5) 'django.contrib.auth.hashers.PBKDF2PasswordHasher', 6) 'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher', 7) ] Django will always consider from first to last. ie order is important. Just like templates and static folder, we have to create media folder also. How to Configure Media Folder in settings.py File: MEDIA_DIR = os.path.join(BASE_DIR,'media') MEDIA_ROOT = MEDIA_DIR MEDIA_URL = '/media/' from django.contrib.auth.decorators import login_required @login_required def java_exams_view(request): return render(request,'testapp/java.html') If we use @login_required decorator for any view function,then auth application will check whether user login or not. If the user not login then the control will be forwarded to login page. http://127.0.0.1:8000/accounts/login/?next=/java/ We have to configure auth application url patterns in urls.py file. from django.conf.urls import url,include url('accounts/', include('django.contrib.auth.urls')), In our project auth application urls also included. TemplateDoesNotExist at /accounts/login/registration/login.html login link of auth application: /accounts/login/ logout link of auth application: /accounts/logout After logout then Django default logout page will be displayed. Instead of this default target page we can configure our own target page inside settings.py as follows. LOGOUT_REDIRECT_URL='/' If we click login link explicitly and after login by default the control will goes to http://127.0.0.1:8000/accounts/profile/ But we can configure our own target page after login inside settings.py as follows. LOGIN_REDIRECT_URL='/' Authentication Application: views.py 1) from django.shortcuts import render 2) from django.contrib.auth.decorators import login_required 3) 4) # Create your views here. 5) def home_page_view(request): 6) return render(request,'testapp/home.html') 6) 8) @login_required 9) def java_exams_view(request): 10) return render(request,'testapp/javaexams.html') 11) @login_required 12) def python_exams_view(request): 13) return render(request,'testapp/pythonexams.html') 14) @login_required 15) def aptitude_exams_view(request): 16) return render(request,'testapp/aptitudeexams.html') 17) 18) def logout_view(request): 19) return render(request,'testapp/logout.html') urls.py 1) from django.conf.urls import url,include 2) from django.contrib import admin 3) from testapp import views 4) 5) urlpatterns = [ 6) path(r'^admin/', admin.site.urls), 7) path ('accounts/',include('django.contrib.auth.urls')), 8) path (r' ', views.home_page_view), 9) path (r'^python/', views.python_exams_view), 10) path (r'^java/', views.java_exams_view), 11) path (r'^aptitude/', views.aptitude_exams_view), 12) path (r'^logout/', views.logout_view), 13) ] auth123.css 1) body{ 2) background: #efb917; 3) color:blue; 4) } 5).jumbotron{ 6) background: green; 7) color:white; 8) } base.html 1) 2) {%load staticfiles%} 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15) DDUGUEXAMS 16) 17) 18) Java Exams 19) Python Exams 20) Aptitude Exams 21) 22) 23) Signup 24) Login 25) Logout 26) 27) 28) 29) {%block body_block%} 30) {%endblock%} 31) 32) home.html 1) 2) {%extends 'testapp/base.html'%} 3) {%block body_block%} 4) 5) 6) Welcome to DDUGU Exams 7) Rules: 8) 9) Rule-1:You should write only one exam per day 10) Rule-1:You should write only one exam per day 11) Rule-1:You should write only one exam per day 12) Rule-1:You should write only one exam per day 13) Rule-1:You should write only one exam per day 14) Rule-1:You should write only one exam per day 15) Rule-1:You should write only one exam per day 16) 17) 18) 19) {%endblock%} javaexams.html 1) 2) {%extends 'testapp/base.html'%} 3) {%block body_block%} 4) 5) 6) Welcome to Java Exams 7) 8) 9) {%endblock%} pythonexams.html 1) 2) {%extends 'testapp/base.html'%} 3) {%block body_block%} 4) 5) 6) Welcome to Python Exams 7) 8) 9) {%endblock%} aptitudeexams.html 1) 2) {%extends 'testapp/base.html'%} 3) {%block body_block%} 4) 5) 6) Welcome to Aptitude Exams 7) 8) 9) {%endblock%} registration/login.html 1) 2) {%extends 'testapp/base.html'%} 3) {%block body_block%} 4) 5) Login to write Exams... 6) 7) {{form.as_p}} 8) {%csrf_token%} 9) Login 10) 11) 12) {%endblock%} testapp/logout.html 1) 2) {%extends 'testapp/base.html'%} 3) {%block body_block%} 4) 5) 6) Thanks for visiting Durgaexams 7) Anyway we are feeling very sad b'z you logout atleast 24 hours per day you have to spend with our website like facebook 8) Please Login Again: 9) Login 10) 11) 12) {%endblock%} settings.py 1) LOGIN_REDIRECT_URL='/' 2) LOGOUT_REDIRECT_URL='/logout' Configure Signup Form: forms.py 1) from django import forms 2) from django.contrib.auth.models import User 3) class SignUpForm(forms.ModelForm): 4) class Meta: 5) model=User 6) fields=['username','password','email','first_name','last_name'] views.py 1) def signup_view(request): 2) form=SignUpForm() 3) if request.method=='POST': 4) form=SignUpForm(request.POST) 5) user=form.save() 6) user.set_password(user.password) 7) user.save() 8) return HttpResponseRedirect('/accounts/login') 9) return render(request,'testapp/signup.html',{'form':form}) urls.py 1) urlpatterns = [ 2).... 3) url(r'^signup/', views.signup_view), 4) ]

Use Quizgecko on...
Browser
Browser