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

module-3

This document covers Django's admin interfaces and model forms, detailing how to activate, use, and customize admin interfaces for full stack web development. It also discusses form processing, including creating feedback forms, handling form submissions, and implementing custom validation. The course objectives and outcomes emphasize the understanding of models, views, and templates connectivity in Django.
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)
0 views

module-3

This document covers Django's admin interfaces and model forms, detailing how to activate, use, and customize admin interfaces for full stack web development. It also discusses form processing, including creating feedback forms, handling form submissions, and implementing custom validation. The course objectives and outcomes emphasize the understanding of models, views, and templates connectivity in Django.
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/ 30

FULLSTACK DEVELOPMENT (21CS62)

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.

Course Outcomes (COs):


Experiment with the role of Template Inheritance and Generic views for developing full stack web
applications.

MRS. SHILPA B, DEPT. OF ISE, CEC 1


FULLSTACK DEVELOPMENT (21CS62)

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.

MRS. SHILPA B, DEPT. OF ISE, CEC 2


FULLSTACK DEVELOPMENT (21CS62)

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

MRS. SHILPA B, DEPT. OF ISE, CEC 3


FULLSTACK DEVELOPMENT (21CS62)

• 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

Users,Groups, and Permissions


• Since you’re logged in as a superuser, you have access to create, edit, and delete any
object.
• However, the admin interface has a user permissions system that you can use to give
other users access only to the portions of the interface that they need
• You edit these users and permissions through the admin interface just like any other
object.
• The link to the User and Group models is there on the admin index along with all the
objects you’ve defined yourself.
• User objects have the standard username, password, e-mail, and real name fields you
might expect, along with a set of fields that define what the user is allowed to do in the
admin interface.
• First, there’s a set of three flags:
o The “is active” flag controls whether the user is active at all. If this flag is off, the
user has no access to any URLs that require login.
o The “is staff” flag controls whether the user is allowed to log in to the admin
interface (i.e., whether that user is considered a “staff member” in your
organization). this flag differentiates between public users and administrators.
o The “is superuser” flag gives the user full, unfettered access to every item in the
admin interface; regular permissions are ignored

MRS. SHILPA B, DEPT. OF ISE, CEC 4


FULLSTACK DEVELOPMENT (21CS62)

• “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')

MRS. SHILPA B, DEPT. OF ISE, CEC 5


FULLSTACK DEVELOPMENT (21CS62)

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

4. REASONS TO USE ADMIN INTERFACES.


• Primary Use:
o Ideal for content producers collaborating with developers.
o Simplifies data entry and management tasks significantly.

MRS. SHILPA B, DEPT. OF ISE, CEC 6


FULLSTACK DEVELOPMENT (21CS62)

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

MRS. SHILPA B, DEPT. OF ISE, CEC 7


FULLSTACK DEVELOPMENT (21CS62)

• What’s GET and POST data?


• GET and POST are the two methods that browsers use to send data to a server.
• Most of the time, you’ll see them in HTML form tags:
<form action="/books/search/" method="get">
• This instructs the browser to submit the form data to the URL /books/search/ using the
GET method.

MRS. SHILPA B, DEPT. OF ISE, CEC 8


FULLSTACK DEVELOPMENT (21CS62)

• The “Perfect Form”


• It should ask the user for some information, obviously. Accessibility and usability matter
here, so smart use of the HTML <label> element and useful contextual help are
important.
• The submitted data should be subjected to extensive validation. The golden rule of Web
application security is “never trust incoming data,” so validation is essential.

MRS. SHILPA B, DEPT. OF ISE, CEC 9


FULLSTACK DEVELOPMENT (21CS62)

• 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

6. CREATING FEEDBACK FORMS


• The best way to build a site that people love is to listen to their feedback.
• When your site has millions of users, this may be a reasonable strategy.
• When you’re trying to build up an audience, though, you should actively encourage
feedback at every opportunity
• Example:

• Our ContactForm consists of three fields:


o a topic, which is a choice among three options;
o a message, which is a character field; and
o a sender, which is an email field and is optional (because even anonymous
feedback can be useful).

MRS. SHILPA B, DEPT. OF ISE, CEC 10


FULLSTACK DEVELOPMENT (21CS62)

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.

MRS. SHILPA B, DEPT. OF ISE, CEC 11


FULLSTACK DEVELOPMENT (21CS62)

o A bound instance isattached to a dictionary (or dictionary-like object) and knows


how to validate and redisplaythe data from it.
o An unbound form has no data associated with it and simply knows how todisplay
itself.

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

MRS. SHILPA B, DEPT. OF ISE, CEC 12


FULLSTACK DEVELOPMENT (21CS62)

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

MRS. SHILPA B, DEPT. OF ISE, CEC 13


FULLSTACK DEVELOPMENT (21CS62)

message = self.clean_data.get('message', '')


num_words = len(message.split())
if num_words< 4:
raise forms.ValidationError("Not enough words!")
return message
• Validation Logic
o The `clean_message` method retrieves the message field data from `clean_data`.
o It counts the number of words using `len()` and `split()`.
o If the word count is less than four, a `ValidationError` is raised with an
appropriate message.
o The method returns the cleaned message to ensure the value is not lost or altered
incorrectly.
• Integration
o The method is called after the default field validator.
o It processes the partially validated field data.
o If the validation fails, an error message is displayed to the user.
• This approach allows enforcing a word count validation directly within the form class,
making it easy to customize and maintain.
• A Custom Look and Feel
• The quickest way to customize the form’s presentation is with CSS. The list of errors in
particular could do with some visual enhancement, and the <ul> has a class attribute of
errorlist for that exact purpose.
• Example:

MRS. SHILPA B, DEPT. OF ISE, CEC 14


FULLSTACK DEVELOPMENT (21CS62)

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

MRS. SHILPA B, DEPT. OF ISE, CEC 15


FULLSTACK DEVELOPMENT (21CS62)

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

10. URLCONF TICKS


• Streamlining Function Imports

MRS. SHILPA B, DEPT. OF ISE, CEC 16


FULLSTACK DEVELOPMENT (21CS62)

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

MRS. SHILPA B, DEPT. OF ISE, CEC 17


FULLSTACK DEVELOPMENT (21CS62)

 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

 Using Multiple View Prefixes


 In practice, if you use the string technique, you’ll probably end up mixing views to the
point where the views in your URLconf won’t have a common prefix.
 However, you can still take advantage of the view prefix shortcut to remove duplication.
 Just add multiple patterns() objects together, like this:

MRS. SHILPA B, DEPT. OF ISE, CEC 18


FULLSTACK DEVELOPMENT (21CS62)

 Special-Casing URLs in Debug Mode


 Speaking of constructing urlpatterns dynamically, you might want to take advantage of
this technique to alter your URLconf’s behavior while in Django’s debug mode.
 To do this, just check the value of the DEBUG setting at runtime, like so:

 Using Named Groups :


 In all of our URLconf examples so far, we’ve used simple, non-named regular expression
groups—that is, we put parentheses around parts of the URL we wanted to capture, and
Django passes that captured text to the view function as a positional argument.

MRS. SHILPA B, DEPT. OF ISE, CEC 19


FULLSTACK DEVELOPMENT (21CS62)

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

• Passing Extra Options to View Functions :


 Sometimes you’ll find yourself writing view functions that are quite similar, with only
a few small differences.
 For example, say you have two views whose contents are identical except for the
template they use:

MRS. SHILPA B, DEPT. OF ISE, CEC 20


FULLSTACK DEVELOPMENT (21CS62)

 We’re repeating ourselves in this code, and that’s inelegant.

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

MRS. SHILPA B, DEPT. OF ISE, CEC 21


FULLSTACK DEVELOPMENT (21CS62)

 The elegant solution involves an optional URLconf parameter.

 Each pattern in a URLconf may include a third item: a dictionary of keyword


arguments to pass to the view function

• Making a View Generic :


 It’s good programming practice to “factor out” commonalities in code. For example,
with these two Python functions:

 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,”

MRS. SHILPA B, DEPT. OF ISE, CEC 22


FULLSTACK DEVELOPMENT (21CS62)

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

MRS. SHILPA B, DEPT. OF ISE, CEC 23


FULLSTACK DEVELOPMENT (21CS62)

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

Using Default View Arguments :


 Another convenient trick is to specify default parameters for a view’s arguments. This
tells the view which value to use for a parameter by default if none is specified.

 Here, both URL patterns point to the same view—views.page—but the first pattern
doesn’t capture anything from the URL.

MRS. SHILPA B, DEPT. OF ISE, CEC 24


FULLSTACK DEVELOPMENT (21CS62)

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

 It’s common to use this technique in conjunction with configuration options, as


explained earlier.

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

 This matches URLs such as /myblog/entries/add/ and /auth/groups/add/.

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

 We could solve this problem by special-casing in the view, like so:

MRS. SHILPA B, DEPT. OF ISE, CEC 25


FULLSTACK DEVELOPMENT (21CS62)

 As a more elegant solution, we can take advantage of the fact that URLconfs are
processed in order from top to bottom:

• Capturing Text in URLs :


 Each captured argument is sent to the view as a plain Python string, regardless of
what sort of match the regular expression makes.

 For example, in the following URLconf line:

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

MRS. SHILPA B, DEPT. OF ISE, CEC 26


FULLSTACK DEVELOPMENT (21CS62)

• Determining What the URLconf Searches Against :


 When a request comes in, Django tries to match the URLconf patterns against the requested
URL, as a normal Python string (not as a Unicode string).

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

 For example, in a request to http://www.example.com/myapp/, Django will try to match


myapp/.

 In a request to http://www.example.com/myapp/?page=3, Django will try to match myapp/.

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

MRS. SHILPA B, DEPT. OF ISE, CEC 27


FULLSTACK DEVELOPMENT (21CS62)

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.

 For example, this URLconf includes other URLconfs:

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

MRS. SHILPA B, DEPT. OF ISE, CEC 28


FULLSTACK DEVELOPMENT (21CS62)

How Captured Parameters Work with include() :

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

How Extra URLconf Options Work with include() :

 Similarly, you can pass extra URLconf options to include(), just as you can pass extra
URLconf options to a normal view—as a dictionary.

MRS. SHILPA B, DEPT. OF ISE, CEC 29


FULLSTACK DEVELOPMENT (21CS62)

 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

Set 1

Set 2

Questions
• How Captured Parameters Work with include() :
• How Extra URLconf Options Work with include ?

MRS. SHILPA B, DEPT. OF ISE, CEC 30

You might also like