Module 3
Module 3
Module-03
Django Admin Interfaces and Model Forms
Admin Interfaces :
An admin interface is an essential part of the infrastructure. It provides a ready to
use, customizable, web based interface for managing the data in your django
application that enables the addition, editing, and deletion of site content. Use of
interface to post to your blog, the back-end site managers use to moderate reader-
generated comments, the tool your clients use to update the press releases on the
Web site you built for them.
The admin interface is automatically generated based on your django models.
making it easy to perform common crud operations on your applications data
without having to write custom views are forms.
the Django admin interface is a versatile tool that simplifies data management,
content management, and user management tasks in Django applications. It
provides a user-friendly interface for administrators and content editors, while also
offering flexibility and extensibility for developers to customize and extend its
functionality.
2. Customization:
While the admin interface is automatically generated, Django provides extensive
customization options.
You can customize the appearance and behaviour of the admin interface using
Python classes and options.
Customizations include defining custom admin views, adding filters, creating
custom actions, and more.
1
MODULE-3, FSD
4. Internationalization:
Django's admin interface supports internationalization out of the box.
You can easily translate the admin interface into multiple languages, making it
accessible to users from different regions.
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'
2
MODULE-3, FSD
Update urls.py:
Include the admin site in URLconf:
• Ensure the following import statements are present
from django.contrib import admin
admin.autodiscover()
3
MODULE-3, FSD
Data Management:
4
MODULE-3, FSD
• Each data type 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 you to add, change, or delete individual records.
Managing Users:
• Click the Change link in the Users row to load the change-list page for users.
• This page shows all users in the database, with options for filtering, sorting, and
searching.
• Filtering: Options are on the right.
• Sorting: Click a column header.
• Search: Use the search box at the top.
• Click a username to see the edit form for that user.
• Change user attributes such as first/last names and permissions.
• To change a user's password, click the Change Password Form link.
• Different field types have different input widgets (e.g., calendar controls for date
fields, checkboxes for Boolean fields).
Adding Records
Input Validation:
• The admin interface validates input automatically. Errors will be displayed if you
leave required fields blank or enter invalid data
6
MODULE-3, FSD
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.
7
MODULE-3, FSD
name = models.CharField(max_length=100)
price = models.DecimalField(max_digits=10, decimal_places=2)
description = models.TextField()
def_str_(self):
8
MODULE-3, FSD
return self.name
Step 3: Register the Model with the Admin Interface
3. Register the Product model with the admin interface by modifying the admin.py
file
#myapp/admin.py
from django.contrib import admin
admin.site.register(Product)
Customize the appearance ModelAdmin class: of the Product model in the admin
interface by creating a cu
#myapp/admin.py
Example 2:
• To change the Author.email field's label to “e-mail”:
class Author(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
10
MODULE-3, FSD
11
MODULE-3, FSD
12
MODULE-3, FSD
FORM PROCESSING
Form processing in Django involves handling form submissions from users,
validating the data, and performing actions based on the submitted data. Let's go
through the steps involved in form processing with Django.
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 Python classes that map to HTML form fields.
13
MODULE-3, FSD
14
MODULE-3, FSD
15
MODULE-3, FSD
Django provides built-in validation for common field types (e.g., EmailField,
IntegerField, etc.).
• You can define custom validation rules by overriding the clean_fieldname()
method in your form class.
• For complex validation rules, you can override the clean() method in your form
class.
16
MODULE-3, FSD
17
MODULE-3, FSD
<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 }}
</div>
<input type=”submit” value=”Submit Feedback”>
</form>
</body></html>
Step 3: Create the Success Template
18
MODULE-3, FSD
19
MODULE-3, FSD
form = FeedbackForm()
return render(request, 'feedback.html', {'form': form})
Step 5: Add URL Pattern
Open your Django app's urls.py file and add the following URL pattern:
from django.urls import path
from . import views
urlpatterns = [
# ... other URL patterns
path('feedback/', views.feedback, name='feedback'),
]
Step 6: Run the Development Server
Start the Django development server and navigate to
http://localhost:8000/feedback/ in your web browser. You should see the feedback
form.
20
MODULE-3, FSD
Form submissions
Form submissions in Django involve handling data sent from HTML forms,
processing it in views, and performing actions based on the submitted data. Here's a
step-by-step guide on how to handle form submissions in Django:
Step 1: Create a Form
Define a form class in your Django app's forms.py file. This form class should
inherit from django.forms.Form or one of its subclasses like django.forms.
ModelForm. Here's an example of a simple form:
#myapp/forms.py
from django import forms
cla name forms.CharField(max_length=100)
email forms.Email Field()
Step 2: Create a View
Define a view function or class-based view to handle form submissions. In the view,
you'll handle form submission, validate the data, and perform actions based on the
submitted data. Here's
an example of a view function:
#myapp/views.py
from django.shortcuts import render
from.forms import MyForm
def my_form_view(request): ss MyForm(forms.Form):
if request.method == 'POST':
form = MyForm(request.POST)
if form.is_valid():
name = form.cleaned_data['name']
email = form.cleaned_data['email']
# Process the form data (e.g, save to database)
# Redirect to a success page or render a template
21
MODULE-3, FSD
else:
form = MyForm()
return render(request, 'my_template.html', {'form': form})
Step 3: Create a Template
Create an HTML template to render the form. Include the form fields in the
template using Django template language. Here's an example of a template
(my_template.html):
<!-- myapp/templates/my_template.html -->
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
Step 4: Configure URLs
Map the view to a URL pattern in your Django project's urls.py file:
#mvproject/urls.pv
from django.urls import path
from myapp import views
urlpattern=[ path(‘my-form/’, views.my_form_view, name=’my-form’),]
Step 5: Handling Form Submission
When a user submits the form, Django processes the form data in the view. If the
form is submitted via POST method, Django initializes the form with the
submitted data (request.POST), validates it and makes the cleaned data available
as form.cleaned_data. Yu can then perform actions based on this data, such as
saving it to a database.
Step 6: Displaying Validation errors
If the form data is invalid, Django automatically renders the formwith validation
errors. You can access these errors in the template using form.errors or display
them alongside form fields using form.field.errors.
Step 7: Adding CSRF Token
22
MODULE-3, FSD
Always include a CSRF token in your forms to protect against CSRF attacks. Use
the {% csrf_token %} template tag to include the CSRF token in your form.
Step 8: Redirecting or Rendering Responses
After processing the form data, you can redirect the user to a success page or
render a template. Alternatively, you can render the same template with the form
to allow users to correct any validations errors
You have now implemented form submissions in dango, allowing users to submit
data through a form, validating it, and performing actions based on the submitted
data.
Custom Validation
Custom validation in Django allows you to define custom logic to validate form
fields beyond the default field validation provided by Djangos form classes. You
can create custom validation methods within your form class to enforce specific
validation rules.
Define the Form Class:
• Use Django's forms.Form to define the fields of the form
#myapp/form.py
from django import forms
class ContactForm(forms.Form):
subject = forms.CharField(max_length=100)
email = forms.EmailField(required=False)
message = forms.CharField(widget=forms.Textarea)
2. Add a Custom Validation Method:
• Create a clean_message() method to enforce the minimum word count.
def clean_message(self):
message = self.cleaned_data['message']
num_words = len(message.split())
if num_words < 4:
raise forms.ValidationError("Not enough words!")
23
MODULE-3, FSD
return message
• This method:
• Extracts the message from self.cleaned_data.
• Counts the words using split() and len().
• Raises a ValidationError if there are fewer than four words.
• Returns the cleaned message value.
Customizing Form Design
• You can customize the form's appearance using CSS and custom HTML
templates for better control over the presentation.
1. CSS for Error Styling:
• Define CSS to style error messages for better visibility
<style type="text/css">
ul.errorlist {
margin: 0;
padding: 0;
}
.errorlist li {
background-color: red;
color: white;
display: block;
font-size: 10px;
margin: 0 0 3px;
padding: 4px 5px;
}
</style>
2. Custom HTML Template:
• Instead of using {{ form.as_table }}, manually render the form fields for finer
24
MODULE-3, FSD
control.
<html>
<head>
<title>Contact us</title>
</head>
<body>
<h1>Contact us</h1>
{% if form.errors %}
<p style="color: red;">
Please correct the error{{ form.errors|pluralize }} below.
</p>
{% endif %}
<form action="" method="post">
<div class="field">
{{ form.subject.errors }}
<label for="id_subject">Subject:</label>
{{ form.subject }}
</div>
<div class="field">
{{ form.email.errors }}
<label for="id_email">Your e-mail address:</label>
{{ form.email }}
</div>
<div class="field">
{{ form.message.errors }}
<label for="id_message">Message:</ label>
25
MODULE-3, FSD
{{ form.message }}
<input type=‘Submit”>
</form></body></html>
26
MODULE-3, FSD
1. Define the Model : Model will serves as the basis for your model
form
• Objective: Create a Django model to represent the data structure.
Example
from django.db import models
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:
class ContactForm(forms.ModelForm):
class Meta:
model = Contact
fields = ['subject', 'email', 'message']
def clean_message(self):
message = self.cleaned_data['message']
num_words = len(message.split())
if num_words < 4:
raise forms.ValidationError("Not enough words!")
return message
28
MODULE-3, FSD
form = ContactForm()
return render(request, 'contact_form.html', {'form': form})
5. Create the Template
• Objective: Design an HTML template to render and display the form.
Example
<html>
<head>
<title>Contact Us</title>
</head>
<body>
<h1>Contact Us</h1>
{% if form.errors %}
<p style="color: red;">
Please correct the error{{ form.errors|pluralize }} below.
</p>
{% endif %}
<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 }}
29
MODULE-3, FSD
1.Define the Model: Establish your data structure with a Django model.
2. Create the Model Form: 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 Form in Views: Implement form handling logic in Django
views to process submissions.
30
MODULE-3, FSD
URLConf Ticks
URLConf is a set of patterns used by the URL dispatcher to determine
the view that should handle an incoming HTTP request.
Streamlining Function Imports
1. Traditional Method: Direct Import of View Functions
Example:
from django.conf.urls.defaults import *
from mysite.views import hello, current_datetime, hours_ahead
urlpatterns = patterns('',
(r'^hello/$', hello),
(r'^time/$', current_datetime),
(r'^time/plus/(\d{1,2})/$', hours_ahead),
)
• Disadvantage: Tedious to manage imports as the application grows.
2. Importing the Views Module
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),
31
MODULE-3, FSD
)
• Advantage: Simplifies imports, but still requires module import.
3. Using Strings to Specify View Functions
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 handles imports
automatically.
4. Factoring Out a Common View Prefix
Example:
from django.conf.urls.defaults import *
urlpatterns = patterns('mysite.views',
(r'^hello/$', 'hello'),
(r'^time/$', 'current_datetime'),
(r'^time/plus/(d{1,2})/$', 'hours_ahead'),
)
• Advantage: Reduces redundancy by factoring out common prefixes.
Choosing Between Methods
• Advantages of the String Approach:
• More compact, no need to import view functions explicitly.
32
MODULE-3, FSD
33
MODULE-3, FSD
Example Breakdown
• Main URLconf:
from django.conf.urls.defaults import *
urlpatterns = patterns('',
(r'^weblog/', include('mysite.blog.urls')),
(r'^photos/', include('mysite.photos.urls')),
(r'^about/$', 'mysite.views.about'),
)
• Included URLconf (mysite.blog.urls):
from django.conf.urls.defaults import *
urlpatterns = patterns('',
(r'^(\d\d\d\d)/$', 'mysite.blog.views.year_detail'),
(r'^(\d\d\d\d)/(\d\d)/$', 'mysite.blog.views.month_detail'),
)
Sample Request Handling
1. Request: /weblog/2007/
• First URLconf: r'^weblog/' matches.
• Action: Strips weblog/.
34
MODULE-3, FSD
**********************************************************
35