module-3
module-3
MODULE –3
DJANGO ADMIN INTERFACES AND MODEL FORMS
• Activating Admin Interfaces
• Using Admin Interfaces
• Customizing Admin Interfaces
• Reasons to use Admin Interfaces.
• Form Processing
• Creating Feedback forms
• Form submissions
• Custom validation
• Creating Model Forms
• URLConf Ticks
• Including Other URLConfs.
Course Objectives:
Illustrate Models, Views and Templates with their connectivity in Django for full stack web development.
Session – 17
1. ACTIVATING ADMIN INTERFACES
• For a certain class of Web sites, an admin interface is an essential part of the
infrastructure.
• This is aWeb-based interface, limited to trusted site administrators, that enables the
addition, editing, and deletion of site content.
• Create a superuser by using the following command: python manage.py createsuperuser
Questions
1. What is a superuser?
2. How to create superuser?
Session –18
2. USING ADMIN INTERFACES
• The admin interface is designed to be used by nontechnical users, and as such it should be
pretty self-explanatory.
• Open http://127.0.0.1:8000/admin in browser.
• Same username and password need to be entered in the admin page which you have
created during creation of superuser. Then login to the page.
• In admin.py, we have to include the class for admin.
• In urls.py, we can include the contents which need to be visible inside the admin page
• Example:
• Links to add and change objects lead to two pages we refer to as object change lists
andedit forms.
• Edit forms are used to modify existing objects and create new ones.
• Admin interface also handles input validation for you.
• Try leaving a required field blank or putting an invalid time into a time field, and you’ll
see those errors when you try to save.
• When you edit an existing object, you’ll notice a History button in the upper-right
cornerof the window.
• Every change made through the admin interface is logged, and you can examine this log
by clicking the History button
• “Normal” admin users—that is, active, nonsuperuser staff members—are granted access
that depends on a set of assigned permissions.
• Each object editable through the admin interface has three permissions:
o a create permission,
o an edit permission, and
o a delete permission.
• Assigning permissions to a user grants the user access to do what is described by those
permissions.
• You can also assign users to groups. A group is simply a set of permissions to apply to all
members of that group. Groups are useful for granting identical permissions to a large
number of users.
Questions
• What is admin interface?
• What are the 3 permissions of admin interface?
Session – 19
3. CUSTOMIZING ADMIN INTERFACES
• You can customize the way the admin interface looks and behaves. The list_display
option controls which columns appear in the change list table.
• Ex: list_display = ('student_name','student_usn','student_sem')
• The list_filter option creates the filtering bar on the right side of the list.
• Ex: list_filter = ('student_name','student_usn')
• The ordering option controls the order in which the objects are presented in the admin
interface.
• It’s simply a list of fields by which to order the results; prefixing a field with a minus sign
reverses the given order
• Ex: ordering=('student_name',)
• Finally, the search_fields option creates a field that allows text searches.
• It allowssearches by the title field
• Ex: search_fields = ('student_name',)
• However, beyond the obvious data entry tasks, we find the admin interface useful in a
fewother cases:
o Inspecting data models: The first thing we do when we’ve defined a new model
is to callit up in the admin interface and enter some dummy data. This is usually
when we findany data modeling mistakes; having a graphical interface to a model
quickly revealsproblems.
o Managing acquired data: There’s little actual data entry associated with a site
likehttp://chicagocrime.org, since most of the data comes from an automated
source.However, when problems with the automatically acquired data crop up, it’s
useful to beable to go in and edit that data easily
Questions
• What is lsit_display, list_filterand ordering?
• Why to use admin interface?
Session-20
5. FORM PROCESSING
• At the heart of this system of components is Django’s Form class. In much the same way
that a Django model describes the logical structure of an object, its behavior, and the way
its parts are represented to us, a Form class describes a form and determines how it works
and appears.
• A ModelForm maps a model class’s fields to HTML form <input> elements via a Form;
• The Django's Form class gives a logical representation of an HTML form, defines how it
should behave and how it appears in the HTML.
• Sample html forms
<form action="/action_page" method=“post”>
<label for="fname">First name:</label><br>
<input type="text" id="fname" value="John"><br><br>
<input type="submit" value="Submit">
</form>
• If the user has made any mistakes, the form should be redisplayed with detailed,
informative error messages. The original data should be prefilled, to save the user from
having to reenter everything.
• The form should continue to redisplay until all of the fields have been correctly filled.
• Django Forms Flow
In contact.html
• There are a number of other field types available, and you can write your own if they
don’t cover your needs.
• The form object itself knows how to do a number of useful things.
o It can validate a collection of data,
o it can generate its own HTML “widgets,”
o it can construct a set of useful error messages and,
o if we’re feeling lazy, it can even draw the entire form for us.
• The most interesting line here is {{ form.as_table }}. form is our ContactForm instance,as
passed to render_to_response. as_table is a method on that object that renders the form
asa sequence of table rows (as_ul and as_p can also be used)
• The forms framework separates out the presentation logic for each field into a set
ofwidgets.
• Each field type has a default widget, but you can easily override the default, or providea
custom widget of your own.
• Our form is currently using a <input type="submit"> widget for the message field.
• A form instance can be in one of two states: bound or unbound.
Questions
• What is GET and POST data?
• What are forms?
• What are the benefits of using forms?
Session-21
7. FORM SUBMISSIONS
• Once the user has filled the form to the point that it passes our validation rules, we need
to do something useful with the data.
• If we want to construct and send an email containing the user’s feedback. We’ll use
Django’s email package to do this.
• First, though, we need to tell if the data is indeed valid, and if it is, we need access to the
validated data.
• The forms framework does more than just validate the data; it also converts it into Python
types.
• Our contact form only deals with strings, but if we were to use an IntegerField or
DateTimeField, the forms framework would ensure that we got back a Python integer or
datetime object, respectively.
• To tell whether a form is bound to valid data, call the is_valid() method:
form = ContactForm(request.POST)
if form.is_valid():
# Process form data
• Now we need access to the data. We could pull it straight out of request.POST, but if we
did, we’d miss out on the type conversions performed by the forms framework.
• Instead, we use form.clean_data to access the validated data:
if form.is_valid():
topic = form.clean_data['topic']
message = form.clean_data['message']
sender = form.clean_data['sender']
• Finally, we need to record the user’s feedback. We can do that using the send_mail
function:
from django.core.mail import send_mail
# ...
send_mail(
'Feedback from your site, topic: %s' % topic,
message, sender,
['[email protected]']
)
• The send_mail function has four required arguments: the email subject, the email
body,the “from” address, and a list of recipient addresses. send_mail is a convenient
wrapper aroundDjango’s EmailMessage class, which provides advanced features such as
attachments, multipartemails, and full control over email headers.
• Having sent the feedback email, we’ll redirect our user to a static confirmation page.
• If a user selects Refresh on a page that was displayed by a POST request, that request will
be repeated.
• This can often lead to undesired behavior, such as a duplicate record being added to the
database.
• Redirect after POST is a useful pattern that can help avoid this scenario: after a successful
POST has been processed, redirect the user to another page rather than returning HTML
directly.
8. CUSTOM VALIDATION
• To enforce a new validation policy for a feedback form in Django, where the message
field must contain at least four words, a custom validation method is added to the form
class. Here's a summary of the process:
• Custom Validation Method: Add a `clean_message` method to the form class.
class ContactForm(forms.Form):
topic = forms.ChoiceField(choices=TOPIC_CHOICES)
message = forms.CharField(widget=forms.Textarea())
sender = forms.EmailField(required=False)
def clean_message(self):
• While it’s convenient to have our form’s HTML generated for us, in many cases the
default rendering won’t be right for our application. {{ form.as_table }} and friends are
useful shortcuts while we develop our application, but everything about the way a form is
displayed can be overridden, mostly within the template itself.
• Form Fields and errors
1. Topic Field
{form.topic} Renders the input element for the topic field and Displays any validation
errors related to the topic field.
2. Message Field
{{ form.message }}: Renders the input element for the message field and displays any
validation errors related to the message field.
3. Sender Field
{{ form.sender }}: Renders the input element for the sender field and displays any
validation errors related to the sender field.
• We can also treat form.message.errors as a Boolean or even iterate over it as a list, for
example:
Questions
• How to tell whether a form is bound to valid data?
• What is Validation Logic?
Session - 22
9. CREATING MODEL FORMS
• Most of the times our user inputs are very close to our models, after all the input data is
stored in models.
• Django provides us with Model Forms, the forms that can be built from models.
• Building a form from a model is really easy. We just need to extend the
django.forms.ModelForm class, specify the model (that we want to built the form from)
in the Meta class and specify the fields to include
• As a Django application grows in complexity, its URLconf grows, too, and keeping those
imports can be tedious to manage.
• (For each new view function, you have to remember to import it, and the import
statement tends to get overly long if you use this approach.)
• It’s possible to avoid this tedium by importing the views module itself.
Streamlining string Imports
Django offers another way of specifying the view function for a particular pattern in the
URLconf: you can pass a string containing the module name and function name rather
than the function object itself.
A further shortcut you can take when using the string technique is to factor out a common
“view prefix.”
In our URLconf example, each of the view strings starts with ‘app1.views', which is
redundant to type.
We can factor out that common prefix and pass it as the first argument to patterns(), like
this:
The first line imports all objects from the django.conf.urls.defaults module, including a
function called patterns.
The second line calls the function patterns() and saves the result into a variable called
urlpatterns.
The patterns() function gets passed only a single argument—the empty string.
The r means that is a Python raw string.
The caret character (^) and dollar sign character ($) are important.
The caret means “require that the pattern matches the start of the string,” and the dollar
sign means “require that the pattern matches the end of the string.”
That means we want to allow either one- or two-digit numbers—in regular expression
syntax, that translates into \d{1,2}:
Advantages of the string approach are as follows:
It’s more compact, because it doesn’t require you to import the view functions.
It results in more readable and manageable URLconfs if your view functions are
spread across several different Python modules.
Advantages of the function object approach are as follows:
It allows for easy “wrapping” of view functions. It’s more “Pythonic”—that is, it’s
more in line with Python traditions, such as passing functions as objects.
Questions
• How create model forms? How to avoid redundant views?
• What are the advantages of the string approach?
• What are the advantages of the function object approach?
Session - 23
In more advanced usage, it’s possible to use named regular expression groups to capture
URL bits and pass them as keyword arguments to a view.
In Python regular expressions, the syntax for named regular expression groups is
(?P<name>pattern), where name is the name of the group and pattern is some pattern to
match.
This accomplishes exactly the same thing as the previous example, with one subtle
difference: the captured values are passed to view functions as keyword arguments rather
than positional arguments.
At first, you may think to remove the redundancy by using the same view for both
URLs, putting parentheses around the URL to capture it, and checking the URL
within the view to determine the template, like so:
The problem with that solution, though, is that it couples your URLs to your code.
If you decide to rename /foo/ to /fooey/, you’ll have to remember to change the view
code.
You can apply this same philosophy to your Django views by using extra URLconf
parameters.
With this in mind, you can start making higher-level abstractions of your views.
Instead of thinking to yourself, “This view displays a list of Event objects,” and “That
view displays a list of BlogEntry objects,”
realize they’re both specific cases of “A view that displays a list of objects, where the
type of object is variable.”
We passed the model classes directly, as the model parameter. The dictionary of extra
URLconf options can pass any type of Python object—not just strings.
The model.objects.all() line is an example of duck typing. Note the code doesn’t know
what type of object model is; the only requirement is that model have an objects
attribute, which in turn has an all() method.
We used model.__name__.lower() in determining the template name. Every Python
class has a __name__ attribute that returns the class name.
In a slight difference between this example and the previous example, we passed the
generic variable name object_list to the template. We could easily change this
variable name to be blogentry_list or event_list.
• Giving a View Configuration Options :
If you’re distributing a Django application, chances are that your users will want some
degree of configuration.
In this case, it’s a good idea to add hooks to your views for any configuration options you
think people may want to change.
You can use extra URLconf parameters for this purpose.
A common bit of an application to make configurable is the template name:
Here, both URL patterns point to the same view—views.page—but the first pattern
doesn’t capture anything from the URL.
If the first pattern matches, the page() function will use its default argument for num,
"1". If the second pattern matches, page() will use whatever num value was captured
by the regular expression.
This example makes a slight improvement to the example in the “Giving aView
Configuration Options” section by providing a default value for template_name:
• Special-Casing Views :
Sometimes you’ll have a pattern in your URLconf that handles a large set of URLs,
but you’ll need to special-case one of them.
In this case, take advantage of the linear way a URLconf is processed and put the
special case first.
For example, the “add an object” pages in Django’s admin site are represented by this
URLconf line:
However, the “add” page for a user object (/auth/user/add/) is a special case—it
doesn’t display all of the form fields, it displays two password fields, and so forth.
As a more elegant solution, we can take advantage of the fact that URLconfs are
processed in order from top to bottom:
• the year argument to views.year_archive() will be a string, not an integer, even though
\d{4} will only match integer strings.
A common error is to attempt to create a datetime.date object with string values
instead of integer values:
This does not include GET or POST parameters, or the domain name. It also does not include
the leading slash, because every URL has a leading slash.
The request method (e.g., POST, GET, HEAD) is not taken into account when traversing the
URLconf.
Questions
• How to make the views generic?
• What is the default view argument?
Session - 24
11. INCLUDING OTHER URLCONFS
If you intend your code to be used on multiple Django-based sites, you should consider
arranging your URLconfs in such a way that allows for “including.”
At any point, your URLconf can “include” other URLconf modules. This essentially “roots”
a set of URLs below other ones.
There’s an important gotcha here: the regular expressions in this example that point to
an include() do not have a $ (end-of-string match character) but do include a trailing
slash.
Whenever Django encounters include(), it chops off whatever part of the URL
matched up to that point and sends the remaining string to the included URLconf for
further processing.
An included URLconf receives any captured parameters from parent URLconfs, for
example :
In this example, the captured username variable is passed to the included URLconf
and, hence, to every view function within that URLconf.
Note that the captured parameters will always be passed to every line in the included
URLconf, regardless of whether the line’s view actually accepts those parameters as
valid.
Similarly, you can pass extra URLconf options to include(), just as you can pass extra
URLconf options to a normal view—as a dictionary.
When you do this, each line in the included URLconf will be passed the extra options.
For example, the following two URLconf sets are functionally identical.
Set 1
Set 2
Questions
• How Captured Parameters Work with include() :
• How Extra URLconf Options Work with include ?