Full Stack Module 3 Notes
Full Stack Module 3 Notes
Module-03
Update MIDDLEWARE_CLASSES:
Ensure the following middlewares are included and uncommented:
• 'django.middleware.common.CommonMiddleware'
• 'django.contrib.sessions.middleware.SessionMiddleware'
• 'django.contrib.auth.middleware.AuthenticationMiddleware'
Execute python manage.py sync db to install the necessary database tables for the
admin interface.
If not prompted to create a super user,run python manage.py create super user to create
an admin account.
Update urls.py:
Logging In:
Visit the adminsite and login with the super user credentials you created.
If you can't login,ensure you’ve created as uperuser by running python manage.py
create super user.
Figure:Django’sloginscreen
After logging in,you'll see the admin home page listing all datatypes available for
editing. Initially, it includes only Groups and Users.
Data Management:
Each datatype in the admin site has a change list and an edit form.
Change List:Displays all records of a data type,similar to a SELECT*FROM<table>
SQL query.
Edit Form: Allows yout o add, change,or delete individual records.
Managing Users:
Click the Change link in the Users row o load the change-list page for users.
Filtering:Options are on the right.
Sorting:Click a column header.
Search:Use the search boxa t the top.
Click a username to see the editform for that user.
Change user attributes such as first/lastnames and permissions.
To change a user's password, click the Change Password Form link.
Different field types have differen tinput widgets(e.g.,calendar controls for date fields,
check boxes for Boolean fields).
Add Record:Click Add in the appropriate column on the admin home page empty edit
form for creating a new record.
Delete Record: Click the Delete button at the bottom left of an edit form. Confirm the
deletion on the sub sequent page,which may list dependen to bjects to be deleted as
well.
Input Validation:
The admin interface validates input automatically.Errors will be displayed if you leave
required fields blank or enter invalid data.
History:
When editing an object,a History link appears in the upper-right corner.This logs every
change made through the admin interface and allows you to review the change history.
Figure:-Anobjecthistory page
In the Django adminsite, each field’s label is derived fromits model name.
To customize a label,use the ver name attribute in your model field definitions.
Example:
classAuthor(models.Model):
first_name=models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
email=models.EmailField(blank=True,verbose_name='e-mail')
Alternatively,you can pass verbose_name as a positional argument:
class Author(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
email=models.EmailField('e-mail',blank=True)
Custom Model Admin Classes
Model Admin classes allow customization of how models are displayed and managed
in the admin interface.
Customizing ChangeLists
By default, change lists show the result of the model's str or unicode method. You
can specify which fields to display using the list_display attribute.
Example:
class AuthorAdmin(admin.ModelAdmin):
list_display=('first_name','last_name','email')
search_fields = ('first_name', 'last_name')
Adding Date Filters
Add list_filter to yourBookAdmin:
classBookAdmin(admin.Model Admin):
list_display=('title','publisher','publication_date')
list_filter = ('publication_date',)
Class BookAdmin(admin.ModelAdmin):
fields=('title','authors','publisher','publication_date')
Excluding Fields
Class Book
Admin(admin.ModelAdmin): fields =
('title', 'authors', 'publisher')
Class BookAdmin(admin.ModelAdmin):
filter_horizontal = ('authors',)
Alternatively,use filter_vertical:
Class BookAdmin(admin.ModelAdmin):
filter_vertical = ('authors',)
Class BookAdmin(admin.ModelAdmin):
raw_id_fields = ('publisher',)
1. Public Interfaces:
Security and Usability:The admininterface is not designed for public use.It lacks
the security measures and user-friendly design necessary for a public-facing
application.
2. Sophisticated Sorting and Searching:
Advanced Data Handling: While the admin site provides basic sorting and
searching capabilities, it’s not built for advanced data manipulation. For complex
data queries and manipulations, custom views and tools are more appropriate.
Form Processing
1. Introduction to Forms
Django provides a built-in form handling functionality that simplifies the process
of handling HTML forms in web applications.
Forms in Django are represented by Pythonclasses that map to HTML form fields.
2. Creating a Form
In Django,forms are created by sub classing the forms.Formclass or the
forms.ModelForm class (for model-based forms).
Each form field is represented by a class attribute,and the type of the field is
determined by the corresponding Django Field class.
Example:
Class ContactForm(forms.Form):
name=forms.CharField(max_length=100)
email = forms.EmailField()
message=forms.CharField(widget=forms.Text area)
3. Rendering a Form
Forms can be rendered in templates using the{{form.as_p}}(for paragraph-based
rendering) or {{ form.as_table }} (for table-based rendering) template tags.
Individual form fields can be rendered using{{form.field_name}}.
7. Form Widgets
Django provides a wide range of built-in form widgets (e.g., Text Input, Text
area, Check box Input, Select, etc.) for rendering form fields.
You can customize the rendering of form fields by specifying the widget
argument when defining the field.
9. Form Inheritance
Django supports form inheritance,allowing you to createre usable form
components and extend or override them as needed.
You can use the Metaclass to specify form-level attributes,such as
labels,help_texts, and error_messages.
Create a new file forms.py in your Django app directory, and add the following code
from django import forms
Class FeedbackForm(forms.Form):
name=forms.CharField(max_length=100,label='YourName')
email = forms.EmailField(label='Your Email')
subject=forms.CharField(max_length=200, label='Subject')
message=forms.CharField(widget=forms.Textarea,label='Your Feedback')
Create a new file feedback.html in your Django app's templates directory, and add the following
code:
<!DOCTYPEhtml>
<html>
<head>
<title>FeedbackForm</title>
</head>
<body>
<h1>Feedback Form</h1>
<form method="post">
{%csrf_token %}
{{form.non_field_errors}}
<div>
{{form.name.errors}}
{{form.name.label_tag}}
{{form.name}}
</div>
<div>
{{form.email.errors}}
{{form.email.label_tag}}
{{form.email}}
</div>
<div>
{{form.subject.errors}}
{{form.subject.label_tag}}
{{form.subject}}
</div>
<div>
{{form.message.errors}}
{{form.message.label_tag}}
{{form.message}}
{%csrf_token %}
{{form.non_field_errors}}
<div>
{{form.name.errors}}
{{form.name.label_tag}}
{{form.name}}
</div>
<div>
{{form.email.errors}}
{{form.email.label_tag}}
{{form.email}}
</div>
<div>
{{form.subject.errors}}
{{form.subject.label_tag}}
{{form.subject}}
</div>
<div>
{{form.message.errors}}
{{form.message.label_tag}}
{{form.message}}
</div>
<inputtype="submit"value="SubmitFeedback">
</form>
</body>
</html>
Create a new file feedback_success.html in your Django app's templates directory, and add the
following code:
<!DOCTYPE html>
<html>
<head>
<title>Feedback Submitted</title>
</head>
<body>
</body>
</html>
Open your Django app's views.py file and add the following code:
from django.shortcuts import render
from.forms import Feedback Form
def feedback(request):
if request.method=='POST':
form=FeedbackForm(request.POST)
if form.is_valid():
#Processthefeedbackdata
name = form.cleaned_data['name']
email = form.cleaned_data['email']
subject = form.cleaned_data['subject']
message=form.cleaned_data['message']
return render(request,'feedback_success.html')
else:
form=FeedbackForm()
return render(request,'feedback.html',{'form':form})
Open your Django app's urls.py file and add the following URL pattern:
from django.urls import path
from.import views
url patterns=[
path('feedback/',views.feedback, name='feedback'),]
Star the Django development server and navigate to http://localhost:8000/feedback/in your web
browser. You should see the feedback form.
Form submissions
1. Create a Form Class: Define a form class that inherits from forms.Form or
forms.ModelForm. This class defines the fields and validations for your form.
2. Render the Formin a Template: In your template,render the form using the{{form}}
template tag or individual field tags like {{ form.field_name }}.
3. Check Request Method: In your view function, check if the request method is POST
(form submission) or GET (initial form load).
4. Create Form Instance with Data: If the request method is POST,create a form instance
with the submitted data using form = Your Form(request.POST) or form = Your Model
Form(request.POST).
5. Validate the Form:Callform.is_valid() to validate the form data against the defined
fields and validations.
6. Process Valid Form Data: If the form is valid (form.is_valid() returns True), access the
cleaned data using form.cleaned_data and perform any necessary operations (e.g., saveto
the database, send an email, etc.).
7. Handle In valid Form Data:If the form is invalid(form.is_valid()returnsFalse),re-render
the form with error messages by passing the form instance to the template context.
8. Redirect or Render Success Page: After successful form processing, it's recommended
to redirect the user to a success page or a different view to prevent duplicate form
submissions on page refresh.
# forms.py
fromdjangoimportforms
classContactForm(forms.Form):
name=forms.CharField(max_length=100)
email = forms.EmailField()
message=forms.CharField(widget=forms.Textarea)
# views.py
fromdjango.shortcutsimportrender,redirect
from .forms import ContactForm
def contact(request):
ifrequest.method=='POST':
form=ContactForm(request.POST) if
form.is_valid():
#Processtheform data
name = form.cleaned_data['name']email
= form.cleaned_data['email']
message=form.cleaned_data['message']
return redirect('success_url')
else:
form=ContactForm()
returnrender(request,'contact.html',{'form': form})
<!--contact.html-->
<formmethod="post">
{%csrf_token %}
{{form.as_p}}
<inputtype="submit"value="Submit">
</form>
CustomValidation
defclean_message(self):
message=self.cleaned_data['message'] num_words
= len(message.split())
ifnum_words <4:
raiseforms.ValidationError("Notenoughwords!")
return message
This method:
Extracts the message from self.cleaned_data.
Counts the words usingsplit() and len().
Raises a Validation Error
Returns the cleaned message value.
You can customize the form's appearance using CSS and custom HTML
templates for better control over the presentation.
<html>
<head>
<title>Contactus</title>
</head>
<body>
<h1>Contactus</h1>
{%if form.errors%}
</p>
{%end if %}
<div class="field">
{{form.subject.errors}}
<label for="id_subject">Subject:</label>
{{form.subject}}
</div>
<div class="field">
{{form.email.errors}}
{{form.email}}
</div>
<div class="field">
{{form.message.errors}}
<label for="id_message">Message:</label>
{{form.message}}
</div>
</form>
</body>
</html>
This template:
Example
Class Contact(models.Model):
subject=models.CharField(max_length=100)
email = models.EmailField(blank=True)
message = models.TextField()
def str(self):
return self.subject
Example
Example:
Class ContacForm(forms.ModelForm):
class Meta:
model =Contact
def clean_message(self):
message=self.cleaned_data['message']
num_words = len(message.split())
if num_words <4:
Example
def contact_view(request):
if request.method=='POST':
form=ContactForm(request.POST) if
form.is_valid():
form.save()
form=ContactForm()
return render(request,'contact_form.html',{'form':form})
5. CreatetheTemplate
Objective :Design an HTML template to render and display the form.
Example
<html>
<head>
<title>ContactUs</title>
</head>
<body>
<h1>ContactUs</h1>
{%if form.errors%}
</p>
{%end if %}
<form method="post">
{%csrf_token %}
<div class="field">
{{form.subject.errors}}
<label for="id_subject">Subject:</label>
{{form.subject}}
</div>
<div class="field">
{{form.email.errors}}
{{form.email}}
</div>
<divclass="field">
{{form.message.errors}}
<label for="id_message">Message:</label>
{{form.message}}
</div>
1. Define the Model: Establish your data structure with a Django model.
2. Create the Mode lForm:Generate a form using forms.ModelForm based on the model.
3. Add Custom Validation: Optionally include custom validation methods within the form.
4. Use the Formin Views:Implement form handling logic in Django views to process
submissions.
5. Create the Template:Design an HTML template to display and manage the form
interface.
Example:
Example
From django.conf.urls.defaults import*
from mysite import views
urlpatterns = patterns('',
(r'^hello/$',views.hello),
(r'^time/$', views.current_datetime),
(r'^time/plus/(d{1,2})/$',views.hours_ahead),
)
Example
From django.conf.urls.defaults import*
urlpatterns = patterns('',
(r'^hello/$','mysite.views.hello'),
(r'^time/$', 'mysite.views.current_datetime'),
(r'^time/plus/(d{1,2})/$','mysite.views.hours_ahead'),
)
Advantage:No need to import view functions; Django handle imports automatically.
Example:
(r'^time/$', 'current_datetime'),
(r'^time/plus/(d{1,2})/$','hours_ahead'),
)
Basic Usage
Important Considerations