Saturday, 16 September 2023

Server

 Python manage.py runserver ===> It is used for Development server, it has good feature auto restart when we are add or edit smoothing development time, as well as servers static files.

Default port server ===> localhost:8000  


But production we required our application more secure needed,

WSGI(Web server gateway interface): WSGi basically interact with python app and web Server.


gunicorn server example of WSGI

nginx example of web server

static code - image, js file, css file

Dynamic code - python code


Gunicorn: Gunicorn, is a Web Server Gateway Interface (WSGI), WSGI server such as gunicorn

1. proper logging feature

2. it fast

3. it has buildin security mesure

4. It is ideally used production or staging enverment in django web app

5. WSGI server such as gunicorn not able to automatically served static files, that's why NGINX web server needs


NGINX is reverse proxy server that accept request from client and respond to the client 







Monday, 4 September 2023

QuerySet

 models.py

from django.db import models
from django.contrib.auth.models import User
from django.core.validators import MinValueValidator, MaxValueValidator
from django.core.exceptions import ValidationError


def validate_restaurant_name_begins_with_a(value):
    if not value.startswith('a'):
        raise ValidationError('Restaurant name must begin with "a"')


class Restaurant(models.Model):
    class TypeChoices(models.TextChoices):
        INDIAN = 'IN', 'Indian'
        CHINESE = 'CH', 'Chinese'
        ITALIAN = 'IT', 'Italian'
        GREEK = 'GR', 'Greek'
        MEXICAN = 'MX', 'Mexican'
        FASTFOOD = 'FF', 'Fast Food'
        OTHER = 'OT', 'Other'


    name = models.CharField(max_length=100, validators=[validate_restaurant_name_begins_with_a])
    website = models.URLField(default='')
    date_opened = models.DateField()
    latitude = models.FloatField(validators=[MinValueValidator(-90), MaxValueValidator(90)])
    longitude = models.FloatField(validators=[MinValueValidator(-180), MaxValueValidator(180)])
    restaurant_type = models.CharField(max_length=2, choices=TypeChoices.choices)

    def __str__(self):
        return self.name


class Rating(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE, related_name='ratings')
    rating = models.PositiveSmallIntegerField(
        validators=[MinValueValidator(1), MaxValueValidator(5)]
    )

    def __str__(self):
        return f"Rating: {self.rating}"
   

class Sale(models.Model):
    restaurant = models.ForeignKey(
        Restaurant, on_delete=models.SET_NULL, null=True, related_name='sales')
    income = models.DecimalField(max_digits=8, decimal_places=2)
    datetime = models.DateTimeField()

views.py

How to access parent model to child model using for loop .py file

Here "ratings" related_name

    restaurants = Restaurant.objects.all()# filter(name__istartswith='a')
    for i in restaurants:
        for j in i.ratings.all():
            print(j.rating)

How to access parent model to child model using for loop .html file

        {% for res in restaurants %}
            <p>{{res.name}}</p>
             <ul>
                {% for rat in res.ratings.all %}
                    <li>{{rat.rating}}</li>
                {% endfor %}
            </ul>
         {% endfor %}

How to access parent and child togather like object in .py file










Saturday, 29 July 2023

Django Channel

ppt1

WebSocket

WebSocket is a full-duplex (two-way communication) protocol that is used in the same scenario of client-server communication.

It is a stateful protocol, which means the connection between client and server will keep alive until it is terminated by either client or server, after closing the connection by either of the client and server, the connection is terminated from both the end. 

WebSockets do not use the http:// or https:// scheme (because they do not follow the HTTP protocol).

Rather, WebSocket URIs use a new scheme ws: (or wss: for a secure WebSocket). 

The remainder of the URI is the same as an HTTP URI: a host, port, path and any query parameters.

Example:- ws://example.com:8000/ws/chat

Configuring Django Channel

gs1- ppt2

Install using pip

                pip install channels

Uninstall using pip

pip uninstall channels

Adding Channels to Django Project

INSTALLED_APPS = [

    ‘channels’,

    …

]

asgi.py

from channels.routing import ProtocolTypeRouter
application = ProtocolTypeRouter({
    "http": get_asgi_application(),
    # Just HTTP for now. (We can add other protocols later.)
})

settings.py

#WSGI_APPLICATION = 'gs1.wsgi.application'
ASGI_APPLICATION = 'gs1.asgi.application'

gs2- ppt3

Consumers

A consumer is the basic unit of Channels code. Consumers are like Django views.

Creating Consumers:-

  1. SyncConsumer
  2. AsyncConsumer
1. SyncConsumer

A consumer is a subclass of either SyncConsumer or AsyncConsumer.
SyncConsumer will run your code synchronously in a threadpool.
app/consumers.py

2.AsyncConsumer

AsyncConsumer will expect you to write async-capable code.
app/consumers.py

consumers.py

# Topic - Consumer
from channels.consumer import SyncConsumer, AsyncConsumer
class MySyncConsumer(SyncConsumer):
  # This handler is called when client initially opens a connection and is about to finish the WebSocket handshake.
  def websocket_connect(self, event):
    print('Websocket Connected...')

  # This handler is called when data received from Client
  def websocket_receive(self, event):
    print('Messaged Received...')

  # This handler is called when either connection to the client is lost, either from the client closing the connection, the server closing the connection, or loss of the socket.  
  def websocket_disconnect(self, event):
    print('Websocket Disconnected...')

class MyAsyncConsumer(AsyncConsumer):
  # This handler is called when client initially opens a connection and is about to finish the WebSocket handshake.
  async def websocket_connect(self, event):
    print('Websocket Connected...')

  # This handler is called when data received from Client
  async def websocket_receive(self, event):
    print('Messaged Received...')

  # This handler is called when either connection to the client is lost, either from the client closing the connection, the server closing the connection, or loss of the socket.  
  async def websocket_disconnect(self, event):
    print('Websocket Disconnected...')

gs3- ppt4 

Routing

 This is similar to Django’s as_view(), which plays the same role for per-request instances of class-based views.

  • Create routing.py File then write all websocket url patterns inside this file.
  • Open asgi.py file and mentioned your routing.py file

app/routing.py

from django.urls import path
from . import consumers

websocket_urlpatterns = [
  path('ws/sc/', consumers.MySyncConsumer.as_asgi()),
  path('ws/ac/', consumers.MyAsyncConsumer.as_asgi()),
]

gs3/asgi.py

import os
from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter, URLRouter
import app.routing
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'gs3.settings')

application = ProtocolTypeRouter({
  'http': get_asgi_application(),
  'websocket': URLRouter(
    app.routing.websocket_urlpatterns
  )
})

gs4- ppt5

Consumers

A consumer is the basic unit of Channels code. Consumers are like Django views.

Allow you to write synchronous or async code and deals with handoffs and threading for you.

A consumer is a subclass of either SyncConsumer or AsyncConsumer.

  1. SyncConsumer will run your code synchronously in a threadpool.
  2. AsyncConsumer will expect you to write async-capable code.

app/consumers.py

# Topic - More on Consumer and Routing
from channels.consumer import SyncConsumer, AsyncConsumer
from channels.exceptions import StopConsumer

class MySyncConsumer(SyncConsumer):
  # when client(application) send somthing to the server ai event(message) call, handshake ar aga pajanta
  # two way connection enable hoya jaba
  def websocket_connect(self, event):
    print('Websocket Connected...', event)
    # client(application) thaka jata as66a sata accept karar janna
    self.send({
      'type':'websocket.accept',
    })
 
  # when Message received from Client ai event(message) call
  def websocket_receive(self, event):
    print('Message received from Client', event)
    print(event['text'])
    # when server send somthing to the client
    self.send({
      'type':'websocket.send', # for send
      'text':'Message Sent to Client' # what server wants to send
    })

  # when server or client au akjon disconnect kora connection ai event(message) call
  def websocket_disconnect(self, event):
    print('Websocket Disconnected...', event)
    # ata lik66i karon jata error na asa(ata ho66a exception(mana exception handel kor66i))
    raise StopConsumer()

class MyAsyncConsumer(AsyncConsumer):
  async def websocket_connect(self, event):
    print('Websocket Connected...', event)
    await self.send({
      'type':'websocket.accept',
    })
 
  async def websocket_receive(self, event):
    print('Message received from Client', event)
    print(event['text'])
    await self.send({
      'type':'websocket.send',
      'text':'Message Sent to Client'
    })

  async def websocket_disconnect(self, event):
    print('Websocket Disconnected...', event)
    raise StopConsumer()


Real Time Data (syncConsumer vs AsyncConsumer) No ppt gs5


gs6- ppt6

WebSocket

The WebSocket object provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection.

To construct a WebSocket, use the WebSocket() constructor.

Example:- 

var ws =  new WebSocket('ws://127.0.0.1:8000/ws/sc/’);

WebSocket Properties

onopen 

ws.onopen = function (event) {

      console.log("WebSocket Connection open“, event);

    };

onmessage 

 ws.onmessage = function (event) {

      console.log("WebSocket message received from server”, event);

    };

onerror 

 ws.onerror = function (event) {

      console.log(“WebSocket Error Occurred”, event);

    };

onclose 

 ws.onclose = function (event) {
      console.log(“WebSocket Connection Closed”, event);
    };

Events

open

ws.addEventListener('open', (event) => {
   console.log("WebSocket Connection open");
});

message

ws.addEventListener('message', (event) => {
    console.log(' WebSocket message received from server', event);
});

error

ws.addEventListener(‘error', (event) => {
   console.log(“WebSocket Error Occurred“, event);
});

close

ws.addEventListener(‘close', (event) => {
    console.log('WebSocket connections Closed ', event);
});


Methods
close() – The WebSocket.close() method closes the WebSocket connection or connection attempt, if any. If the connection is already CLOSED, this method does nothing.
Syntax:- ws.close(code, reason)
code - A numeric value indicating the status code explaining why the connection is being closed. If this parameter is not specified, a default value of 1005 is assumed.
reason – A human-readable string explaining why the connection is closing. This string must be no longer than 123 bytes of UTF-8 text (not characters).
Example:- ws.close()



send() – The WebSocket.send() method enqueues the specified data to be transmitted to the server over the WebSocket connection.
If the data can't be sent, the socket is closed automatically. 
The browser will throw an exception if you call send() when the connection is in the CONNECTING state. 
If you call send() when the connection is in the CLOSING or CLOSED states, the browser will silently discard the data.
Syntax:- ws.send(data)
Example:- ws.send(“Hello”)

consumers.py
# Topic - Web API WebSocket - JavaScript
from channels.consumer import SyncConsumer, AsyncConsumer
from channels.exceptions import StopConsumer
from time import sleep
import asyncio

class MySyncConsumer(SyncConsumer):
  def websocket_connect(self, event):
    print('Websocket Connected...', event)
    self.send({
      'type':'websocket.accept',
    })
 
  def websocket_receive(self, event):
    print('Message received from Client', event)
    print(event['text'])
    for i in range(10):
      self.send({
        'type':'websocket.send',
        'text': str(i)
      })
      sleep(1)

  def websocket_disconnect(self, event):
    print('Websocket Disconnected...', event)
    raise StopConsumer()

class MyAsyncConsumer(AsyncConsumer):
  async def websocket_connect(self, event):
    print('Websocket Connected...', event)
    await self.send({
      'type':'websocket.accept',
    })
 
  async def websocket_receive(self, event):
    print('Message received from Client', event)
    print(event['text'])
    for i in range(50):
      await self.send({
        'type':'websocket.send',
        'text': str(i)
      })
      await asyncio.sleep(1)

  async def websocket_disconnect(self, event):
    print('Websocket Disconnected...', event)
    raise StopConsumer()

templates\app\index.html
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <h1>Count Page</h1>

  <script>
    var ws = new WebSocket('ws://127.0.0.1:8000/ws/sc/')

    ws.onopen = function () {
      console.log('Websocket connection open...')
      ws.send('Hi, Message from Client to server...')
    }
    ws.onmessage = function (event) {
      console.log('Message Received from Server...', event)
    }
    ws.onerror = function (event) {
      console.log('Websocket Error Occurred...', event)
    }
    ws.onclose = function (event) {
      console.log('Websocket Connection Closed...', event)
    }

    // ws.addEventListener('open', (event) => {
    //   console.log('Websocket connection open...', event)
    //   ws.send('Hi, Message from Client...')
    // })
    // ws.addEventListener('message', (event) => {
    //   console.log('Message Received from Server...', event)
    // })
    // ws.addEventListener('error', (event) => {
    //   console.log('Websocket Error Occurred...', event)
    // })
    // ws.addEventListener('close', (event) => {
    //   console.log('Websocket Connection Closed...', event)
    // })

  </script>
</body>

</html>


readyState


gs7

Server Side:-

When Sending Data to Client

    Python to String

When Receiving Data from Client

    String to Python

Client Side:-

When Sending Data to Server

    JavaScript Object to String

When Receiving Data from Server

    String to JavaScript Object


Python JSON Lib

In python file used

import json

json.dumps() – This method is used to convert Python dictionary into json string.

json.loads() – This method is used to convert json string into Python dictionary.


JSON
in JavaScript file used
JSON.parse() – This method is used to convert json string into JavaScript object.
JSON.stringify() – This method is used to convert JavaScript object into json string.


gs8 & gs9 - ppt7

Channel Layers

Channel layers allow you to talk between different instances of an application. 

It is for high-level application-to-application communication.

We can communicate with out storing data in database.

Most Important this three things- Channels, Groups, Message

Channels - Channels are a first-in, first out queue with at-most-once delivery semantics. Each channel has a name.

Chanal ar nume jana thakla amra message send korta parbo.

Groups - Multiple channel a data send karar janna Groups used kara hoy.

Multiple chanal a data send kara ka bala hoy broadcast system.

Sending to individual channels isn’t particularly useful - in most cases you’ll want to send to multiple channels/consumers there we use groups.

Multiple channels can be grouped into a group. Each group has a name. A channel can be added or removed from a group by anyone who knows the group name. Using the group name you can also send a message to all channels in the group. 

Groups are a broadcast system that:

  • Allows you to add and remove channel names from named groups, and send message to those named groups.
  • Provides group expiry for clean-up of connections.

Messages – Messages must be a dict. Because these messages are sometimes sent over a network, they need to be serializable.

Redis Channel Layer - It is basically use developing purpose and production(So it is recomended to implement and important)

In-Memory Channel Layer - It is basically use developing purpose not used in production

Redis Channel Layer

Redis works as the communication store for the channel layer. 

In order to use Redis as a channel layer you have to install channels_redis package.

channels_redis is the only official Django-maintained channel layer supported for production use. 


Config Redis Channel Layer

Download and Install Memurai – Redis for Windows alternative

Install channels_redis pip install channels_redis

Open settings.py file then write

CHANNEL_LAYERS = {

    "default": {

        "BACKEND": "channels_redis.core.RedisChannelLayer",

        "CONFIG": {

            "hosts": [("127.0.0.1", 6379)],

        },

    },

}

get_channel_layer() –  This function is used to get default channel layer from a project.

from channels.layers import get_channel_layer

channel_layer – This attribute is used to get default channel layer from a project. This contains a pointer to the channel layer instance, only if you are using consumers.

channel_name – This attribute contains the channel name that will reach the consumer.

Method

send() – It  that takes two arguments: the channel to send on, as a unicode string, and the message to send, as a serializable dict.

Syntax:- send(‘channel_name’, message)

group_send() – It takes two positional arguments; the group to send to, as a unicode string, and the message to send, as a serializable dict. It may raise MessageTooLarge but cannot raise ChannelFull.

Syntax:- group_send(‘group_name’, message)

group_add() – This is used to add a channel to a new or existing group. If the channel is already in the group, the function should return normally.

Syntax:- group_add(‘group_name’, ‘channel_name’)

Example:- group_add(‘friends’, self.channel_name)

group_discard() – This is used to remove channel from the group if it is in it, and does nothing otherwise.

Syntax:- group_discard(‘group_name’, ‘channel_name’)

Example:- group_discard(‘friends’, self.channel_name)

Exception

MessageTooLarge, the exception raised when a send operation fails because the encoded message is over the layer’s size limit.

ChannelFull, the exception raised when a send operation fails because the destination channel is over capacity.

gs10 - ppt8

Database

The Django ORM is a synchronous piece of code, and so if you want to access it from asynchronous code you need to do special handling to make sure its connections are closed properly.

If you are writing asynchronous code, however, you will need to call database methods in a safe, synchronous context, using database_sync_to_async.

database_sync_to_async
Write your ORM queries in a separate function or method, and then call it with database_sync_to_async.
Example:- 
from channels.db import database_sync_to_async
async def websocket_connect(self):
    self.username = await database_sync_to_async(self.get_name)()

def get_name(self):
    return User.objects.all()[0].name

gs11- ppt9

Authentication

asgi.py

from channels.auth import AuthMiddlewareStack

application = ProtocolTypeRouter({

  'http': get_asgi_application(),

  'websocket': AuthMiddlewareStack(

    URLRouter(

      app.routing.websocket_urlpatterns

    ) )})

To access the user, just use self.scope["user"] in your consumer 

gs12 to gs16 - ppt10


Sunday, 16 July 2023

GitHub

 Branching Strategy




Django

Check python version

CODE 
python --version

Check PIP version

CODE 
pip --version

Check Django install or not

CODE 
django-admin --version

Install Django in Separate Environment

Install Virtual Environment Wrapper

CODE 
pip install virtualenv

Create Virtual Environment (VE)

CODE 
virtualenv env

Active Virtual Environment (VE)

CODE 
cd env/Scripts
activate

Install Django in Created VE

CODE 
pip install django

OR

*You can also specify version*

CODE 
pip install django==2.0

Create Django Project

CODE 
django-admin startproject projectname

Uninstall Django from Separate Environment

Active Virtual Environment (VE)

CODE 
workon envname

Uninstall Django from VE

CODE 
pip uninstall django

Remove Virtual Environment

CODE 
rmvirtualenv envname

Uninstall Virtual Environment Wrapper

CODE 
pip uninstall virtualenvwrapper-win

How to run server

CODE 
python manage.py runserver

Server Started Visit http://127.0.0.1:8000 or http://localhost:8000

You can specify Port number python manage.py runserver 5555 Visit http://127.0.0.1:5555 or http://localhost:5555

ctrl + c is used to stop Server

Note – Sometime when you make changes in your project you may need to restart the server. 

How to Start/Create Application

Django -admin startproject projectName

Creating One Application inside Project:-

Go to Project Folder

python manage.py startapp course


pip freeze

Install All requirement

pip install -r requirements.txt -v


create requirements.txt file using freeze 

pip freeze > requirements.txt

Views.py

from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def learn_django(request):
 return HttpResponse('Hello Django')

def learn_python(request):
 return HttpResponse('<h1>Hello Python</h1>')

def learn_var(request):
 a = '<h1>Hello variable</h1>'
 return HttpResponse(a)

def learn_math(request):
 a = 10 + 10
 return HttpResponse(a)

def learn_format(request):
 a = 'GeekyShows'
 return HttpResponse(f'Hello How are You {a}')

urls.py

from django.contrib import admin
from django.urls import path
from course import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('learndj/', views.learn_django),
    path('learnpy/', views.learn_python),
    path('learnv/', views.learn_var),
    path('learnm/', views.learn_math),
    path('learnf/', views.learn_format),
]

Url inside Application

views.py

from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def fees_django(request):
 return HttpResponse('300')

def fees_python(request):
 return HttpResponse('200')

fees/urls.py

from django.urls import path
from . import views
urlpatterns = [
    path('feesdj/', views.fees_django),
    path('feespy/', views.fees_python),
]

urls.py

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('fe/', include('fees.urls')),
]

We create templates folder inside Project Folder

settings.py

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates')

TEMPLATES = [
    {
        'DIRS': [TEMPLATE_DIR],
    },
]


views.py

from django.shortcuts import render
# Create your views here.
def fees_django(request):
 return render(request, 'feesone.html')

def fees_python(request):
 return render(request, 'feestwo.html')


Messages Framework

INSTALLED_APPS = [ 'django.contrib.messages' ]

MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.messages.middleware.MessageMiddleware' ]

‘context_processors’: ['django.contrib.messages.context_processors.messages’]

Message Tag:-


admin.py 
from django.contrib import admin
      from .models import User
      # Register your models here.
      @admin.register(User)
      class UserAdmin(admin.ModelAdmin):
       list_display = ('id', 'name', 'email', 'password')
models.py 
from django.db import models

      # Create your models here.
      class User(models.Model):
       name=models.CharField(max_length=70)
       password=models.CharField(max_length=70)
       email=models.EmailField(max_length=70)
from.py 
from django import forms
      from .models import User
      
      class StudentRegistration(forms.ModelForm):
       class Meta:
        model = User
        fields = ['name', 'email', 'password']
views.py 
from django.shortcuts import render
      from .forms import StudentRegistration
      from django.contrib import messages
      # Create your views here.
      def regi(request):
      	messages.add_message(request, messages.SUCCESS, 'Your Account has been created !!!')
        messages.info(request, 'Now You can Login')
        messages.warning(request, 'This is warning')
        messages.error(request, 'This is an error')
        fm = StudentRegistration()
        return render(request, 'enroll/userregistration.html', {'form':fm})
userregistration.html 
<!DOCTYPE html>
      <html lang="en">
      <head>
       <meta charset="UTF-8">
       <meta name="viewport" content="width=device-width, initial-scale=1.0">
       <title>Document</title>
       <style>
        .alert-info {
         color: blue;
        }
        .alert-success{
         color:green;
        }
        .alert-warning{
         color:orange;
        }
        .alert-danger{
         color:red;
        }
       </style>
      </head>
      <body>
       <form action="" method="post">
        {% csrf_token %}
        {{form.as_p}}
        <input type="submit" value="Submit">
       </form>
       {% if messages %}
        {% for message in messages %}
         <p {% if message.tags %} class="alert-{{message.tags}}" {% endif %}>{{message}}</p>
        {% endfor %}
       {% endif %}
      </body>
      </html>

Message Tag Change

settings.py 
MESSAGE_TAGS = {messages_s.ERROR:'danger'}

User Authtication(gs66,67)

forms.py 
from django.contrib.auth.models import User
      from django import forms
      from django.contrib.auth.forms import UserCreationForm, UserChangeForm
      
      class SignUpForm(UserCreationForm):
       password2 = forms.CharField(label='Confirm Password (again)', widget=forms.PasswordInput)
       class Meta:
        model = User
        fields = ['username', 'first_name', 'last_name', 'email']
        labels = {'email': 'Email'}
      
      class EditUserProfileForm(UserChangeForm):
       password = None
       class Meta:
        model = User
        fields = ['username', 'first_name', 'last_name', 'email', 'date_joined', 'last_login']
        labels = {'email': 'Email'}
      
      class EditAdminProfileForm(UserChangeForm):
       password = None
       class Meta:
        model = User
        fields = '__all__'
        labels = {'email': 'Email'}
      
urls.py 
from django.contrib import admin
      from django.urls import path
      from enroll import views
      urlpatterns = [
          path('admin/', admin.site.urls),
          path('signup/', views.sign_up, name='signup'),
          path('login/', views.user_login, name='login'),
          path('dashboard/', views.user_dashboard, name='dashboard'),
          path('logout/', views.user_logout, name='logout'),
      ]
      
views.py 
 from django.shortcuts import render, HttpResponseRedirect
from .forms import SignUpForm, EditUserProfileForm, EditAdminProfileForm
from django.contrib import messages
from django.contrib.auth.forms import AuthenticationForm, PasswordChangeForm, SetPasswordForm
from django.contrib.auth import authenticate, login, logout, update_session_auth_hash
from django.contrib.auth.models import User

# Signup View Function
def sign_up(request):
 if request.method == "POST":
  fm = SignUpForm(request.POST)
  if fm.is_valid():
   messages.success(request, 'Account Created Successfully !!') 
   fm.save()
 else: 
  fm = SignUpForm()
 return render(request, 'enroll/signup.html', {'form':fm})

# Login View Function
def user_login(request):
  if not request.user.is_authenticated:
    if request.method == "POST":
      fm = AuthenticationForm(request=request, data=request.POST)
      if fm.is_valid():
        uname = fm.cleaned_data['username']
        upass = fm.cleaned_data['password']
        user = authenticate(username=uname, password=upass)
        if user is not None:
          login(request, user)
          messages.success(request, 'Logged in successfully !!')
          return HttpResponseRedirect('/profile/')
    else: 
      fm = AuthenticationForm()
    return render(request, 'enroll/userlogin.html', {'form':fm})
  else:
    return HttpResponseRedirect('/profile/')

# Profile
def user_profile(request):
  if request.user.is_authenticated:
    if request.method == "POST":
      if request.user.is_superuser == True:
        fm = EditAdminProfileForm(request.POST, instance=request.user)
        users = User.objects.all()
      else:
        fm = EditUserProfileForm(request.POST, instance=request.user)
        users = None
      if fm.is_valid():
        messages.success(request, 'Profile Updated !!!')
        fm.save()
    else:
      if request.user.is_superuser == True:
        fm = EditAdminProfileForm(instance=request.user)
        users = User.objects.all()
      else:
        fm = EditUserProfileForm(instance=request.user)
        users = None
    return render(request, 'enroll/profile.html', {'name': request.user.username, 'form':fm, 'users':users})
  else:
    return HttpResponseRedirect('/login/')

# Logout
def user_logout(request):
  logout(request)
  return HttpResponseRedirect('/login/')

# Change Password with old Password
def user_change_pass(request):
  if request.user.is_authenticated:
    if request.method == "POST":
      fm = PasswordChangeForm(user=request.user, data=request.POST)
      if fm.is_valid():
        fm.save()
        update_session_auth_hash(request, fm.user)
        messages.success(request, 'Password Changed Successfully')
        return HttpResponseRedirect('/profile/')
    else:
      fm = PasswordChangeForm(user=request.user)
    return render(request, 'enroll/changepass.html', {'form':fm})
  else:
    return HttpResponseRedirect('/login/')

def user_detail(request, id):
  if request.user.is_authenticated:
    pi = User.objects.get(pk=id)
    fm = EditAdminProfileForm(instance=pi)
    return render(request, 'enroll/userdetail.html', {'form':fm})
  else:
    return HttpResponseRedirect('/login/')
      
      
signup.html 
<!DOCTYPE html>
      <html lang="en">
      <head>
       <meta charset="UTF-8">
       <meta name="viewport" content="width=device-width, initial-scale=1.0">
       <title>User Registration</title>
       <style>
        .success{
         color:red;
        }
       </style>
      </head>
      <body>
      <form action="" method="post" novalidate>
       {% csrf_token %}
        {% if form.non_field_errors %}
         {% for error in form.non_field_errors %}
          <p class="er">{{error}}</p>
         {% endfor %}
        {% endif %}
       {% for fm in form %}
        {{fm.label_tag}} {{fm}} {{fm.errors|striptags}} <br><br>
       {% endfor %}
       <input type="submit" value="Submit">
      </form>
      {% if messages %}
       {% for message in messages %}
        <small {% if message.tags %} class="{{message.tags}}" {% endif %}> {{message}} </small>
       {% endfor %}
       {% endif %}
       <a href="{% url 'login' %}">Login</a>
      </body>
      </html>
      
      
userlogin.html 
<!DOCTYPE html>
      <html lang="en">
      <head>
       <meta charset="UTF-8">
       <meta name="viewport" content="width=device-width, initial-scale=1.0">
       <title>User Login</title>
       <style>
       .er{
        color:red;
       }
       </style>
      </head>
      <body>
       <form action="" method="post" novalidate>
        {% csrf_token %}
        {% if form.non_field_errors %}
         {% for error in form.non_field_errors %}
          <p class="er">{{error}}</p>
         {% endfor %}
        {% endif %}
        {% for fm in form %}
         {{fm.label_tag}} {{fm}} {{fm.errors|striptags}} <br><br>
        {% endfor %}
        <input type="submit" value="Login">
       </form>
        <a href="{% url 'signup' %}">Signup</a>
      </body>
      </html>
      
      
dashboard.html 
<!DOCTYPE html>
      <html lang="en">
      <head>
       <meta charset="UTF-8">
       <meta name="viewport" content="width=device-width, initial-scale=1.0">
       <title>Dashboard</title>
      </head>
      <body>
       <h1>Dashboard Page</h1>
        <h2>Welcome {{name}}</h2>
      
      {% if perms.enroll.delete_blog %}
        <input type="button" value="Delete"> <br><br>
      {% else %}
        <h3>No Delete Permission</h3>
      {% endif %}
      
      {% if perms.enroll.add_blog %}
        <input type="button" value="Add"> <br><br>
      {% else %}
        <h3>No Add Permission</h3>
      {% endif %}
      
      
       <a href="{% url 'logout' %}">Logout</a>
      </body>
      </html>
      

cookie(gs68)

less data store into the client machan, if we are not set expires, after close browser cookie will expire.
In cookie we can store data, but in session we can store session id in cookie
views.py 
from django.shortcuts import render
      from datetime import datetime, timedelta
      # Create your views here.

      def setcookie(request):
       reponse = render(request, 'student/setcookie.html')
       reponse.set_cookie('lname', 'Jha', expires=datetime.utcnow()+timedelta(days=2))
       return reponse
      
      def getcookie(request):
      #  name = request.COOKIES['lname']
       # name = request.COOKIES.get('name')
       name = request.COOKIES.get('name', "Guest")
       return render(request, 'student/getcookie.html', {'name':name})
      
      def delcookie(request):
       reponse = render(request, 'student/delcookie.html')
       reponse.delete_cookie('name')
       return reponse
      
      
set_signed_cookie and  get_signed_cookie:(gs69)
set_signed_cookie and  get_signed_cookie "salt='nm'" sould be same ---> this is one of the squre feature
views.py 
from django.shortcuts import render
      from datetime import datetime, timedelta
      # Create your views here.
      def setcookie(request):
       reponse = render(request, 'student/setcookie.html')
       reponse.set_signed_cookie('name', 'Sonam', salt='nm', expires=datetime.utcnow()+timedelta(days=2))
       return reponse
      
      def getcookie(request):
       name = request.get_signed_cookie('name', default="Guest", salt='nm')
       return render(request, 'student/getcookie.html', {'name':name})
      
      def delcookie(request):
       reponse = render(request, 'student/delcookie.html')
       reponse.delete_cookie('name')
       return reponse
      
      

Session(gs71, 72, 74)

# In Session data store into the server(Database) not in client machan, here cookies contain session id

# By default session expire in 2 week

# Session data store into the server so, we have run migrate for create table

# In cookie we can store simple text data, but in session we can store session id in cookie

Session Type:

1. database-backed sessions(By default)

2. file-based sessions(gs76)

3. cookie-based sessions 

4. cached sessions 

views.py 
      from django.shortcuts import render
      
      # Create your views here.
      def setsession(request):
       request.session.set_expiry(10)
       request.session['name'] = 'Sonam'
       request.session['lname'] = 'Jha'
       request.session['dicts'] = {'name':'Sonam', 'roll':101}
       return render(request, 'student/setsession.html')
      
      def getsession(request):
       name = request.session.get('name', default="puspendu")
       keys = request.session.keys()
       items = request.session.items()
       # age = request.session.setdefault('age', '26')
       dicts = request.session['dicts']

       
       print(request.session.get_session_cookie_age())
       print(request.session.get_expiry_age())
       print(request.session.get_expiry_date())
       print(request.session.get_expire_at_browser_close())
       return render(request, 'student/getsession.html', {'name':name, 'keys':keys, 'items':items})
      
       def delsession(request):
       request.session.flush()
       request.session.clear_expired()
       return render(request, 'student/delsession.html')
      
      

Set session expire age:

settinges.py 
      # SESSION_COOKIE_AGE 400 Sec a used hoy
      SESSION_COOKIE_AGE = 400
      # We can define session name, by default sessionId thaka
      SESSION_COOKIE_NAME = 'sessionname'
      # we can set path, By default only / thaka
      SESSION_COOKIE_PATH = '/home'
      

Caching:

prathama data search korba cach ta, jodi data na pai tahola database thaka search kora niba.

A Cache is an information technology for the temporary storage (caching) of Web documents, such as Web pages, images, and other types of Web multimedia, to reduce server lag.

Caching is one of those methods which a website implements to become faster. It is cost efficient and saves CPU processing time.

Following are the options of caching:-

  1. Database Caching
  2. File System Caching
  3. Local Memory Caching

We can do Caching our application:

  1. The per-site cache - Once the cache is set up, the simplest way to use caching is to cache your entire site. gs78
  2. The per-view cache - A more granular way to use the caching framework is by caching the output of individual views. gs81
  3. Template fragment caching – This gives you more control what to cache. gs84

settinges.py 
MIDDLEWARE = [
      'django.middleware.cache.UpdateCacheMiddleware',
      'django.middleware.common.CommonMiddleware',
      'django.middleware.cache.FetchFromCacheMiddleware’,
  ]

      

The per-site cache(Database Caching)(gs78)

Before using the database cache, you must create the cache table with this command: python manage.py createcachetable (same to same run korta hoba) 

settinges.py 
      CACHE_MIDDLEWARE_SECONDS = 30
      CACHES = {
          'default': {
              'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
              'LOCATION': 'enroll_cache',
          }
      }

      
course.html 
      <!DOCTYPE html>
      <html lang="en">
      <head>
       <meta charset="UTF-8">
       <meta name="viewport" content="width=device-width, initial-scale=1.0">
       <title>Document</title>
      </head>
      <body>
       <h1>Course 1</h1>
       <h1>Course 2</h1>
       <h1>Course 3</h1>
       <h1>Course 4</h1>
      </body>
      </html>
      

      

The per-view cache(File System Caching)(gs81, gs83)

settinges.py 
      CACHES = {
        'default': {
            'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
            'LOCATION': 'C:\DjangoCode\gs83\cache',
        }
    }

      
views.py 
      from django.shortcuts import render
      from django.views.decorators.cache import cache_page
      
      # Create your views here.
      @cache_page(60)
      def home(request):
       return render(request, 'enroll/course.html')
      
      def contact(request):
       return render(request, 'enroll/contact.html')

      
urls.py 
      from django.contrib import admin
      from django.urls import path
      from enroll import views
      from django.views.decorators.cache import cache_page
      urlpatterns = [
          path('admin/', admin.site.urls),
          path('', cache_page(30)(views.home)),
          path('home/', views.home),
          path('contact/', views.contact),
      ]

      
course.html 
      <!DOCTYPE html>
      <html lang="en">
      <head>
       <meta charset="UTF-8">
       <meta name="viewport" content="width=device-width, initial-scale=1.0">
       <title>Document</title>
      </head>
      <body>
       <h1>Course 1</h1>
       <h1>Course 2</h1>
      
      </body>
      </html>

      
contact.html 
      <!DOCTYPE html>
      <html lang="en">
      <head>
       <meta charset="UTF-8">
       <meta name="viewport" content="width=device-width, initial-scale=1.0">
       <title>Document</title>
      </head>
      <body>
       <h1>Contact 1</h1>
       <h1>Contact 2</h1>
       <h1>Contact 3</h1>
       <h1>Contact 4</h1>
      </body>
      </html>

      

Template fragment caching(Local Memory Caching)(gs84)

settings.py 
      CACHES = {
        'default': {
            'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
            'LOCATION': 'unique-snowflake',
        }
    }

      
views.py 
      from django.shortcuts import render

      # Create your views here.
      def home(request):
       return render(request, 'enroll/course.html')

      
urls.py 
      from django.contrib import admin
      from django.urls import path
      from enroll import views
      urlpatterns = [
          path('admin/', admin.site.urls),
          path('', views.home),
      ]

      
course.html 
      <!DOCTYPE html>
{% load cache %}
<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>Document</title>
</head>
<body>
 <h1>Course 1</h1>
 <h1>Course 2</h1>
{% cache 30 course %}
 <h1>Course 3</h1>
 <h1>Course 4</h1>
{% endcache course %}
</body>
</html>
      

Signals(gs89)

signals.py 
      from django.contrib.auth.signals import user_logged_in, user_logged_out, user_login_failed
from django.contrib.auth.models import User
from django.dispatch import receiver
from django.db.models.signals import pre_init, pre_save, pre_delete, post_init, post_save, post_delete, pre_migrate, post_migrate
from django.core.signals import request_started, request_finished, got_request_exception
from django.db.backends.signals import connection_created

@receiver(user_logged_in, sender=User)
def login_success(sender, request, user, **kwargs):
 print("----------------------------")
 print("Logged-in Signal... Run Intro..")
 print("Sender:", sender)
 print("Request:", request)
 print("User:", user)
 print("User Password:", user.password)
 print(f'Kwargs: {kwargs}')
# user_logged_in.connect(login_success, sender=User)

@receiver(user_logged_out, sender=User)
def log_out(sender, request, user, **kwargs):
 print("----------------------------")
 print("Logged-out Signal... Run Outro..")
 print("Sender:", sender)
 print("Request:", request)
 print("User:", user)
 print(f'Kwargs: {kwargs}')
# user_logged_out.connect(log_out, sender=User)

@receiver(user_login_failed)
def login_failed(sender, credentials, request, **kwargs):
 print("----------------------------")
 print("Login Failed Signal...")
 print("Sender:", sender)
 print("Credentials:", credentials)
 print("Request:", request)
 print(f'Kwargs: {kwargs}')
# user_login_failed.connect(login_failed)

@receiver(pre_save, sender=User)
def at_beginning_save(sender, instance, **kwargs):
 print("----------------------------")
 print("Pre Save Signal...")
 print("Sender:", sender)
 print("Instance:", instance)
 print(f'Kwargs: {kwargs}')
# pre_save.connect(at_beginning_save, sender=User)

@receiver(post_save, sender=User)
def at_ending_save(sender, instance, created, **kwargs):
 if created:
  print("----------------------------")
  print("Post Save Signal...")
  print("New Record")
  print("Sender:", sender)
  print("Instance:", instance)
  print("Created:", created)
  print(f'Kwargs: {kwargs}')
 else:
  print("----------------------------")
  print("Post Save Signal...")
  print("Update")
  print("Sender:", sender)
  print("Instance:", instance)
  print("Created:", created)
  print(f'Kwargs: {kwargs}')
# post_save.connect(at_ending_save, sender=User)

@receiver(pre_delete, sender=User)
def at_beginning_delete(sender, instance, **kwargs):
 print("-----------------------------------------")
 print("Pre Delete Signal......")
 print('Sender:', sender)
 print('Instance:', instance)
 print(f'Kwargs: {kwargs}')
# pre_delete.connect(at_beginning_delete, sender=User)

@receiver(post_delete, sender=User)
def at_ending_delete(sender, instance, **kwargs):
 print("-----------------------------------------")
 print("Post Delete Signal......")
 print('Sender:', sender)
 print('Instance:', instance)
 print(f'Kwargs: {kwargs}')
# post_delete.connect(at_ending_delete, sender=User)

@receiver(pre_init, sender=User)
def at_beginning_init(sender, *args, **kwargs):
 print("-----------------------------------------")
 print("Pre Init Signal......")
 print('Sender:', sender)
 print(f'Args: {args}')
 print(f'Kwargs: {kwargs}')
# pre_init.connect(at_beginning_init, sender=User)

@receiver(post_init, sender=User)
def at_ending_init(sender, *args, **kwargs):
 print("-----------------------------------------")
 print("Post Init Signal......")
 print('Sender:', sender)
 print(f'Args: {args}')
 print(f'Kwargs: {kwargs}')
# post_init.connect(at_ending_init, sender=User)

@receiver(request_started)
def at_beginning_request(sender, environ, **kwargs):
 print("-----------------------------------------")
 print("At Beginning Request......")
 print('Sender:', sender)
 print('Environ:', environ)
 print(f'Kwargs: {kwargs}')
# request_started.connect(at_beginning_request)

@receiver(request_finished)
def at_ending_request(sender, **kwargs):
 print("-----------------------------------------")
 print("At Ending Request......")
 print('Sender:', sender)
 print(f'Kwargs: {kwargs}')
# request_finished.connect(at_ending_request)

@receiver(got_request_exception)
def at_req_exception(sender, request, **kwargs):
 print("-----------------------------------------")
 print("At Request Exception......")
 print('Sender:', sender)
 print('Request:', request)
 print(f'Kwargs: {kwargs}')
# got_request_exception.connect(at_req_exception)

@receiver(pre_migrate)
def before_install_app(sender, app_config, verbosity, interactive, using, plan, apps, **kwargs):
 print("-----------------------------------------")
 print("before_install_app......")
 print('Sender:', sender)
 print('App_config:', app_config)
 print('Verbosity:', verbosity)
 print('Interactive:', interactive)
 print('Using:', using)
 print('Plan:', plan)
 print('App:', apps)
 print(f'Kwargs: {kwargs}')
# pre_migrate.connect(before_install_app)

@receiver(post_migrate)
def at_end_migrate_flush(sender, app_config, verbosity, interactive, using, plan, apps, **kwargs):
 print("-----------------------------------------")
 print("at_end_migrate_flush......")
 print('Sender:', sender)
 print('App_config:', app_config)
 print('Verbosity:', verbosity)
 print('Interactive:', interactive)
 print('Using:', using)
 print('Plan:', plan)
 print('App:', apps)
 print(f'Kwargs: {kwargs}')
# post_migrate.connect(at_end_migrate_flush)

@receiver(connection_created)
def conn_db(sender, connection, **kwargs):
 print("-----------------------------------------")
 print("Initial connection to the database......")
 print('Sender:', sender)
 print('Connection:', connection)
 print(f'Kwargs: {kwargs}')
# connection_created.connect(conn_db)
      
apps.py 
      from django.apps import AppConfig


      class BlogConfig(AppConfig):
          name = 'blog'

          def ready(self):
              import blog.signals


      
__init__.py 
      default_app_config = 'blog.apps.BlogConfig'
    

Custom Signals(gs90)

views.py 
      from django.shortcuts import render, HttpResponse
      from blog import signals
      # Create your views here.
      def home(request):
      signals.notification.send(sender=None, request=request, user=['Geeky', 'Shows'])
      print("*******************")
      return HttpResponse("This is Home Page")
    
Signals.py 
      from django.dispatch import Signal, receiver
      # Creating Signals
      notification = Signal(providing_args=["request", "user"])

      # Receiver Function
      @receiver(notification)
      def show_notification(sender, **kwargs):
      print(sender)
      print(f'{kwargs}')
      print("Notification")
    

Middleware

Function based Middleware (gs91)

middlewares.py 
      def my_middleware(get_response):
      print("One Time Initialization")
      def my_function(request):
        print("This is before view")
        response = get_response(request)
        print("This is after view")
        return response
      return my_function
    
settings.py 
      MIDDLEWARE = [
    ...
    'blog.middlewares.my_middleware',
]
    
views.py 
      from django.shortcuts import render, HttpResponse

      # Create your views here.
      def home(request):
       print("I am View")
       return HttpResponse("This is Home Page")
    

Middleware

  1. Built in Middleware  
  2. Custom Middleware

  • Function based Middleware
  • Class based Middleware

                                                Real life Ex1

Real life Ex2


                                                Real life Ex3
Technical Ex1


Technical Ex2

Technical Ex3



Class based Middleware(gs92)

Example-1

Used single middlewares

middlewares.py(gs92) 
      class MyMiddleware:
      def __init__(self, get_response):
       self.get_response = get_response
       print("One Time Initialization")
     
      def __call__(self, request):
       print("This is before view")
       response = self.get_response(request)
       print("This is after view")
       return response
    

Example-2

Used multiple middlewares

middlewares.py(gs93) 
      from django.shortcuts import HttpResponse
      class BrtoherMiddleware:
       def __init__(self, get_response):
        self.get_response = get_response
        print("One Time Brtoher Initialization")
      
       def __call__(self, request):
        print("This is Brother before view")
        response = self.get_response(request)
        print("This is Brother after view")
        return response
      
      class FatherMiddleware:
       def __init__(self, get_response):
        self.get_response = get_response
        print("One Time Father Initialization")
      
       def __call__(self, request):
        print("This is Father before view")
        # response = self.get_response(request)
        response = HttpResponse("Nikal lo")
        # print("This is Father after view")
        return response
      
      class MummyMiddleware:
       def __init__(self, get_response):
        self.get_response = get_response
        print("One Time Mummy Initialization")
      
       def __call__(self, request):
        print("This is Mummy before view")
        response = self.get_response(request)
        print("This is Mummy after view")
        return response
    

Output 1 (With out return HttpResponse)

One Time Mummy Initialization

One Time Father Initialization 

 One Time Brtoher Initialization


This is Brother before view

This is Father before view

This is Mummy before view

I am View

This is Mummy after view 

This is Father after view

This is Brother after view 


Output 2 (return HttpResponse in FatherMiddleware)

One Time Mummy Initialization

One Time Father Initialization

One Time Brtoher Initialization 


This is Brother before view

This is Father before view

This is Brother after view

settings.py(gs93) 
      MIDDLEWARE = [
      .....
      'blog.middlewares.BrtoherMiddleware',
      'blog.middlewares.FatherMiddleware',
      'blog.middlewares.MummyMiddleware',
  ]
  
    

Check once middleware gs94

QuerySet API

models.py 
      from django.db import models

      # Create your models here.
      class Student(models.Model):
       name = models.CharField(max_length=70)
       roll = models.IntegerField(unique=True, null=False)
       city = models.CharField(max_length=70)
       marks = models.IntegerField()
       pass_date = models.DateField()
      
      class Teacher(models.Model):
       name = models.CharField(max_length=70)
       empnum = models.IntegerField(unique=True, null=False)
       city = models.CharField(max_length=70)
       salary = models.IntegerField()
       join_date = models.DateField()
    
views.py(gs96) 
      from django.shortcuts import render
      from .models import Student, Teacher
      from django.db.models import Q
      # Create your views here.
      
      def home(request):
       
       student_data = Student.objects.all()
      
       student_data = Student.objects.filter(marks=70)
      
       student_data = Student.objects.exclude(marks=70)
      
       student_data = Student.objects.order_by('marks')
       student_data = Student.objects.order_by('-marks')
       student_data = Student.objects.order_by('?') # random
       student_data = Student.objects.order_by('name')
      
       student_data = Student.objects.order_by('id').reverse()
       student_data = Student.objects.order_by('id').reverse()[0:5]
      
       
       student_data = Student.objects.values()
       student_data = Student.objects.values('name', 'city')
      
       student_data = Student.objects.values_list()
       student_data = Student.objects.values_list('id', 'name')
       student_data = Student.objects.values_list('id', 'name', named=True)
       
       student_data = Student.objects.using('default')
      
       student_data = Student.objects.dates('pass_date', 'month')
      
      ############## Second Tables 'Teacher' Started ################
      
       qs1 = Student.objects.values_list('id', 'name', named=True)
       qs2 = Teacher.objects.values_list('id', 'name', named=True)
       student_data = qs2.union(qs1)
      
       qs1 = Student.objects.values_list('id', 'name', named=True)
       qs2 = Teacher.objects.values_list('id', 'name', named=True)
       student_data = qs2.union(qs1, all=True)
      
       qs1 = Student.objects.values_list('id', 'name', named=True)
       qs2 = Teacher.objects.values_list('id', 'name', named=True)
       student_data = qs1.intersection(qs2)
      
       qs1 = Student.objects.values_list('id', 'name', named=True)
       qs2 = Teacher.objects.values_list('id', 'name', named=True)
       student_data = qs2.difference(qs1)
      
       ############ AND OR operator ###############
       
       student_data = Student.objects.filter(id=6) & Student.objects.filter(roll=106)
       student_data = Student.objects.filter(id=6, roll=106)
       student_data = Student.objects.filter(Q(id=6) & Q(roll=106))
      
       student_data = Student.objects.filter(id=6) | Student.objects.filter(roll=107)
       student_data = Student.objects.filter(Q(id=6) | Q(roll=108))
      
       print("Return:", student_data)
       print()
       print("SQL Query:", student_data.query)
       return render(request, 'school/home.html', {'students':student_data})
    
home.html 
      <!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>Student Information</title>
  <style>
  table, th, tr, td {
   border: 1px solid black
  }
 </style>
</head>
<body>
<table>
<h3>Student Information</h3>
 <th>ID</th>
 <th>Name</th>
 <th>Roll</th>
 <th>City</th>
 <th>Marks</th>
 <th>Passing Year</th>
 {% for student in students %}
  <tr>
   <td>{{student.id}}</td>
   <td>{{student.name}}</td>
   <td>{{student.roll}}</td>
   <td>{{student.city}}</td>
   <td>{{student.marks}}</td>
   <td>{{student.pass_date}}</td>
  </tr>
 {% endfor %}
</table>
</body>
</html>
    
views.py(gs97) 
      from django.shortcuts import render
      from .models import Student
      # Create your views here.
      
      def home(request):
       student_data = Student.objects.get(pk=1)
       
       student_data = Student.objects.first()
       student_data = Student.objects.order_by('name').first()
      
       student_data = Student.objects.last()
      
       student_data = Student.objects.latest('pass_date')
      
       student_data = Student.objects.earliest('pass_date')
      
       student_data = Student.objects.all()
       print(student_data.exists())
       one_data = Student.objects.get(pk=1)
       print(student_data.filter(pk=one_data.pk).exists())
      
       student_data = Student.objects.create(name='Sameer', roll=114, city='Bokaro', marks=60, pass_date='2020-5-4')
      
       student_data, created = Student.objects.get_or_create(name='Anisa', roll=115, city='Bokaro', marks=60, pass_date='2020-5-4')
       print(created)
      
       student_data = Student.objects.filter(id=12).update(name='Kabir', marks=80)
       student_data = Student.objects.filter(marks=70).update(city='Pass')
      
       student_data, created = Student.objects.update_or_create(id=14, name='Sameer', defaults={'name':'Kohli'})
       print(created)
      
       objs = [
        Student(name='Atif', roll=116, city='Dhanbad', marks=70, pass_date='2020-5-4'),
        Student(name='Sahil', roll=117, city='Bokaro', marks=50, pass_date='2020-5-6'),
        Student(name='Kumar', roll=118, city='Dhanbad', marks=30, pass_date='2020-5-9'),
       ]
       student_data = Student.objects.bulk_create(objs)
      
      
       all_student_data = Student.objects.all()
       for stu in all_student_data:
        stu.city = 'Dhanbad'
       student_data = Student.objects.bulk_update(all_student_data, ['city'])
      
       student_data = Student.objects.in_bulk([1, 2])
       print(student_data[2].name)
       student_data = Student.objects.in_bulk([])
       student_data = Student.objects.in_bulk()
      
       student_data = Student.objects.get(pk=18).delete()
       student_data = Student.objects.filter(marks=50).delete()
       student_data = Student.objects.all().delete()
      
       student_data = Student.objects.all()
       print(student_data.count())
      
      
      
       print("Return:", student_data)
       return render(request, 'school/home.html', {'student':student_data})
    
views.py(gs98) 
      from django.shortcuts import render
      from .models import Student
      from datetime import date, time
      # Create your views here.
      
      def home(request):
       student_data = Student.objects.all()
       student_data = Student.objects.filter(name__exact='Sonam')
       student_data = Student.objects.filter(name__iexact='sonam')
       student_data = Student.objects.filter(name__contains='u')
       student_data = Student.objects.filter(name__icontains='U')
       student_data = Student.objects.filter(id__in = [1, 5, 7])
       student_data = Student.objects.filter(marks__in = [60, 70])
       student_data = Student.objects.filter(marks__gt = 60)
       student_data = Student.objects.filter(marks__gte = 60)
       student_data = Student.objects.filter(marks__lt = 60)
       student_data = Student.objects.filter(marks__lte = 60)
       student_data = Student.objects.filter(name__startswith='S')
       student_data = Student.objects.filter(name__istartswith='s')
       student_data = Student.objects.filter(name__endswith='L')
       student_data = Student.objects.filter(name__iendswith='L')
       student_data = Student.objects.filter(passdate__range=('2020-04-01', '2020-05-03'))
       student_data = Student.objects.filter(admdatetime__date=date(2020, 1, 2))
       student_data = Student.objects.filter(admdatetime__date__gt=date(2020, 1, 4))
       student_data = Student.objects.filter(passdate__year=2019)
       student_data = Student.objects.filter(passdate__year__gte=2019)
       student_data = Student.objects.filter(passdate__month=4)
       student_data = Student.objects.filter(passdate__month__gte=4)
       student_data = Student.objects.filter(passdate__day=2)
       student_data = Student.objects.filter(passdate__day__gt=2)
       student_data = Student.objects.filter(passdate__week=14)
       student_data = Student.objects.filter(passdate__week__gt=14)
       student_data = Student.objects.filter(passdate__week_day=5)
       student_data = Student.objects.filter(passdate__week_day__gt=5)
       student_data = Student.objects.filter(passdate__quarter=2)
       student_data = Student.objects.filter(admdatetime__time__gt=time(21,17))
       student_data = Student.objects.filter(admdatetime__hour__gt=5)
       student_data = Student.objects.filter(admdatetime__minute__gt=20)
       student_data = Student.objects.filter(admdatetime__second__gt=20)
       student_data = Student.objects.filter(roll__isnull=False)
      
      
      
      
       print("Return:", student_data)
       print()
       print("SQL Query:", student_data.query)
       return render(request, 'school/home.html', {'students':student_data})
      
    
views.py(gs99) 
      from django.shortcuts import render
      from .models import Student
      from django.db.models import Avg, Sum, Min, Max, Count
      # Create your views here.
      
      def home(request):
       student_data = Student.objects.all()
       average = student_data.aggregate(Avg('marks'))
       total = student_data.aggregate(Sum('marks'))
       minimum = student_data.aggregate(Min('marks'))
       maximum = student_data.aggregate(Max('marks'))
       totalcount = student_data.aggregate(Count('marks'))
      
       context = {'students':student_data, 'average':average, 'total':total, 'minimum':minimum, 'maximum':maximum, 'totalcount':totalcount}
      
       print(average)
       print("Return:", student_data)
       print()
       print("SQL Query:", student_data.query)
       return render(request, 'school/home.html', context)
      
    
views.py(gs100) 
      from django.shortcuts import render
      from .models import Student
      from django.db.models import Q
      # Create your views here.
      
      def home(request):
       student_data = Student.objects.filter(Q(id=6) & Q(roll=106))
       student_data = Student.objects.filter(Q(id=6) | Q(roll=107))
       student_data = Student.objects.filter(~Q(id=6))
      
       print("Return:", student_data)
       print()
       print("SQL Query:", student_data.query)
       return render(request, 'school/home.html', {'students':student_data })
      
      
    
views.py(gs101) 
      from django.shortcuts import render
      from .models import Student
      # Create your views here.
      
      def home(request):
       
       student_data = Student.objects.all()[:5]
       student_data = Student.objects.all()[5:10]
       student_data = Student.objects.all()[:11:2]
       
      
       print("Return:", student_data)
       print()
       print("SQL Query:", student_data.query)
       return render(request, 'school/home.html', {'students':student_data })
      
      
      
    

Model Inheritance

Three type model inheritance

  1. Abstract Base Classes
  2. Multi-table Inheritance
  3. Proxy Models
Abstract Base Classes(gs102)

Abstract base classes are useful when you want to put some common information into a number of other models. 
You write your base class and put abstract=True in the Meta class. 
This model will then not be used to create any database table. when it is used as a base class for other models, its fields will be added to those of the child class. 
It does not generate a database table or have a manager, and cannot be instantiated or saved directly.
Fields inherited from abstract base classes can be overridden with another field or value, or be removed with None.
models.py 
      from django.db import models

      # Create your models here.
      class CommonInfo(models.Model):
       name = models.CharField(max_length=70)
       age = models.IntegerField()
       date = models.DateField()
       class Meta:
        abstract = True
      
      class Student(CommonInfo):
       fees = models.IntegerField()
       date = None
      
      class Teacher(CommonInfo):
       salary = models.IntegerField()
      
      class Contractor(CommonInfo):
       date = models.DateTimeField()
       payment = models.IntegerField()
      
    
views.py 
      from django.shortcuts import render
      from .models import Student, Teacher, Contractor
      # Create your views here.
      def home(request):
       student_data = Student.objects.all()
       teacher_data = Teacher.objects.all()
       contractor_data = Contractor.objects.all()
       return render(request, 'school/home.html', {'students':student_data, 'teachers':teacher_data, 'contractors':contractor_data})
      
      
    

Multi-table Inheritance(gs103)

In this inheritance each model have their own database table, which means base class and child class will have their own table.

The inheritance relationship introduces links between the child model and each of its parents (via an automatically-created OneToOneField). 

models.py 
      from django.db import models

      # Create your models here.
      class ExamCenter(models.Model):
       cname = models.CharField(max_length=70)
       city = models.CharField(max_length=70)
      
      class Student(ExamCenter):
       name = models.CharField(max_length=70)
       roll = models.IntegerField()
      
    
views.py 
      from django.shortcuts import render
      from .models import ExamCenter, Student
      # Create your views here.
      def home(request):
      exam_center = ExamCenter.objects.all()
      student_data = Student.objects.all()
      return render(request, 'school/home.html', {'centers':exam_center, 'students':student_data})

      
      
    

All of the fields of ExamCenter will also be available in Student, although the data will reside in a different database table.

Proxy Models(gs104)

Sometimes, however, you only want to change the Python behavior of a model.

Two database table created.

If we insert data one table reflect another table, other table data visible behavior wise.

models.py 
      from django.db import models

      # Create your models here.
      class ExamCenter(models.Model):
       cname = models.CharField(max_length=70)
       city = models.CharField(max_length=70)
      
      class MyExamCenter(ExamCenter):
       class Meta:
        proxy = True
        ordering = ['city']
      
    
views.py 
      from django.shortcuts import render
      from .models import ExamCenter, MyExamCenter
      # Create your views here.
      
      def home(request):
       exam_center = ExamCenter.objects.all()
       my_exam_center = MyExamCenter.objects.all()
       return render(request, 'school/home.html', {'centers':exam_center, 'mycenters':my_exam_center})

      
      
    

Model Manager

Example-1(gs105)

models.py 
      from django.db import models

      # Create your models here.
      class Student(models.Model):
       name = models.CharField(max_length=70)
       roll = models.IntegerField()
      
       students = models.Manager()
      
    
views.py 
      from django.shortcuts import render
      from .models import Student
      # Create your views here.
      def home(request):
       student_data = Student.students.all()
       return render(request, 'school/home.html', {'students':student_data })
    

Example-2(gs106)

models.py 
      from django.db import models
      from .managers import CustomManager
      # Create your models here.
      class Student(models.Model):
       name = models.CharField(max_length=70)
       roll = models.IntegerField()
       
       objects = models.Manager()
       students = CustomManager()
      
      
    
views.py 
      from django.shortcuts import render
      from .models import Student
      # Create your views here.
      def home(request):
       student_data = Student.students.all()
       # student_data = Student.objects.all()
       return render(request, 'school/home.html', {'students':student_data })
    

Custom Model Manager(gs107)

Example-1

views.py 
      from django.shortcuts import render
      from .models import Student
      # Create your views here.
      def home(request):
       # student_data = Student.objects.all()
       student_data = Student.students.get_stu_roll_range(103, 109)
       return render(request, 'school/home.html', {'students':student_data })
    
managers.py 
      from django.db import models

      class CustomManager(models.Manager):
       def get_stu_roll_range(self, r1, r2):
        return super().get_queryset().filter(roll__range=(r1, r2))

    
models.py 
      from django.db import models
      from .managers import CustomManager
      # Create your models here.
      class Student(models.Model):
       name = models.CharField(max_length=70)
       roll = models.IntegerField()
       
       objects = models.Manager()
       students = CustomManager()

    

Example-2

views.py 
      from django.shortcuts import render
      from .models import Student, ProxyStudent
      # Create your views here.
      def home(request):
       student_data = Student.objects.all()
       # student_data = ProxyStudent.students.all()
       # student_data = ProxyStudent.students.get_stu_roll_range(103, 109)
       return render(request, 'school/home.html', {'students':student_data })
    
managers.py 
      from django.db import models

      class CustomManager(models.Manager):
       def get_stu_roll_range(self, r1, r2):
        return super().get_queryset().filter(roll__range=(r1, r2)).order_by('id')

    
models.py 
      from django.db import models
      from .managers import CustomManager
      # Create your models here.
      class Student(models.Model):
       name = models.CharField(max_length=70)
       roll = models.IntegerField()
      
      class ProxyStudent(Student):
       students = CustomManager()
       class Meta:
        proxy = True
        ordering = ['name']
    

Model Relationship

  1. One to One Relationship
  2. Many to One Relationship
  3. Many to Many Relationships
1. One to One Relationship

on_delete=models.CASCADE-----> Jadi user create page, akhana jodi user delete kora hoy tahola page delete hoya jaba
on_delete=models.PROTECT-----> Jadi user create page, akhana jodi user delete kora hoy tahola page delete hoba na. 1st page delete korta hoba tar por user delete korta parbo
limit_choices_to={'is_staff':True}----> ja user ar is_staff':True sai page create korta parba
primary_key=True--------------> field ka primary key set karar janna

models.py(gs109) 
      from django.db import models
      from django.contrib.auth.models import User
      # Create your models here.
      class Page(models.Model):
       user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
      #  user = models.OneToOneField(User, on_delete=models.PROTECT, primary_key=True)
      #  user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, limit_choices_to={'is_staff':True})
       page_name = models.CharField(max_length=70)
       page_cat = models.CharField(max_length=70)
       page_publish_date = models.DateField()
    
models.py(gs110) 
      from django.db import models
      from django.contrib.auth.models import User
      # Create your models here.
      class Page(models.Model):
       user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
       page_name = models.CharField(max_length=70)
       page_cat = models.CharField(max_length=70)
       page_publish_date = models.DateField()
      
      class Like(Page):
       panna = models.OneToOneField(Page, on_delete=models.CASCADE, primary_key=True, parent_link=True)
       likes = models.IntegerField()
    

2. Many to One Relationship(gs111)

models.py 
      from django.db import models
      from django.contrib.auth.models import User
      # Create your models here.
      class Post(models.Model):
       # user = models.ForeignKey(User, on_delete=models.CASCADE)
       # user = models.ForeignKey(User, on_delete=models.PROTECT)
       user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
       post_title =  models.CharField(max_length=70)
       post_cat =  models.CharField(max_length=70)
       post_publish_date =  models.DateField()
    

3. Many to Many Relationship(gs112)

models.py 
      from django.db import models
      from django.contrib.auth.models import User
      # Create your models here.
      class Song(models.Model):
       user = models.ManyToManyField(User)
       song_name = models.CharField(max_length=70)
       song_duration = models.IntegerField()
      
       def written_by(self):
        p= ",".join([str(p) for p in self.user.all()])
        # print(p)
        return p
    

Model Relationship with queryset(gs113)

models.py 
      from django.db import models
      from django.contrib.auth.models import User
      # Create your models here.
      class Page(models.Model):
       user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, related_name='mypage')
       page_name = models.CharField(max_length=70)
       page_cat = models.CharField(max_length=70)
       page_publish_date = models.DateField()
      
      class Post(models.Model):
       user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='mypost')
       post_title = models.CharField(max_length=70)
       post_cat = models.CharField(max_length=70)
       post_publish_date = models.DateField()
      
      class Song(models.Model):
       user = models.ManyToManyField(User)
       song_name = models.CharField(max_length=70)
       song_duration = models.IntegerField()
      
       def written_by(self):
          return ",".join([str(p) for p in self.user.all()])
    
views.py 
      from django.shortcuts import render
      from .models import Page, Post, Song, User
      
      def home(request):
        return render(request, 'myapp/home.html')
      
      def show_user_data(request):
        data1 = User.objects.all()
        data2 = User.objects.filter(email='contact@geekyshows.com')
        # data3 = User.objects.filter(page__page_cat='Programming')
        data3 = User.objects.filter(mypage__page_cat='Programming')
        data4 = User.objects.filter(mypost__post_publish_date='2020-05-28')
        data5 = User.objects.filter(song__song_duration=3)
        return render(request, 'myapp/user.html', {'data1':data1, 'data2':data2, 'data3':data3, 'data4':data4, 'data5':data5})
      
      def show_page_data(request):
        data1 = Page.objects.all()
        data2 = Page.objects.filter(page_cat='Programming')
        data3 = Page.objects.filter(user__email='contact@geekyshows.com')
        return render(request, 'myapp/page.html', {'data1':data1, 'data2':data2, 'data3':data3})
      
      def show_post_data(request):
        data1 = Post.objects.all()
        data2 = Post.objects.filter(post_publish_date='2020-05-28')
        data3 = Post.objects.filter(user__username='sonam')
        return render(request, 'myapp/post.html', {'data1':data1, 'data2':data2, 'data3':data3})
      
      def show_song_data(request):
        data1 = Song.objects.all()
        data2 = Song.objects.filter(song_duration=3)
        data3 = Song.objects.filter(user__username='sonam')
        return render(request, 'myapp/song.html', {'data1':data1, 'data2':data2, 'data3':data3})
      
    



Type of Views

  1. Function Based View
  2. Class Based View


2. Class Based View
  1. Base Class-Based Views / Base View
  2. Generic Class-Based Views / Generic View

1. Base Class-Based Views / Base View
  1. View
  2. TemplateView
  3. RedirectView


2. Generic Class-Based Views / Generic View

  1. Display View – ListView, DetailView
  2. Editing View – FormView, CreateView, UpdateView, DeleteView

ListView

Return all(multipule object) data

Example-1(gs18)

models.py 
      from django.db import models

      # Create your models here.
      class Student(models.Model):
      name = models.CharField(max_length=70)
      roll = models.IntegerField()
      course = models.CharField(max_length=70)
    
views.py 
      from django.shortcuts import render
      from django.views.generic.list import ListView
      from .models import Student
      # Create your views here.
      class StudentListView(ListView):
       model = Student
      
      
      ###############################################################
      
      #  stud=Student.objects.all()
      #  contex={'student_list':stud}
      #  return render(request,'school/student_list.html',context)
      
    
urls.py 
      from django.contrib import admin
      from django.urls import path
      from school import views
      urlpatterns = [
          path('admin/', admin.site.urls),
          path('student/', views.StudentListView.as_view(), name='student')
      ]
      
    
student_list.html 
      <!DOCTYPE html>
      <html lang="en">
      <head>
       <meta charset="UTF-8">
       <meta name="viewport" content="width=device-width, initial-scale=1.0">
       <title>Document</title>
      </head>
      <body>
       {% for student in student_list %}
        {{student.name}}
        {{student.roll}}
        {{student.course}} <br>
       {% endfor %}
      </body>
      </html>
      
    

Example-2(gs119)

views.py 
      from django.shortcuts import render
      from django.views.generic.list import ListView
      from .models import Student
      # Create your views here.
      class StudentListView(ListView):
       model = Student
       template_name_suffix = '_get'
       ordering = ['name']
      
    
student_get.html 
      <!DOCTYPE html>
      <html lang="en">
      <head>
       <meta charset="UTF-8">
       <meta name="viewport" content="width=device-width, initial-scale=1.0">
       <title>Document</title>
      </head>
      <body>
       {% for student in student_list %}
        {{student.name}}
        {{student.roll}}
        {{student.course}} <br>
       {% endfor %}
      </body>
      </html>
      
    

Example-3(gs120)

views.py 
      from django.shortcuts import render
      from django.views.generic.list import ListView
      from .models import Student
      # Create your views here.
      class StudentListView(ListView):
       model = Student
       template_name = 'school/student.html'
       context_object_name = 'students'
      
    
student.html 
      <!DOCTYPE html>
      <html lang="en">
      <head>
       <meta charset="UTF-8">
       <meta name="viewport" content="width=device-width, initial-scale=1.0">
       <title>Document</title>
      </head>
      <body>
       {% for student in students %}
        {{student.name}}
        {{student.roll}}
        {{student.course}} <br>
       {% endfor %}
      </body>
      </html>
      
    

Example-4(gs121)

views.py 
      from django.shortcuts import render
      from django.views.generic.list import ListView
      from .models import Student
      # Create your views here.
      class StudentListView(ListView):
       model = Student
       template_name = 'school/student.html'
       context_object_name = 'students'
      
       def get_queryset(self):
        return Student.objects.filter(course='Django',roll=105)
      
       def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(*args, **kwargs)
        context['freshers'] = Student.objects.all().order_by('name')
        return context
      
      #  def get_template_names(self):
      #   if self.request.COOKIES['user'] == 'sonam':
      #    template_name = 'school/sonam.html'
      #   else:
      #    template_name = self.template_name
      #   return [template_name]
      
       # def get_template_names(self):
       #  if self.request.user.is_superuser:
       #   template_name = 'school/superuser.html'
       #  elif self.request.user.is_staff:
       #   template_name = 'school/staff.html'
       #  else:
       #   template_name = self.template_name
       #  return [template_name]
      
    
student.html 
      <!DOCTYPE html>
      <html lang="en">
      <head>
       <meta charset="UTF-8">
       <meta name="viewport" content="width=device-width, initial-scale=1.0">
       <title>Document</title>
      </head>
      <body>
       {% for student in students %}
        {{student.name}}
        {{student.roll}}
        {{student.course}} <br>
       {% endfor %}
      <hr>
       {% for fresher in freshers %}
        {{fresher.name}}
        {{fresher.roll}}
        {{fresher.course}} <br>
       {% endfor %}
      </body>
      </html>
      
    

DetailView(gs123, gs124, gs125)

Return singal data(object), so, we have to specify in url

views.py 
      from django.shortcuts import render
      from .models import Student
      from django.views.generic.detail import DetailView
      from django.views.generic.list import ListView
      # Create your views here.
      class StudentDetailView(DetailView):
       model = Student
       template_name = 'school/student.html'
      
       def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(*args, **kwargs)
        context['all_student'] = self.model.objects.all().order_by('name')
        return context
      
      class StudentListView(ListView):
       model = Student
    
urls.py 
      from django.contrib import admin
      from django.urls import path
      from school import views
      urlpatterns = [
          path('admin/', admin.site.urls),
          path('student/', views.StudentListView.as_view(), name='studentlist'),
          path('student/', views.StudentDetailView.as_view(), name='studentdetail'),
      ]
      
    
student.html 
      <!DOCTYPE html>
      <html lang="en">
      <head>
       <meta charset="UTF-8">
       <meta name="viewport" content="width=device-width, initial-scale=1.0">
       <title>Document</title>
      </head>
      <body>
       <h1>Student_detail Page</h1>
       {{student.id}}
       {{student.name}}
       {{student.roll}}
       {{student.course}}
       <hr>
        {% for stu in all_student %}
         <li><a href="{% url 'studentdetail' stu.id %}">{{stu.name}}</a></li>
        {% endfor %}
      </body>
      </html>
      
    
student_list.html 
      <!DOCTYPE html>
      <html lang="en">
      <head>
       <meta charset="UTF-8">
       <meta name="viewport" content="width=device-width, initial-scale=1.0">
       <title>Document</title>
      </head>
      <body>
       <h1>Student List</h1>
       {% for stu in student_list %}
        <li><a href="{% url 'studentdetail' stu.id %}">{{stu.name}}</a></li>
       {% endfor %}
      </body>
      </html>
      
    
FormView-----------> for display form
CreateView----------->(display form, Displaying the form with validation errors, saving the object) A view that displays a form for creating an object, redisplaying the form with validation errors (if there are any) and saving the object.
UpdateView-----------> using update view we can edit particular data,(get particular data and update that data) in url we have to pass id 
 DeleteView-----------> using delete view we can delete particular data,in url we have to pass id

Authentication Views



Server

 Python manage.py runserver ===> It is used for Development server, it has good feature auto restart when we are add or edit smoothing d...