Web Application using Django
(Session Management)
Presented by
Mr.B.Muthukrishna Vinayagam, AP-CSE
Cookies
• HTTP’s statelessness poses a huge problem for Web developers, and thus cookies
were born. A cookie is a small piece of information that browsers store on behalf of
Web servers.
• COOKIES is a special attribute of request, and its value is the name of the cookie
from which you want to read data
– Using request.COOKIES[]
• Basic syntax to access a class parameter as: request.COOKIES[‘cookie_name’]
• Using Directmethod: request.COOKIES.get(key,value)
• Using response object with following function to set and delete cookie.
– set_cookie() to create cookies, we can also delete cookies using a similar function, delete_cookie()
Views.py
def chk(request):
count=request.COOKIES.get('count',0)
tc=int(count)+1
response=render(request,"testck.html",{'count':tc})
response.set_cookie('count',tc)
return response
def dck(request):
response = HttpResponse("Deleting the cookie which is set")
response.delete_cookie('count','Updated Successfully')
return response
from django.urls import reverse
return res
def reset(request):
res=HttpResponse("cookies deleted <a
href='{}'>reload</a>".format(reverse('index')))
res.delete_cookie('count','Updated
Successfully')
return res
testck.html
<h1> User Visit(s) {{count}}</h1>
urls.py
from django.contrib import admin
from django.urls import path
from APP import views
urlpatterns = [
path('admin/', admin.site.urls),
path("chk",views.chk,name="chk"),
path("dck",views.dck,name="dck"),]
]
Session
Sessions are the mechanism used by Django (and most of the
Internet) for keeping track of the "state" between the site and a
particular browser.
The session is a semi-permanent and two-way communication
between the server and the browser.
Syntax
# Get a session value, setting a default if it is not present (0)
count= request.session.get(' count ',0)
# Set a session value
request.session[' count '] =0
# Delete a session value
del request.session[' count ']
Views.py
def chk(request):
count=request.session.get('count',0)
tc=int(count)+1
response=render(request,"testck.html",{'count':tc})
return response
def dck(request):
del request.session['count']
response = HttpResponse("Deleting the session key which is set")
return response
testck.html
<h1> User Visit(s) {{count}}</h1>
urls.py
from django.contrib import admin
from django.urls import path
from APP import views
urlpatterns = [
path('admin/', admin.site.urls),
path("chk",views.chk,name="chk"),
path("dck",views.dck,name="dck"),]
]
Session Example2
(logging and logout with Session)
forms.py
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class NewUserForm(UserCreationForm):
class Meta:
model=User
fields=['username','email','password1','password2']
Views.py
from django.shortcuts import render,HttpResponse,redirect
from django.contrib.auth import authenticate,login,logout
from.forms import *
def signup(request):
if request.method=='POST':
form = NewUserForm(request.POST)
if form.is_valid():
form.save()
return redirect('login')
else:
form = NewUserForm()
return render(request, 'signup.html', {'form': form })
def loginpage(request):
if request.method=='POST':
username=request.POST.get('username')
pass1=request.POST.get('password')
user=authenticate(request,username=username,password=pass1)
if user is not None:
login(request,user)
request.session["uname"] = username
return redirect('home')
else:
return HttpResponse ("Username or Password is incorrect!!!")
return render (request,'login.html')
def home(request):
uname =request.session["uname"]
return render (request,'home.html',{'uname': uname})
def logoutpage(request):
del request.session["uname"]
logout(request)
return redirect('login')
templates
signup.html
<form action="" method="post">
{%csrf_token %}
{{form.as_p}}
<input type="submit" value="New User"/>
</form>
<a href="{% url 'login' %}" >signup</a>
login.html
<form action="" method="post">
{%csrf_token %}
<input type="text" name="username" id="username" placeholder="username"/><br/>
<input type="password" name="password" id="password" placeholder="password"/><br/
<input type="submit" value="Login"/>
</form>
<a href="{% url 'signup' %}" >Signup </a>
home.html
<body>
<h1>Home Page</h1>
<h2>Welcome! {{uname}} </h2>
<a href="{% url 'logout' %}">Logout</a>
</body>
urls.py
from django.contrib import admin
from django.urls import path
from myapp.views import *
urlpatterns = [
path('admin/', admin.site.urls),
path('home/',home,name='home'),
path('',signup,name='signup'),
path('login/',loginpage,name='login'),
path('logout/',logoutpage,name='logout')
]
mail
from django.core.mail import send_mail
send_mail(
"Subject here",
"Here is the message.",
"from@example.com",
["to@example.com"],
fail_silently=False,
)
settings.py
EMAIL_BACKEND =
'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp-mail.outlook.com’
#smtp.gmail.com
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = 'xxxx'
EMAIL_HOST_PASSWORD = 'xxxxxx' #app password
Include Bootstrap
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Index web page</title>
<link rel="stylesheet" href="{% static 'cssbootstrap.min.css'
%}">
</head>
<body>
<script src="{% static 'jsbootstrap.bundle.min.js'
%}"></script>
<nav class="navbar navbar-expand-sm bg-dark navbar-dark
sticky-top">
<div class="container-fluid">
<a class="navbar-brand" href="index.html">Logo</a>
<button class="navbar-toggler" type="button"
data-bs-toggle="collapse" data-bs-target="#id">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse bg-dark" id="id">
<ul class="navbar-nav">
<li class="nav-item">
<a href="{% url 'reset' %}" class="nav-link">Reset</a>
</li>
{%if uname%}
<li class="nav-item">
<a href="{% url 'logout'%}" class="nav-link">Logout</a>
</li>
{% else%}
<li class="nav-item">
<a href="{% url 'login' %}" class="nav-link">Login</a>
</li>
<li class="nav-item">
<a href="{% url 'signup' %}" class="nav-link">SignUp</a>
</li>
{%endif%}
</ul>
</div>
</div>
</nav>
</body> </html>
Settings.py
import os
STATIC_URL = '/static/'
STATICFILES_DIRS = [(os.path.join(BASE_DIR, 'static'))]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
Urls.py:
urlpatterns +=
static(settings.STATIC_URL,document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Thank you

session faculty development programme.pptx

  • 1.
    Web Application usingDjango (Session Management) Presented by Mr.B.Muthukrishna Vinayagam, AP-CSE
  • 2.
    Cookies • HTTP’s statelessnessposes a huge problem for Web developers, and thus cookies were born. A cookie is a small piece of information that browsers store on behalf of Web servers. • COOKIES is a special attribute of request, and its value is the name of the cookie from which you want to read data – Using request.COOKIES[] • Basic syntax to access a class parameter as: request.COOKIES[‘cookie_name’] • Using Directmethod: request.COOKIES.get(key,value) • Using response object with following function to set and delete cookie. – set_cookie() to create cookies, we can also delete cookies using a similar function, delete_cookie()
  • 4.
    Views.py def chk(request): count=request.COOKIES.get('count',0) tc=int(count)+1 response=render(request,"testck.html",{'count':tc}) response.set_cookie('count',tc) return response defdck(request): response = HttpResponse("Deleting the cookie which is set") response.delete_cookie('count','Updated Successfully') return response
  • 5.
    from django.urls importreverse return res def reset(request): res=HttpResponse("cookies deleted <a href='{}'>reload</a>".format(reverse('index'))) res.delete_cookie('count','Updated Successfully') return res
  • 6.
    testck.html <h1> User Visit(s){{count}}</h1> urls.py from django.contrib import admin from django.urls import path from APP import views urlpatterns = [ path('admin/', admin.site.urls), path("chk",views.chk,name="chk"), path("dck",views.dck,name="dck"),] ]
  • 7.
    Session Sessions are themechanism used by Django (and most of the Internet) for keeping track of the "state" between the site and a particular browser. The session is a semi-permanent and two-way communication between the server and the browser.
  • 8.
    Syntax # Get asession value, setting a default if it is not present (0) count= request.session.get(' count ',0) # Set a session value request.session[' count '] =0 # Delete a session value del request.session[' count ']
  • 9.
    Views.py def chk(request): count=request.session.get('count',0) tc=int(count)+1 response=render(request,"testck.html",{'count':tc}) return response defdck(request): del request.session['count'] response = HttpResponse("Deleting the session key which is set") return response
  • 10.
    testck.html <h1> User Visit(s){{count}}</h1> urls.py from django.contrib import admin from django.urls import path from APP import views urlpatterns = [ path('admin/', admin.site.urls), path("chk",views.chk,name="chk"), path("dck",views.dck,name="dck"),] ]
  • 11.
    Session Example2 (logging andlogout with Session) forms.py from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class NewUserForm(UserCreationForm): class Meta: model=User fields=['username','email','password1','password2']
  • 12.
    Views.py from django.shortcuts importrender,HttpResponse,redirect from django.contrib.auth import authenticate,login,logout from.forms import * def signup(request): if request.method=='POST': form = NewUserForm(request.POST) if form.is_valid(): form.save() return redirect('login') else: form = NewUserForm() return render(request, 'signup.html', {'form': form })
  • 13.
    def loginpage(request): if request.method=='POST': username=request.POST.get('username') pass1=request.POST.get('password') user=authenticate(request,username=username,password=pass1) ifuser is not None: login(request,user) request.session["uname"] = username return redirect('home') else: return HttpResponse ("Username or Password is incorrect!!!") return render (request,'login.html')
  • 14.
    def home(request): uname =request.session["uname"] returnrender (request,'home.html',{'uname': uname}) def logoutpage(request): del request.session["uname"] logout(request) return redirect('login')
  • 15.
    templates signup.html <form action="" method="post"> {%csrf_token%} {{form.as_p}} <input type="submit" value="New User"/> </form> <a href="{% url 'login' %}" >signup</a>
  • 16.
    login.html <form action="" method="post"> {%csrf_token%} <input type="text" name="username" id="username" placeholder="username"/><br/> <input type="password" name="password" id="password" placeholder="password"/><br/ <input type="submit" value="Login"/> </form> <a href="{% url 'signup' %}" >Signup </a> home.html <body> <h1>Home Page</h1> <h2>Welcome! {{uname}} </h2> <a href="{% url 'logout' %}">Logout</a> </body>
  • 17.
    urls.py from django.contrib importadmin from django.urls import path from myapp.views import * urlpatterns = [ path('admin/', admin.site.urls), path('home/',home,name='home'), path('',signup,name='signup'), path('login/',loginpage,name='login'), path('logout/',logoutpage,name='logout') ]
  • 18.
    mail from django.core.mail importsend_mail send_mail( "Subject here", "Here is the message.", "from@example.com", ["to@example.com"], fail_silently=False, )
  • 19.
    settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST ='smtp-mail.outlook.com’ #smtp.gmail.com EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'xxxx' EMAIL_HOST_PASSWORD = 'xxxxxx' #app password
  • 20.
    Include Bootstrap {% loadstatic %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Index web page</title> <link rel="stylesheet" href="{% static 'cssbootstrap.min.css' %}"> </head> <body> <script src="{% static 'jsbootstrap.bundle.min.js' %}"></script> <nav class="navbar navbar-expand-sm bg-dark navbar-dark sticky-top"> <div class="container-fluid"> <a class="navbar-brand" href="index.html">Logo</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#id"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse bg-dark" id="id"> <ul class="navbar-nav"> <li class="nav-item"> <a href="{% url 'reset' %}" class="nav-link">Reset</a> </li> {%if uname%} <li class="nav-item"> <a href="{% url 'logout'%}" class="nav-link">Logout</a> </li> {% else%} <li class="nav-item"> <a href="{% url 'login' %}" class="nav-link">Login</a> </li> <li class="nav-item"> <a href="{% url 'signup' %}" class="nav-link">SignUp</a> </li> {%endif%} </ul> </div> </div> </nav> </body> </html>
  • 21.
    Settings.py import os STATIC_URL ='/static/' STATICFILES_DIRS = [(os.path.join(BASE_DIR, 'static'))] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') Urls.py: urlpatterns += static(settings.STATIC_URL,document_root=settings.STATIC_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
  • 22.