0% found this document useful (0 votes)
7 views

Module 3

Uploaded by

Zuha Kareem
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Module 3

Uploaded by

Zuha Kareem
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

MODULE-3, FSD

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.

Key aspects of Django’s admin interface:


1. Automatic CRUD Operations:
 After defining models in Django, the admin interface automatically generates an
interface for managing those models.
 We can perform operations such as create, read, update, and delete instances of
your models directly from the admin interface without writing any additional code.

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

3. Integration with Django's Authentication System:


 Django's admin interface integrates seamlessly with Django's built-in
authentication system.
 This means you can control access to different parts of the admin interface based
on user permissions and groups.
 You can define which users have access to the admin interface and what actions
they can perform.

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.

5. Development and Debugging:


 During development, the admin interface is a valuable tool for quickly inspecting
and managing your application's data.
 It's particularly useful for debugging and verifying that your models and data are
set up correctly.
Overall, Django's admin interface is a time-saving tool that simplifies the process of
managing data in your Django application. It's highly customizable, integrates
seamlessly with Django's authentication system and provides a convenient way to
interact with your application's data during development.

Activating Admin Interfaces


Update settings.py:
Add 'django.contrib.admin' to INSTALLED_APPS
• Ensure 'django.contrib.auth', 'django.contrib.contenttypes', and
'django.contrib.sessions' are included. Uncomment if previously commented

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

Sync the database:


Run database synchronization:
• Execute python manage.py syncdb to install the necessary database tables for
the admin interface.
If not prompted ,To access the admin interface, you need to create a user account
with superuser privileges

• to create a superuser, run python manage.py createsuperuser to create an


admin account.

Update urls.py:
Include the admin site in URLconf:
• Ensure the following import statements are present
from django.contrib import admin
admin.autodiscover()

Add the admin URL pattern


urlpatterns = patterns('',
# ...
(r'^admin/', include(admin.site.urls)),
# ...
)
Access the admin interface:
• Run the development server and access the admin site:
• Start the server with python manage.py runserver.
• Visit http://127.0.0.1:8000/admin/ in your web browser.

Using Admin Interfaces


Logging In:
• Visit the admin site and log in with the superuser credentials you created.
• If you can't log in, ensure you’ve created a superuser by running python
manage.py createsuperuser.

3
MODULE-3, FSD

Admin Home Page:


• After logging in, you'll see the admin home page listing all data types available for
editing. Initially, it includes only Groups and Users.

Django Admin Home Page

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).

The User Change-List page


5
MODULE-3, FSD

Adding and Deleting Records:


• Add Record: Click Add in the appropriate column on the admin home page to
access an
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 subsequent page, which may list dependent objects to be deleted as
well.

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

Edit form displaying errors

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.

Object history page

Using Admin Interface:


The Django admin interface serves several key purposes in web development:
Rapid Prototyping and Development: During the early stages of development, the
admin interface allows developers to quickly prototype and develop features
without building custom user interfaces. It provides a ready-made interface for
managing data models, which speeds up development time.
Data Management: The admin interface is a powerful tool for managing data in
Django applications. It allows administrators to perform CRUD (Create, Read,
Update, Delete) operations on database records without writing custom views or
forms. This includes creating, editing, and deleting records, as well as searching and
filtering data.
Content Management: For content-heavy websites such as blogs, news sites, or e-
commerce platforms, the admin interface simplifies content management tasks.
Content editors can use the admin interface to create and update articles, products,

7
MODULE-3, FSD

or other types of content without needing technical knowledge or access to the


codebase.
User Management: Django's admin interface integrates with the authentication
system, allowing administrators to manage user accounts, permissions, and groups.
This includes creating new user accounts, assigning permissions, resetting
passwords, and managing user sessions.

Customization and Extensibility: While the admin interface provides a lot of


functionality out of the box, it's also highly customizable and extensible. Develop…
and dashboards for administrative tasks, reporting, of monitoring Developers can
create custom admin views to display analytics, generate reports, or perform other
administrative tasks.

Customize the Admin Interface:


While the default admin interface is functional. You can customize the admin
interface by creating admin site classes, customizing model admin classes, or
overriding admin templates. In the Django admin site, each field’s label is derived
from its model field name. To customize a label, use the verbose_name attribute in
your model field definitions.
1. First create a new Django project and app
django-admin startproject myadmin
cd myadmin
python manage.py adminapp
2. Define a Model
Define a model in your app’s mode;s.py file ex:#myadmin/models.py
from django.db import models

class Product(models. Model):

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

from.models import Product

admin.site.register(Product)

4. Customize the Model Admin Class

Customize the appearance ModelAdmin class: of the Product model in the admin
interface by creating a cu

#myapp/admin.py

from django.contrib import admin


from.models import Product
class ProductAdmin(admin.ModelAdmin):
list_display = ('name', 'price') # Display these fields in the list view
admin.site.register(Product, ProductAdmin)

5. Run Migrations and Create a Superuser


Apply migrations to create database tables for the models, and create a superuser to
access admin interface:
python manage.py makemigrations
python manage.py migrate

python manage.py createsuperuser


9
MODULE-3, FSD

Step 6: Customize Templates (Optional)


Optionally, customize admin templates to change the appearance and layout of the
admin interface. You can override templates by creating files with the same name in
your project's templates/admin directory.

7. Customizing Admin Site-wide Settings (Optional)


You can customize the overall appearance and behavior of the admin interface by
subclassing AdminSite and modifying attributes such as site_header, site_title, and
index_title.

8. Start the Development Server


Start the Django development server:
python manage.py runserver

9. Access the Admin Interfac


Open a web browser and navigate to http://127.0.0.1:8000/admin. Log in with the
superuser credentials you created earlier.

10. Interact with the Admin Interface


You can now interact with the admin interface to manage your Product objects. You
can add, view, update, and delete products directly through the admin interface.
You've customized the admin interface in Django by altering the appearance and
behavior of the built-in admin site to suit your project's requirements

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

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


• ModelAdmin classes allow customization of how models are displayed and
managed in the admin interface.
• Customizing Change Lists
• 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:

To display first_name, last_name, and email for the Author model:


from django.contrib import admin
from mysite.books.models import Author
class AuthorAdmin(admin.ModelAdmin):
list_display = ('first_name', 'last_name', 'email')
admin.site.register(Author, AuthorAdmin)
• Adding a Search Bar
• Add search_fields to your AuthorAdmin:
class AuthorAdmin(admin.ModelAdmin):
list_display = ('first_name', 'last_name', 'email')
search_fields = ('first_name', 'last_name')

11
MODULE-3, FSD

• Adding Date Filters


• Add list_filter to your BookAdmin:
class BookAdmin(admin.ModelAdmin):
list_display = ('title', 'publisher', 'publication_date')
list_filter = ('publication_date',)
• Adding Date Hierarchy
• Add date_hierarchy to BookAdmin:
class BookAdmin(admin.ModelAdmin):
list_display = ('title', 'publisher', 'publication_date')
list_filter = ('publication_date',)
date_hierarchy = 'publication_date'
• Changing Default Ordering
• Use ordering to set the default order of records:
class BookAdmin(admin.ModelAdmin):
list_display = ('title', 'publisher', 'publication_date')
list_filter = ('publication_date',)
date_hierarchy = 'publication_date'
ordering = ('-publication_date',)
Customizing Edit Forms
• Changing Field Order
• Use the fields option to customize the order of fields:
class BookAdmin(admin.ModelAdmin):
fields = ('title', 'authors', 'publisher', 'publication_date')
• Excluding Fields
• Exclude fields by omitting them from the fields list:
class BookAdmin(admin.ModelAdmin):
fields = ('title', 'authors', 'publisher')

12
MODULE-3, FSD

• Many-to-Many Field Widgets


• Use filter_horizontal for ManyToManyFields:
class BookAdmin(admin.ModelAdmin):
filter_horizontal = ('authors',)
• Alternatively, use filter_vertical:
class BookAdmin(admin.ModelAdmin):
filter_vertical = ('authors',)
• ForeignKey Field Widgets
• Use raw_id_fields for ForeignKey fields:
class BookAdmin(admin.ModelAdmin):
raw_id_fields = ('publisher',)

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.

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. Each form field is represented by a class attribute, and the type of the
field is determined by the corresponding Django Field class.
Here's an example of a simple form:
#myapp/forms.py
from django import forms
class MyForm(forms.Form):
name = forms.CharField(max_length=100)
email=forms.EmailField()
message= forms.CharField(widget=forms.Textarea)

13
MODULE-3, FSD

Step 2: Create a View


Define a view function or class-based view to handle form processing logic. In the
view, you'll handle form submission, validate the data, and perform actions based
on the submitted data. 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 }}
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):
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
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):
<1--myapp/templates/my_template.html -->
<form method="post">
{% csrf_token %}
{{ form.as_p}}
<button type="submit">Submit</button>
</form>

14
MODULE-3, FSD

Step 4: Configure URLs


Map the view to a URL pattern in your Django project's urls.py file:
#myproject/urls.py
from django.urls import path
from myapp import views
urlpatterns = [
path('my-form/', viewsmy_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. You can then perform actions based on this data, such as
saving it to a database.
In the view function, you can access the submitted form data using the
request.POST or request.GET dictionaries.
• To bind the form data to the form instance, use form = MyForm(request.POST)
or form = MyForm(request.GET).
• After binding the data, you can check if the form is valid using form.is_valid().

Step 6: Displaying Validation Errors


If the form data is invalid, Django automatically renders the form with validation
errors. You can access these errors in the template using form.errors or display
them alongside form fields using form.field.errors.

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.

Step 7: Saving Form Data


• For forms not based on models, you can access the cleaned data using
form.cleaned_data and handle it as needed.
• For model-based forms (ModelForm), you can create or update model instances
using form.save()

Step 8: Form Widgets


• Django provides a wide range of built-in form widgets (e.g., TextInput, Textarea,
CheckboxInput, Select, etc.) for rendering form fields.
• You can customize the rendering of form fields by specifying the widget
argument when defining the field.

Step 9: Form Handling in Views


• In the view function, you typically create a form instance, bind the data to it, and
perform validation and data handling.
• After successful form submission, you can redirect the user to another page or
render a success message

Step 10:Adding CSRF Token


Django provides built-in protection against Cross-Site Request Forgery (CSRF)
attacks by including a CSRF token in forms.
• You need to include the {% csrf_token %} template tag in your form template to
generate the CSRF token.
Always include a CSRF token in your forms to protect against CSRF attacks. Use
the (% csrf_token %) template tag…

Step 11: Form Inheritance


• Django supports form inheritance, allowing you to create reusable form
components and extend or override them as needed.
• You can use the Meta class to specify form-level attributes, such as labels,
help_texts, and error_messages

16
MODULE-3, FSD

Step 12 : Redirecting or Rendering Response


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 validation errors.
You've now implemented form processing in Django, allowing users to submit
data through a form, validating it, and performing actions based on the submitted
data

Creating Feedback forms


Step 1: Create the Feedback Form
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='Your Name')
email = forms.EmailField(label='Your Email')
subject = forms.CharField(max_length=200, label='Subject')
message = forms.CharField(widget=forms.Textarea, label='Your Feedback')

Step 2: Create the Feedback Template


Create a new file feedback.html in your Django app's templates directory, and add
the following
code:
<!DOCTYPE html>
<html>
<head>
<title>Feedback Form</title>
</head>
<body>
<h1>Feedback Form</h1>

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

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>
<h1>Thank you for your feedback!</h1>
<p>We appreciate your comments and will review them shortly.</p>
</body>
</html>
Step 4: Create the View Function
Open your Django app's views.py file and add the following code:
from django.shortcuts import render
from .forms import FeedbackForm
def feedback(request):
if request.method == 'POST':
form = FeedbackForm(request.POST)
if form.is_valid():
# Process the feedback data
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:

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>

3. Advanced Error Handling in Template:


• Conditionally add classes and display error messages
<div class="field{% if form.message.errors %} errors{% endif %}">
{% if form.message.errors %}
<ul>
{% for error in form.message.errors %}
<li><strong>{{ error }}</strong></li>
{% endfor %}
</ul>
{% endif %}
<label for="id_message">Message:</label>
{{ form.message }}
</div>
This template:
• Checks for errors and displays them if present.
• Adds an errors class to the <div> if there are validation errors.
• Lists individual error messages in an unordered list.

Creating Model Forms


Creating a Model form allow you to easily create a HTML formsbased
on your django model definitions. These form handle data validation,
saving, and updating of model instances,

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

2. Create the ModelForm Create a model form class in your app’s


form.py file. This form class should inherit from
django.forms.Modelform and specify the model it’s based on
Example
from django import forms
• Objective: Use forms.ModelForm to create a form based on the model.
from .models import Contact
class ContactForm(forms.ModelForm):
class Meta:
model = Contact
fields = ['subject', 'email', 'message']

3. Add Custom Validation (Optional)


Objective: Add custom validation logic specific to form fields.
27
MODULE-3, FSD

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

4. Use the Form in Views


Example
• Objective: Handle the form submission and validation within Django
views.
from django.shortcuts import render, redirect
from .forms import ContactForm
def contact_view(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
form.save()
return redirect('success') # Redirect to a success page or another view
else:

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

<label for="id_email">Your email address:</label>


{{ form.email }}
</div>
<div class="field">
{{ form.message.errors }}
<label for="id_message">Message:</label>
{{ form.message }}
</div>
<input type="submit" value="Submit">
</form></body></html>
6. Configure URLs:
Map a view to a URL pattern in your Django projects urls.py file. This
view will handle rendering the form and processing form submission.
#myproject/url.py
from django.urls import path
from myapp import views
urlpattern=[
path(‘my-form/’,’views.my_form_view, name=’my-form’),]

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

5. Create the Template: Design an HTML template to display and


manage the form interface.

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

• More readable and manageable for projects with views in


multiple modules.
• Advantages of the Function Object Approach:
• Facilitates easy wrapping of view functions.
• More "Pythonic," aligning with Python traditions of passing
functions as objects.
• Flexibility:
• Both approaches are valid and can be mixed within the same
URLconf depending on personal coding style and project needs.

Including Other URLConfs


Purpose and Benefit
1. Purpose: Allows for modular organization of URL patterns by
"including" URLconf
modules from different parts of the project.
2. Benefit: Enhances reusability and maintainability across multiple
Django-based sites.
Basic Usage
• Example URLconf that includes other URLconfs.
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'),
)
Important Considerations

33
MODULE-3, FSD

1. No End-of-String Match Character: Regular expressions pointing to


an include() should
not have a $ but should include a trailing slash.
2. URL Stripping: When Django encounters include(), it removes the
matched part of the
URL and sends the remaining string to the included URLconf.

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

• Remaining URL: 2007/.


• Result: Matches r'^(\d\d\d\d)/$' in mysite.blog.urls.
2. Request: /weblog//2007/ (with two slashes)
• First URLconf: r'^weblog/' matches.
• Action: Strips weblog/.
• Remaining URL: /2007/ (with leading slash).
• Result: Does not match any patterns in mysite.blog.urls.
3. Request: /about/
• First URLconf: Matches r'^about/$'.
• Result: Maps to mysite.views.about view.
Mixing Patterns
• Flexibility: You can mix include() patterns with non-include()
patterns within the same
URLconf.

**********************************************************

35

You might also like