Full Stack Devlopment Module 3 Notes…
Module-03
Django Admin Interfaces and Model Forms
Activating Admin Interfaces
Update [Link]:
Add to INSTALLED_APPS:
• '[Link]'
• Ensure '[Link]', '[Link]', and '[Link]'
are included. Uncomment if previously commented.
Update MIDDLEWARE_CLASSES:
Ensure the following middlewares are included and uncommented:
• '[Link]'
• '[Link]'
• '[Link]'
Sync the database:
Run database synchronization:
Execute python [Link] sync db to install the necessary database tables for the
admin interface.
If not prompted to create a super user,run python [Link] create super user to create
an admin account.
Update [Link]:
Include the admin site in URL conf:
Ensure the following import statement represent
from [Link] import admin [Link]
discover()
Add the admin URL pattern
urlpatterns = patterns('',
# ...
(r'^admin/',include([Link])),
# ...
)
Prepared By:Prof:Prasad Mathapati,[Link],Department of CSE,SGBIT,Belagavi... Page1
Full Stack Devlopment Module 3 Notes…
Access the admin interface:
Run the development server and access the adminsite:
Start the server with python [Link] run server.
Visit[Link] web browser.
Using Admin Interfaces
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 [Link]
create super user.
Figure:Django’sloginscreen
Prepared By:Prof:Prasad Mathapati,[Link],Department of CSE,SGBIT,Belagavi... Page2
Full Stack Devlopment Module 3 Notes…
Admin Home Page:
After logging in,you'll see the admin home page listing all datatypes available for
editing. Initially, it includes only Groups and Users.
Figure:-The Django admin homepage
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).
Prepared By:Prof:Prasad Mathapati,[Link],Department of CSE,SGBIT,Belagavi... Page3
Full Stack Devlopment Module 3 Notes…
Figure:-The user change-list page
Adding and Deleting Records:
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.
Prepared By:Prof:Prasad Mathapati,[Link],Department of CSE,SGBIT,Belagavi... Page4
Full Stack Devlopment Module 3 Notes…
Figure:-An Adding Records
Prepared By:Prof:Prasad Mathapati,[Link],Department of CSE,SGBIT,Belagavi... Page5
Full Stack Devlopment Module 3 Notes…
Input Validation:
The admin interface validates input [Link] will be displayed if you leave
required fields blank or enter invalid data.
Figure:-An editform displaying errors
History:
When editing an object,a History link appears in the upper-right [Link] logs every
change made through the admin interface and allows you to review the change history.
Figure:-Anobjecthistory page
Prepared By:Prof:Prasad Mathapati,[Link],Department of CSE,SGBIT,Belagavi... Page6
Full Stack Devlopment Module 3 Notes…
Customizing Admin Interfaces
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:
To change the [Link] field's label to “e-mail”:
classAuthor([Link]):
first_name=[Link](max_length=30)
last_name = [Link](max_length=40)
email=[Link](blank=True,verbose_name='e-mail')
Alternatively,you can pass verbose_name as a positional argument:
class Author([Link]):
first_name = [Link](max_length=30)
last_name = [Link](max_length=40)
email=[Link]('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.
Prepared By:Prof:Prasad Mathapati,[Link],Department of CSE,SGBIT,Belagavi... Page7
Full Stack Devlopment Module 3 Notes…
Example:
To display first_name,last_name,and email for the Author model:
from [Link] import admin
from [Link] import Author
class AuthorAdmin([Link]):
list_display=('first_name','last_name','email')
[Link](Author, AuthorAdmin)
Adding a Search Bar
Add search_fields to your Author Admin:
class AuthorAdmin([Link]):
list_display=('first_name','last_name','email')
search_fields = ('first_name', 'last_name')
Adding Date Filters
Add list_filter to yourBookAdmin:
classBookAdmin([Link] Admin):
list_display=('title','publisher','publication_date')
list_filter = ('publication_date',)
Adding Date Hierarchy
Add date_hierarchy to BookAdmin:
Class BookAdmin([Link] Admin):
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([Link] Admin):
list_display=('title','publisher','publication_date')
list_filter = ('publication_date',)
date_hierarchy='publication_date'
ordering = ('-publication_date',)
Prepared By:Prof:Prasad Mathapati,[Link],Department of CSE,SGBIT,Belagavi... Page8
Full Stack Devlopment Module 3 Notes…
Customizing Edit Forms
Changing Field Order
Usethe fields optionto customize the order of fields:
Class BookAdmin([Link]):
fields=('title','authors','publisher','publication_date')
Excluding Fields
Class Book
Admin([Link]): fields =
('title', 'authors', 'publisher')
Many-to-Many Field Widgets
Use filter_horizontal for Many To Many Fields:
Class BookAdmin([Link]):
filter_horizontal = ('authors',)
Alternatively,use filter_vertical:
Class BookAdmin([Link]):
filter_vertical = ('authors',)
Foreign Key Field Widgets
Use raw_id_fields for Foreign Key fields:
Class BookAdmin([Link]):
raw_id_fields = ('publisher',)
Prepared By:Prof:Prasad Mathapati,[Link],Department of CSE,SGBIT,Belagavi... Page9
Full Stack Devlopment Module 3 Notes…
Reasons to use Admin Interfaces.
When and Why toUse the Admin Interface—and When Not To
When to Use the Admin Interface
1. For Non-Technica Users:
DataEntry:The admininterface is designed to enable non-technical users to easily
enter and manage data. For instance, reporters or content creators can input data
without needing to know any code.
Exampl e Wor kflow:
1. A reporter meets with a developr to describe the data.
2. The developer creates Django models based onthis data and sets up the
admin interface.
3. The reporter reviews the adminsite and suggests any changes to the fields.
4. The developer updates the models accordingly.
5. The reporter allowing the developer to focuson building views and
templates.
2. Inspecting Data Models:
Model Validation: The admin interface is useful for developers to enter dummy
data and validate their data [Link] process can help identify modeling errors
or inconsistencies early in development.
3. Managing Acquired Data:
External Data Sources: If your application relies on data from external sources
(such as user inputs or webcrawlers. It acts as a convenient tool for data
management, complementing your database's command-line utility.
When Not to Uset he Admin Interface
1. Public Interfaces:
Security and Usability:The admininterface is not designed for public [Link] 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.
3. Complex User Interfaces:
Customization Limits: The admin interface has limitations in terms of
customization and interactivity. If your project requires a highly customized user
interface with complex workflows, a custom-built solution will be more suitable.
Prepared By:Prof:Prasad Mathapati,[Link],Department of CSE,SGBIT,Belagavi... Page10
Full Stack Devlopment Module 3 Notes…
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 [Link] or the
[Link] 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:
From django import forms
Class ContactForm([Link]):
name=[Link](max_length=100)
email = [Link]()
message=[Link](widget=[Link] area)
Prepared By:Prof:Prasad Mathapati,[Link],Department of CSE,SGBIT,Belagavi... Page11
Full Stack Devlopment Module 3 Notes…
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}}.
4. Handling Form Data
In the view function,you can access the submitted form data using the
[Link] or [Link] dictionaries.
To bind the form data to the form instance,use form=MyForm([Link])or
form = MyForm([Link]).
After binding the data,youcan checkif the formis validusing form.is_valid().
5. Validating Form Data
Django provide sbuilt-invalidation for common fieldtypes(e.g.,EmailField,
IntegerField, etc.).
You can define custom validation rules by overridingtheclean_fieldname() method
in your form class.
For complex validation rules, you can override the clean() method in your
formclass.
6. 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 instance s
using [Link]().
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.
Prepared By:Prof:Prasad Mathapati,[Link],Department of CSE,SGBIT,Belagavi... Page12
Full Stack Devlopment Module 3 Notes…
8. Form Handling inViews
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.
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.
Creating Feedback forms
Step1:Create the Feedback Form
Create a new file [Link] in your Django app directory, and add the following code
from django import forms
Class FeedbackForm([Link]):
name=[Link](max_length=100,label='YourName')
email = [Link](label='Your Email')
subject=[Link](max_length=200, label='Subject')
message=[Link](widget=[Link],label='Your Feedback')
Prepared By:Prof:Prasad Mathapati,[Link],Department of CSE,SGBIT,Belagavi... Page13
Full Stack Devlopment Module 3 Notes…
Step2:Create the Feedback Template
Create a new file [Link] 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>
{{[Link]}}
{{[Link].label_tag}}
{{[Link]}}
</div>
<div>
{{[Link]}}
{{[Link].label_tag}}
{{[Link]}}
</div>
<div>
Prepared By:Prof:Prasad Mathapati,[Link],Department of CSE,SGBIT,Belagavi... Page14
Full Stack Devlopment Module 3 Notes…
{{[Link]}}
{{[Link].label_tag}}
{{[Link]}}
</div>
<div>
{{[Link]}}
{{[Link].label_tag}}
{{[Link]}}
{%csrf_token %}
{{form.non_field_errors}}
<div>
{{[Link]}}
{{[Link].label_tag}}
{{[Link]}}
</div>
<div>
{{[Link]}}
{{[Link].label_tag}}
{{[Link]}}
</div>
<div>
{{[Link]}}
{{[Link].label_tag}}
{{[Link]}}
Prepared By:Prof:Prasad Mathapati,[Link],Department of CSE,SGBIT,Belagavi... Page15
Full Stack Devlopment Module 3 Notes…
</div>
<div>
{{[Link]}}
{{[Link].label_tag}}
{{[Link]}}
Prepared By:Prof:Prasad Mathapati,[Link],Department of CSE,SGBIT,Belagavi... Page16
Full Stack Devlopment Module 3 Notes…
</div>
<inputtype="submit"value="SubmitFeedback">
</form>
</body>
</html>
Step3:Create the Success Template
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>
Prepared By:Prof:Prasad Mathapati,[Link],Department of CSE,SGBIT,Belagavi... Page17
Full Stack Devlopment Module 3 Notes…
Step4:Create the View Function
Open your Django app's [Link] file and add the following code:
from [Link] import render
[Link] import Feedback Form
def feedback(request):
if [Link]=='POST':
form=FeedbackForm([Link])
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,'[Link]',{'form':form})
Step5:Add URL Pattern
Open your Django app's [Link] file and add the following URL pattern:
from [Link] import path
[Link] views
url patterns=[
# ... otherURL patterns
path('feedback/',[Link], name='feedback'),]
Step6:Run the Development Server
Star the Django development server and navigate to [Link] your web
browser. You should see the feedback form.
Prepared By:Prof:Prasad Mathapati,[Link],Department of CSE,SGBIT,Belagavi... Page18
Full Stack Devlopment Module 3 Notes…
Prepared By:Prof:Prasad Mathapati,[Link],Department of CSE,SGBIT,Belagavi... Page19
Full Stack Devlopment Module 3 Notes…
Form submissions
1. Create a Form Class: Define a form class that inherits from [Link] or
[Link]. 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([Link]) or form = Your Model
Form([Link]).
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.
Prepared By:Prof:Prasad Mathapati,[Link],Department of CSE,SGBIT,Belagavi... Page20
Full Stack Devlopment Module 3 Notes…
# [Link]
fromdjangoimportforms
classContactForm([Link]):
name=[Link](max_length=100)
email = [Link]()
message=[Link](widget=[Link])
# [Link]
[Link],redirect
from .forms import ContactForm
def contact(request):
[Link]=='POST':
form=ContactForm([Link]) 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,'[Link]',{'form': form})
Prepared By:Prof:Prasad Mathapati,[Link],Department of CSE,SGBIT,Belagavi... Page21
Full Stack Devlopment Module 3 Notes…
<!--[Link]-->
<formmethod="post">
{%csrf_token %}
{{form.as_p}}
<inputtype="submit"value="Submit">
</form>
Prepared By:Prof:Prasad Mathapati,[Link],Department of CSE,SGBIT,Belagavi... Page22
Full Stack Devlopment Module 3 Notes…
CustomValidation
1. Define the Form Class:
Use Django's [Link] to define the fields of the
form from django import forms
classContactForm([Link]):
subject=[Link](max_length=100)
email = [Link](required=False)
message=[Link](widget=[Link])
2. Add a CustomValidation Method:
Create a clean_message() method to enforce the minimum word count.
defclean_message(self):
message=self.cleaned_data['message'] num_words
= len([Link]())
ifnum_words <4:
[Link]("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.
Prepared By:Prof:Prasad Mathapati,[Link],Department of CSE,SGBIT,Belagavi... Page23
Full Stack Devlopment Module 3 Notes…
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
<stylet ype="text/css">
[Link] {
margin:0;
padding:0;
}
.error listli{
background-color:red;
color: white;
display: block;
font-size: 10px;
margin: 0 0 3px;
padding:4px5px;
}
</style>
2. Custom HTML Template:
Instead of using{{form.as_table}},manually render the form fields for finer
control.
<html>
<head>
<title>Contactus</title>
</head>
Prepared By:Prof:Prasad Mathapati,[Link],Department of CSE,SGBIT,Belagavi... Page24
Full Stack Devlopment Module 3 Notes…
<body>
<h1>Contactus</h1>
{%if [Link]%}
<p style="color: red;">
Please correct the error{{ [Link]|pluralize}}below.
</p>
{%end if %}
<form action="" method="post">
<div class="field">
{{[Link]}}
<label for="id_subject">Subject:</label>
{{[Link]}}
</div>
<div class="field">
{{[Link]}}
<label for="id_email">Your e-mail address:</label>
{{[Link]}}
</div>
<div class="field">
{{[Link]}}
<label for="id_message">Message:</label>
Prepared By:Prof:Prasad Mathapati,[Link],Department of CSE,SGBIT,Belagavi... Page25
Full Stack Devlopment Module 3 Notes…
{{[Link]}}
</div>
<input type="submit" value="Submit">
</form>
</body>
</html>
3. Advanced Error Handling in Template:
Conditionally add classes and display error messages
<div class="field{%if [Link]%} errors{%end if %}">
{%if [Link]%}
<ul>
{%for error [Link]%}
<li><strong>{{error }}</strong></li>
{%endfor %}
</ul>
{%end if %}
<label for="id_message">Message:</label>
{{[Link]}}
</div>
This template:
Checks for errors and displays them if present.
Adds an errors class to the<div> if thereare validation errors.
Lists individual error messages in an unordered list.
Prepared By:Prof:Prasad Mathapati,[Link],Department of CSE,SGBIT,Belagavi... Page26
Full Stack Devlopment Module 3 Notes…
Creating Model Forms
1. Define the Model
Objective:Create a Django model to represent the data structure.
Example
From [Link] import models
Class Contact([Link]):
subject=[Link](max_length=100)
email = [Link](blank=True)
message = [Link]()
def str(self):
return [Link]
2. Create the Model Form
Objective:Use [Link] Form to create a form based on the model.
Example
from django import forms
[Link] Contact
class ContactForm([Link]
Form): class Meta:
model =Contact
fields= ['subject','email', 'message']
Prepared By:Prof:Prasad Mathapati,[Link],Department of CSE,SGBIT,Belagavi... Page27
Full Stack Devlopment Module 3 Notes…
3. Add Custom Validation (Optional)
Objective:Add custom validation logic specific to form fields.
Example:
Class ContacForm([Link]):
class Meta:
model =Contact
fields= ['subject','email', 'message']
def clean_message(self):
message=self.cleaned_data['message']
num_words = len([Link]())
if num_words <4:
raise [Link] Error("Not enough words!")
return message
4. Usethe Form inViews
Objective:Handle the form submission and validation with in Django views.
Example
From [Link] import render,redirect
from .forms import ContactForm
def contact_view(request):
if [Link]=='POST':
form=ContactForm([Link]) if
form.is_valid():
[Link]()
return redirect('success')# Redirect to a success page or another view
else:
form=ContactForm()
return render(request,'contact_form.html',{'form':form})
Prepared By:Prof:Prasad Mathapati,[Link],Department of CSE,SGBIT,Belagavi... Page28
Full Stack Devlopment Module 3 Notes…
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 [Link]%}
<p style="color: red;">
Please correct the error{{[Link]|pluralize}}below.
Prepared By:Prof:Prasad Mathapati,[Link],Department of CSE,SGBIT,Belagavi... Page29
Full Stack Devlopment Module 3 Notes…
</p>
{%end if %}
<form method="post">
{%csrf_token %}
<div class="field">
{{[Link]}}
<label for="id_subject">Subject:</label>
{{[Link]}}
</div>
<div class="field">
{{[Link]}}
<label for="id_email">Your email address:</label>
{{[Link]}}
</div>
<divclass="field">
{{[Link]}}
<label for="id_message">Message:</label>
{{[Link]}}
</div>
<input type="submit "value="Submit">
</form> </body> </html>
Prepared By:Prof:Prasad Mathapati,[Link],Department of CSE,SGBIT,Belagavi... Page30
Full Stack Devlopment Module 3 Notes…
1. Define the Model: Establish your data structure with a Django model.
2. Create the Mode lForm:Generate a form using [Link] 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.
URL Conf Ticks
Stream lining Function Imports
1. Traditional Method :Direct Import of View Functions
Example:
From [Link] import *
From [Link] import hello,current_datetime,hours_ahead
urlpatterns = patterns('',
(r'^hello/$',
hello),(r'^time/$',current_date
time),
(r'^time/plus/(\d{1,2})/$', hours_ahead),
)
2. Importing the Views Module
Example
From [Link] import*
from mysite import views
urlpatterns = patterns('',
(r'^hello/$',[Link]),
(r'^time/$', views.current_datetime),
(r'^time/plus/(d{1,2})/$',views.hours_ahead),
)
Advantage:Simplifies imports,but still requires module import.
Prepared By:Prof:Prasad Mathapati,[Link],Department of CSE,SGBIT,Belagavi... Page31
Full Stack Devlopment Module 3 Notes…
3. Using Strings to Specify View Functions
Example
From [Link] import*
urlpatterns = patterns('',
(r'^hello/$','[Link]'),
(r'^time/$', '[Link].current_datetime'),
(r'^time/plus/(d{1,2})/$','[Link].hours_ahead'),
)
Advantage:No need to import view functions; Django handle imports automatically.
4. Factoring Out a Common View Prefix
Example:
From [Link] import*
urlpatterns = patterns('[Link]',
(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.
More readable and manage able 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 with in the same URL conf
depending on personal coding style and project needs.
Prepared By:Prof:Prasad Mathapati,[Link],Department of CSE,SGBIT,Belagavi... Page32
Full Stack Devlopment Module 3 Notes…
Including Other URL Confs
Purpose and Benefit
1. Purpose:Allows for modul a rorganization of URL patterns by "including" URL conf
modules from different parts of the project.
2. Benefit: Enhances re usability and maintain ability across multiple Django-based sites.
Basic Usage
Example URL conf that includes other URL confs.
From [Link] impor t
url patterns = patterns('',
(r'^weblog/', include('[Link]')),
(r'^photos/',include('[Link]')),
(r'^about/$', '[Link]'),
)
Important Considerations
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
theURL and sends the remaining string to the included URL conf.
Main URL conf:
From [Link] import*
urlpatterns = patterns('',
(r'^weblog/', include('[Link]')),
(r'^photos/',include('[Link]')),
(r'^about/$', '[Link]'),
)
Included URL conf ([Link]):
From [Link] import*
urlpatterns = patterns('',
(r'^(\d\d\d\d)/$', '[Link].year_detail'),
(r'^(\d\d\d\d)/(\d\d)/$','[Link].month_detail'),
)
Prepared By:Prof:Prasad Mathapati,[Link],Department of CSE,SGBIT,Belagavi... Page33
Full Stack Devlopment Module 3 Notes…
Prepared By:Prof:Prasad Mathapati,[Link],Department of CSE,SGBIT,Belagavi... Page34