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

Full Stack Module 3 Notes

Uploaded by

Vijaylaxmi Patil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Full Stack Module 3 Notes

Uploaded by

Vijaylaxmi Patil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

Full Stack Devlopment Module 3 Notes…

Module-03

Django Admin Interfaces and Model Forms

Activating Admin Interfaces


Update settings.py:
Add to INSTALLED_APPS:
• 'django.contrib.admin'
• 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'

Sync the database:

Run database synchronization:

 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:

Include the admin site in URL conf:

 Ensure the following import statement represent


from django.contrib import admin admin.auto
discover()

 Add the admin URL pattern


urlpatterns = patterns('',
# ...
(r'^admin/',include(admin.site.urls)),
# ...
)

Prepared By:Prof:Prasad Mathapati,Asst.Professor,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 manage.py run server.
 Visithttp://127.0.0.1:8000/admin/inyour 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 manage.py
create super user.

Figure:Django’sloginscreen

Prepared By:Prof:Prasad Mathapati,Asst.Professor,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,Asst.Professor,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,Asst.Professor,Department of CSE,SGBIT,Belagavi... Page4


Full Stack Devlopment Module 3 Notes…

Figure:-An Adding Records

Prepared By:Prof:Prasad Mathapati,Asst.Professor,Department of CSE,SGBIT,Belagavi... Page5


Full Stack Devlopment Module 3 Notes…

Input Validation:

 The admin interface validates input automatically.Errors 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 corner.This logs every
change made through the admin interface and allows you to review the change history.

Figure:-Anobjecthistory page

Prepared By:Prof:Prasad Mathapati,Asst.Professor,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 Author.email field's label to “e-mail”:

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.

Prepared By:Prof:Prasad Mathapati,Asst.Professor,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 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 Author Admin:

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',)

 Adding Date Hierarchy


 Add date_hierarchy to BookAdmin:

Class BookAdmin(admin.Model 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(admin.Model Admin):


list_display=('title','publisher','publication_date')
list_filter = ('publication_date',)
date_hierarchy='publication_date'
ordering = ('-publication_date',)

Prepared By:Prof:Prasad Mathapati,Asst.Professor,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(admin.ModelAdmin):
fields=('title','authors','publisher','publication_date')

 Excluding Fields
Class Book
Admin(admin.ModelAdmin): fields =
('title', 'authors', 'publisher')

 Many-to-Many Field Widgets


 Use filter_horizontal for Many To Many Fields:

Class BookAdmin(admin.ModelAdmin):
filter_horizontal = ('authors',)

 Alternatively,use filter_vertical:

Class BookAdmin(admin.ModelAdmin):
filter_vertical = ('authors',)

 Foreign Key Field Widgets


 Use raw_id_fields for Foreign Key fields:

Class BookAdmin(admin.ModelAdmin):
raw_id_fields = ('publisher',)

Prepared By:Prof:Prasad Mathapati,Asst.Professor,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 models.This 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 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.

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,Asst.Professor,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 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:

From django import forms

Class ContactForm(forms.Form):

name=forms.CharField(max_length=100)
email = forms.EmailField()
message=forms.CharField(widget=forms.Text area)

Prepared By:Prof:Prasad Mathapati,Asst.Professor,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
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,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 form.save().

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,Asst.Professor,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 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')

Prepared By:Prof:Prasad Mathapati,Asst.Professor,Department of CSE,SGBIT,Belagavi... Page13


Full Stack Devlopment Module 3 Notes…

Step2:Create the Feedback Template

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>

Prepared By:Prof:Prasad Mathapati,Asst.Professor,Department of CSE,SGBIT,Belagavi... Page14


Full Stack Devlopment Module 3 Notes…

{{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}}

Prepared By:Prof:Prasad Mathapati,Asst.Professor,Department of CSE,SGBIT,Belagavi... Page15


Full Stack Devlopment Module 3 Notes…

</div>

<div>

{{form.message.errors}}

{{form.message.label_tag}}

{{form.message}}

Prepared By:Prof:Prasad Mathapati,Asst.Professor,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,Asst.Professor,Department of CSE,SGBIT,Belagavi... Page17


Full Stack Devlopment Module 3 Notes…

Step4: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 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})

Step5: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
url patterns=[

# ... otherURL patterns

path('feedback/',views.feedback, name='feedback'),]

Step6:Run the Development Server

Star the Django development server and navigate to http://localhost:8000/feedback/in your web
browser. You should see the feedback form.

Prepared By:Prof:Prasad Mathapati,Asst.Professor,Department of CSE,SGBIT,Belagavi... Page18


Full Stack Devlopment Module 3 Notes…

Prepared By:Prof:Prasad Mathapati,Asst.Professor,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 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.

Prepared By:Prof:Prasad Mathapati,Asst.Professor,Department of CSE,SGBIT,Belagavi... Page20


Full Stack Devlopment Module 3 Notes…

# 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})

Prepared By:Prof:Prasad Mathapati,Asst.Professor,Department of CSE,SGBIT,Belagavi... Page21


Full Stack Devlopment Module 3 Notes…

<!--contact.html-->

<formmethod="post">

{%csrf_token %}

{{form.as_p}}

<inputtype="submit"value="Submit">

</form>

Prepared By:Prof:Prasad Mathapati,Asst.Professor,Department of CSE,SGBIT,Belagavi... Page22


Full Stack Devlopment Module 3 Notes…

CustomValidation

1. Define the Form Class:


 Use Django's forms.Form to define the fields of the
form from django import forms
classContactForm(forms.Form):
subject=forms.CharField(max_length=100)
email = forms.EmailField(required=False)
message=forms.CharField(widget=forms.Textarea)

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

Prepared By:Prof:Prasad Mathapati,Asst.Professor,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">
ul.errorlist {
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,Asst.Professor,Department of CSE,SGBIT,Belagavi... Page24


Full Stack Devlopment Module 3 Notes…

<body>

<h1>Contactus</h1>

{%if form.errors%}

<p style="color: red;">

Please correct the error{{ form.errors|pluralize}}below.

</p>

{%end if %}

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

Prepared By:Prof:Prasad Mathapati,Asst.Professor,Department of CSE,SGBIT,Belagavi... Page25


Full Stack Devlopment Module 3 Notes…

{{form.message}}

</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 form.message.errors%} errors{%end if %}">


{%if form.message.errors%}
<ul>
{%for error inform.message.errors%}
<li><strong>{{error }}</strong></li>
{%endfor %}
</ul>
{%end if %}
<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 thereare validation errors.
 Lists individual error messages in an unordered list.

Prepared By:Prof:Prasad Mathapati,Asst.Professor,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 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 Model Form


 Objective:Use forms.Model Form to create a form based on the model.

Example

from django import forms


from.modelsimport Contact
class ContactForm(forms.Model
Form): class Meta:
model =Contact
fields= ['subject','email', 'message']

Prepared By:Prof:Prasad Mathapati,Asst.Professor,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(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.Validation Error("Not enough words!")


return message

4. Usethe Form inViews


 Objective:Handle the form submission and validation with in Django views.

Example

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:

form=ContactForm()

return render(request,'contact_form.html',{'form':form})

Prepared By:Prof:Prasad Mathapati,Asst.Professor,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 form.errors%}

<p style="color: red;">

Please correct the error{{form.errors|pluralize}}below.

Prepared By:Prof:Prasad Mathapati,Asst.Professor,Department of CSE,SGBIT,Belagavi... Page29


Full Stack Devlopment Module 3 Notes…

</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}}

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

{{form.email}}

</div>

<divclass="field">

{{form.message.errors}}

<label for="id_message">Message:</label>

{{form.message}}

</div>

<input type="submit "value="Submit">

</form> </body> </html>

Prepared By:Prof:Prasad Mathapati,Asst.Professor,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 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.

URL Conf Ticks

Stream lining 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_date
time),
(r'^time/plus/(\d{1,2})/$', hours_ahead),
)

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

Advantage:Simplifies imports,but still requires module import.

Prepared By:Prof:Prasad Mathapati,Asst.Professor,Department of CSE,SGBIT,Belagavi... Page31


Full Stack Devlopment Module 3 Notes…

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 handle 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.
 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,Asst.Professor,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 django.conf.urls.defaults impor t


url patterns = patterns('',
(r'^weblog/', include('mysite.blog.urls')),
(r'^photos/',include('mysite.photos.urls')),
(r'^about/$', 'mysite.views.about'),
)

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 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 URL conf (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'),
)

Prepared By:Prof:Prasad Mathapati,Asst.Professor,Department of CSE,SGBIT,Belagavi... Page33


Full Stack Devlopment Module 3 Notes…

Prepared By:Prof:Prasad Mathapati,Asst.Professor,Department of CSE,SGBIT,Belagavi... Page34

You might also like