Django Notes
Django Notes
Django Installation
1
d. In app/views.py
def signup_view(request):
if request.method=='POST':
form=UserCreationForm(request.POST)
if form.is_valid():
form.save()
return redirect('login')
else:
form=UserCreationForm()
return render(request,'signup.html',locals())
def login_view(request):
if request.method == 'POST':
form = AuthenticationForm(request, data=request.POST)
if form.is_valid():
user = form.get_user()
login(request, user) # Log the user in
next_url = request.GET.get('next') # Get the next URL from the query
parameters
if next_url: # If there is a next URL, redirect there
return redirect(next_url)
return redirect('home') # Default redirect to home if no next URL
else:
messages.error(request, "Invalid username or password")
else:
form = AuthenticationForm()
return render(request, 'login.html', {'form': form})
def logout_view(request):
logout(request)
messages.success(request,"Logout Successfully")
return redirect('login')
e. in templates:
#signup:
<form method="POST">
{% csrf_token %}
2
{% for field in form %}
<div class="form-group">
<ul class="bullets" style="list-style-type: none; padding-left: 0; margin: 0;">
<li> {{ field.label_tag }} </li>
<li> {{ field }}</li>
</ul>
</div>
{% endfor %}
<br>
<button type="submit" class="btn btn-primary">Register</button>
</form>
{% if messages %}
<div class="message-container">
{% for message in messages %}
<div class="alert {{ message.tags }}">
{{ message }}
</div>
{% endfor %}
</div>
{% endif %}
<a href="{% url 'login' %}">Already have an account? Login</a>
# login
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Login</button>
</form>
{% if messages %}
<ul>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
<a href="{% url 'signup' %}">Don't have an account? Sign up</a>
#home
<a href="{% url 'logout' %}">Logout</a>
3
o MEDIA_ROOT = BASE_DIR / 'media'
o MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
In app/urls.py
o from django.conf import settings
o from django.conf.urls.static import static
o if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
o path('registration/',views.Studentview,name='registration')
models.py
class Student(models.Model):
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
id = models.CharField(primary_key=True,max_length=10) # Use AutoField
for an auto-incrementing primary key
photo = models.ImageField(upload_to='images/')
phone = models.CharField(max_length=15) # Change to CharField to allow
phone number formatting
branch = models.CharField(choices=choices_program, default='cse',
max_length=3)
def __str__(self):
return f"{self.first_name} {self.last_name} - {self.branch}"
Forms.py
class StudentForm(forms.ModelForm):
class Meta:
model = Student
fields = ['first_name', 'last_name', 'id', 'photo', 'phone',
'branch']
4
Admin.py
Views.py
def Studentview(request):
if request.method=='POST':
form=StudentForm(request.POST, request.FILES)
if form.is_valid():
form.save()
messages.success(request,"saved successfully")
else:
form=StudentForm()
return render(request,'registration.html',locals())
Registration.html
{% csrf_token %}
{% for field in form %}
<div class="form-group">
<ul class="bullets" style="list-style-type: none; padding-left: 0; margin: 0;">
<li> {{ field.label_tag }} </li>
<li> {{ field }}</li>
</ul>
</div>
{% endfor %}
<br>
<button type="submit" class="btn btn-primary">Register</button>
</form>
{% if messages %}
<div class="message-container">
{% for message in messages %}
<div class="alert {{ message.tags }}">
{{ message }}
</div>
5
{% endfor %}
</div>
{% endif %}
if request.method == 'POST':
form = VendorUpdateForm(request.POST, instance=vendor)
if form.is_valid():
form.save()
messages.success(request, 'Vendor details updated successfully.')
return redirect('vendor_list')
else:
form = VendorUpdateForm(instance=vendor)
6
Delete Member or Student
def delete_student(request,id):
student=get_object_or_404(Student,id=id)
student.delete()
return redirect('adminview')
Note: everything is same as above update.
Admin Panel
py manage.py createsuperuser
To include the Member model in the admin interface, we have to tell Django that this model should
be visible in the admin interface.
In app/admin.py
o from .models import Member
o
o # Register your models here.
o admin.site.register(Member)
set list display:
o We can control the fields to display by specifying them in in a list_display property in the
admin.py file.
o In admin.py of app
class MemberAdmin(admin.ModelAdmin):
admin.site.register(Member, MemberAdmin)
QuerySelect
A QuerySet is built up as a list of objects.
7
QuerySets makes it easier to get the data you actually need, by allowing you to filter
and order the data at an early stage.
def testing(request):
mydata = Member.objects.all()
context = {'mymembers': mydata}
return render(request, 'template.html', context)
//this will give all data from member table.
//template should be:
{% for x in mymembers %}
<tr>
<td>{{ x.id }}</td>
<td>{{ x.firstname }}</td>
<td>{{ x.lastname }}</td>
</tr>
{% endfor %}
Note:
mydata = Member.objects.all().values() -this will return data in dictionary format
mydata = Member.objects.values_list('firstname')- to make a list
mydata = Member.objects.filter(firstname='Emil').values() to return
particular row
mydata = Member.objects.filter(lastname='Refsnes', id=2).values() AND
query
mydata = Member.objects.filter(firstname='Emil').values() |
Member.objects.filter(firstname='Tobias').values() OR query
mydata = Member.objects.all().order_by('firstname').values() ascending
order
mydata = Member.objects.all().order_by('-firstname').values()
descending order
8
STATIC_ROOT = BASE_DIR / 'productionfiles'
STATIC_URL = 'static/'
py manage.py collectstatic
2. for images upload
pip install Pillow
in models.py
MVT
The MVT (Model View Template) is a software design pattern. It is a collection of three important components Model
View and Template. The Model helps to handle database. It is a data access layer which handles the data.
1. model.py
class Vendor_Registration(models.Model):
username = models.CharField(max_length=150, unique=True)
email = models.EmailField()
password = models.CharField(max_length=255)
confirm_password = models.CharField(max_length=255)
def __str__(self):
return self.username
2. forms.py
9
class VendorForm(forms.ModelForm):
class Meta:
model = Vendor_Registration
fields = ['username', 'email', 'password', 'confirm_password']
widgets = {
'password': forms.PasswordInput(),
'confirm_password': forms.PasswordInput(),
}
def clean(self):
cleaned_data = super().clean()
password = cleaned_data.get("password") # Fixed typo here
confirm_password = cleaned_data.get("confirm_password")
return cleaned_data
class LoginForm(forms.Form):
username = forms.CharField(max_length=150)
password = forms.CharField(widget=forms.PasswordInput)
3. views.py
def HomeView(request):
return render(request,"home.html")
def Vendor_Registration_View(request):
if request.method=="POST":
form=VendorForm(request.POST)
if form.is_valid():
form.save()
messages.success(request,"registration successfull")
return redirect("vendor_login")
else:
messages.error(request,"please correct the error below")
else:
form=VendorForm()
return render(request,"vendor_registration.html",{'form':form})
def Login_View(request):
form = LoginForm(request.POST or None)
10
if user.password == password:
request.session['vendor_id'] = user.id
return redirect('vendor_home')
else:
messages.error(request, "Invalid credentials.")
except Vendor_Registration.DoesNotExist:
messages.error(request, "Vendor does not exist. Please register.")
return render(request, 'vendor_login.html', {'form': form})
def Logout_View(request):
if 'vendor_id' in request.session:
del request.session['vendor_id']
messages.success(request, "You have successfully logged out.")
else:
messages.info(request, "You are not logged in.")
return redirect('home')
4. urls.py
5. templates/html files are same as above. (most important part is in form and login.view)
MODEL
Each model class maps to a single table in the database.
Django Model is a subclass of django.db.models.Model and each field of the model class represents a
database field (column).
Django provides us a database-abstraction API which allows us to create, retrieve, update and delete a
record from the mapped table.
Model is defined in Models.py file.
For Example:
class Employee(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
Field Name Class Particular
11
It is a 64-bit integer, much like
AutoField except that it is guaranteed t
BigAutoField class BigAutoField(**options)
numbers from 1
9223372036854775807.
class FileField(upload_to=None,
FileField It is a file-upload field.
max_length=100, **options)
12
It is an integer field. Values from
IntegerField class IntegerField(**options) 2147483648 to 2147483647 are safe i
databases supported by Django.
The default value for the field. This can be a value or a call
Default
object.
13
Django Model Forms
from django import forms
from myapp.models import Student
class EmpForm(forms.ModelForm):
class Meta:
model = Student
fields = "__all__"
in views.py
1. def index(request):
2. stu = EmpForm()
3. return render(request,"index.html",{'form':stu}
The is_valid() method is used to perform validation for each field of the form, it is defined in Django Form class.
the forms.FileField() method is used to create a file input and submit the file to the server. While working with files,
make sure the HTML form tag contains enctype="multipart/form-data" property.
2. {% csrf_token %}
3. {{ form.as_p }}
5. </form>
def index(request):
if request.method == 'POST':
student = StudentForm(request.POST, request.FILES)
14
Django Exception
Django core exceptions classes are defined in django.core.exceptions module. This module contains the following
classes.
Exception Description
15
It is raised when data validation fails form or model field
ValidationError
validation.
Exception Description
Exception Description
DataError It raises when data related issues come into the database.
16
def getdata(request):
try:
data = Employee.objects.get(id=12)
except ObjectDoesNotExist:
return HttpResponse("Exception: Data not found")
return HttpResponse(data);
Session
A session is a mechanism to store information on the server side during the interaction with the web application.
In Django, by default session stores in the database and also allows file-based and cache based sessions. It is
implemented via a piece of middleware and can be enabled by using the following code.
To set and get the session in views, we can use request.session and can set multiple times too.
The class backends.base.SessionBase is a base class of all session objects. It contains the following
standard methods.
Method Description
def setsession(request):
request.session['sname'] = 'irfan'
request.session['semail'] = 'irfan.sssit@gmail.com'
17
return HttpResponse("session is set")
1. path('ssession',views.setsession),
2. path('gsession',views.getsession)
Cookie
The set_cookie() method is used to set a cookie and get() method is used to get the cookie.
def setcookie(request):
response = HttpResponse("Cookie Set")
response.set_cookie('java-tutorial', 'javatpoint.com')
return response
def getcookie(request):
tutorial = request.COOKIES['java-tutorial']
return HttpResponse("java tutorials @: "+ tutorial);
1. path('scookie',views.setcookie),
2. path('gcookie',views.getcookie)
Django PDF
To generate PDF, we will use ReportLab Python PDF library that creates customized dynamic PDF.
// views.py
3.
4. def getpdf(request):
5. response = HttpResponse(content_type='application/pdf')
7. p = canvas.Canvas(response)
8. p.setFont("Times-Roman", 55)
10. p.showPage()
11. p.save()
18
12. return response
First, provide MIME (content) type as application/pdf, so that output generates as PDF rather than HTML,
Set Content-Disposition in which provide header as attachment and output file name.
Pass response argument to the canvas and drawstring to write the string after that apply to the save() method and
return response.
// urls.py
1. path('pdf',views.getpdf)
Relationship model
1. One-to-One Relationship
from django.db import models
class User(models.Model):
name = models.CharField(max_length=100)
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
bio = models.TextField()
2. 2. Many-to-One Relationship (ForeignKey)
class Author(models.Model):
name = models.CharField(max_length=100)
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
3. 3. Many-to-Many Relationship
class Student(models.Model):
name = models.CharField(max_length=100)
class Course(models.Model):
title = models.CharField(max_length=100)
students = models.ManyToManyField(Student)
PDF
pip install WeasyPrint
# pdfapp/views.py
from django.shortcuts import render
from django.http import HttpResponse
from weasyprint import HTML
def generate_pdf(request):
# Render the HTML template
html_string = render(request, 'pdfapp/template.html', {}).content.decode()
# Create PDF from rendered HTML
pdf = HTML(string=html_string).write_pdf()
# Return PDF as response
19
response = HttpResponse(pdf, content_type='application/pdf')
response['Content-Disposition'] = 'inline; filename="output.pdf"'
return response
# pdfapp/urls.py
urlpatterns = [
# myproject/urls.py
urlpatterns = [
path('admin/', admin.site.urls),
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>PDF Report</title>
20
<style>
h1 { color: #333; }
</style>
</head>
<body>
</body>
</html>
21