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

MODULE 3- FSD-Notes

The document provides detailed notes on Django's admin interfaces, form processing, and URL configuration. It covers activating and customizing admin interfaces, creating and validating forms, and managing URL patterns effectively. Key topics include customizing field labels, form submissions, and the use of URLConf for routing in Django applications.

Uploaded by

Ranjitha J
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)
9 views

MODULE 3- FSD-Notes

The document provides detailed notes on Django's admin interfaces, form processing, and URL configuration. It covers activating and customizing admin interfaces, creating and validating forms, and managing URL patterns effectively. Key topics include customizing field labels, form submissions, and the use of URLConf for routing in Django applications.

Uploaded by

Ranjitha J
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/ 19

SJB Institute of Technology, Bangalore – 60

BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

Name of the Course: FSD (18CS745)


NOTES – Module-3

Chapter 6
• Activating Admin Interfaces
• Using Admin Interfaces
• Customizing Admin Interfaces - Customizing Field Labels, Custom
ModelAdmin Classes(Customizing Change Lists, Customizing Edit
Forms)
• Reasons to use Admin Interfaces -
Chapter 7
• Form Processing
• Creating Feedback forms
• Form submissions
• Custom validation
• Creating Model Forms

Chapter 8
• URLConf Ticks
• Including Other URLConfs.
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

CHAPTER 6

ACTIVATING ADMIN INTERFACES

First, make a few changes to your settings file:


1. Add 'django.contrib.admin' to the INSTALLED_APPS setting. (The order of INSTALLED_ APPS
doesn’t matter, but we like to keep things alphabetical so it’s easy for a human to read.)
2. Make sure INSTALLED_APPS contains 'django.contrib.auth', 'django.contrib. contenttypes', and
'django.contrib.sessions'. The Django admin site requires these three packages.
3. Make sure MIDDLEWARE_CLASSES contains
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware', and 'django.contrib.
auth.middleware.AuthenticationMiddleware'.

Second, run python manage.py syncdb. This step will install the extra database tables that the admin
interface uses. The first time you run syncdb with 'django.contrib.auth' in INSTALLED_APPS, you’ll be
asked about creating a superuser. If you don’t do this, you’ll need to run python manage.py
createsuperuser separately to create an admin user account; otherwise you won’t be able to log in to the
admin site.
Third, add the admin site to your URLconf (in urls.py, remember). By default, the urls.py generated by
django-admin.py startproject contains commented-out code for the Django admin, and all you have to do
is uncomment it. For the record, here are the bits you need to make sure are in there:
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

USING ADMIN INTERFACES


Logging In:

• Visit the admin site and log in with the superuser credentials you created.

• If you can't log in, ensure you’ve created a superuser by running python manage.py
createsuperuser.

Admin Home Page:

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

Data Management:

• Each data type in the admin site has a change list and an edit form.

• Change List: Displays all records of a data type, similar to a SELECT * FROM <table> SQL query.
• Edit Form: Allows you to add, change, or delete individual records.

Adding and Deleting Records:

• Add Record: Click Add in the appropriate column on the admin home page to access an

empty edit form for creating a new record.

• Delete Record: Click the Delete button at the bottom left of an edit form. Confirm the
deletion on the subsequent page, which may list dependent objects to be deleted as well.
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

CUSTOMIZING ADMIN INTERFACES

1. Customizing Field Labels - Model level change(Verbose_name, blank, null)


2. Custom ModelAdmin Classes(Customizing Change Lists, Customizing Edit Forms)
3. Customizing Edit forms

Customizing Field Labels


1. Model level change- Verbose_name
One can also add more built-in field validations for applying or removing certain constraints on a
particular field. verbose_name is a human-readable name for the field. If the verbose name isn’t
given, Django will automatically create it using the field’s attribute name, converting underscores to
spaces. This attribute in general changes the field name in admin interface.

Syntax : field_name = models.Field(verbose_name = "name")

2. Model level change- blank


One can also add more built-in field validations for applying or removing certain constraints on a
particular field. blank=True will make the field accept blank values. It simply means that field can be
empty.
Syntax: field_name = models.Field(blank = True)
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

3. Model level change Null

One can also add more built-in field validations for applying or removing certain constraints on a
particular field. null=True will make the field accept NULL values. Blank values for Django field
types such as DateTimeField or ForeignKey will be stored as NULL in the database.

Syntax: field_name = models.Field(null = True)

Custom ModelAdmin Classes

1. The author change-list page


2. The change-list page after list_display
3. The change-list page after search_fields
4. The change-list page after list_filter
5. The change-list page after date_hierarchy
6. The change-list page after ordering
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

1. The author change-list page

In admin page it a created a page called the authors page.

2. The change-list page after list_display

It displays the attribute fields – Author_Name, Birthdate.


SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

3. The change-list page after search_fields

4. The change-list page after list_filter


SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

5. The change-list page after date_hierarchy

6. The change-list page after ordering


SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

Customizing Edit forms

1. The book edit form after adding filter_horizontal


2. The book edit form after adding raw_id_fields.

1. The book edit form after adding filter_horizontal

2. The book edit form after adding raw_id_fields.


SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

REASONS TO USE ADMIN INTERFACES

The admin site is useful in a few other cases


• Inspecting data models- Once defined a few models, it can be quite useful to call them up in the
admin interface. In some cases, this might reveal data-modeling mistakes or other problems with
your models.
• Managing acquired data- For applications that rely on data coming from external sources (e.g.,
users or Web crawlers), the admin site gives you an easy way to inspect or edit this data. You can
think of it as a less powerful but more convenient version of your database’s command-line
utility.
• Quick and dirty management apps- You can use the admin site to build a very lightweight data-
management app—say, to keep track of expenses. If you’re just building something for your own
needs, not for public consumption, the admin site can take you a long way.
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

CHAPTER 7

FORM PROCESSING
The behavior of a hypothetical 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.
• 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.
• When one creates a Form class, the most important part is defining the fields of the form. Each field
has custom validation logic, along with a few other hooks.
• Forms are used for taking input from the user in some manner and using that information for logical
operations on databases. For example, Registering a user by taking input such as his name, email,
password, etc.
• Django maps the fields defined in Django forms into HTML input fields. Django handles three
distinct parts of the work involved in forms:
o Preparing and restructuring data to make it ready for rendering.
o Creating HTML forms for the data.
o Receiving and processing submitted forms and data from the client.

CREATING FEEDBACK FORMS

Creating a form in Django is completely similar to creating a model, one needs to specify what fields would
exist in the form and of what type. For example, to input, a registration form one might need First Name
(CharField), Roll Number (IntegerField), and so on.

Syntax:

from django import forms


class FormName(forms.Form):
# each field would be mapped as an input field in HTML
field_name = forms.Field(**options)
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

FORM SUBMISSIONS

Talking about forms, In HTML, a form is a collection of elements inside <form>…</form> that allow a
visitor to do things like entering text, select options, manipulate objects or controls, and so on, and then
send that information back to the server. Basically, it is a collection of data for processing it for any purpose
including saving it in the database or fetching data from the database. Django supports all types of HTML
forms and rendering data from them to a view for processing using various logical operations.
Render HTML Forms (GET & POST) in Django.
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

CUSTOM VALIDATION

A validator is a callable that takes a value and raises a ValidationError if it doesn’t meet criteria. Validators
can be useful for re-using validation logic between different types of fields.
Django Custom Field Validation Explanation for Django Forms

CREATING MODEL FORMS

Django ModelForm is a class that is used to directly convert a model into a Django form. If you’re building
a database-driven app, chances are you’ll have forms that map closely to Django models. For example, a
User Registration model and form would have the same quality and quantity of model fields and form
fields. So instead of creating a redundant code to first create a form and then map it to the model in a view.
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

CHAPTER 8

URLConf TICKS

1. Streamlining Function Import


2. Using Multiple View Prefixes
3. Special-Casing URLs in Debug Mode
4. Using Named Groups
5. Understanding the Matching/Grouping Algorithm
6. Passing Extra Options to View Functions
7. Using Default View Arguments
8. Special-Casing Views
9. Capturing Text in URLs
10. Determining What the URLconf Searches Against

There’s nothing “special” about URLconfs — like anything else in Django, they’re just Python code.
The following path convertor types are available in Django

int – Matches zero or any positive integer.


str – Matches any non-empty string, excluding the path separator(‘/’).
slug – Matches any slug string, i.e. a string consisting of alphabets, digits, hyphen and under score.
path – Matches any non-empty string including the path separator(‘/’)
uuid – Matches a UUID(universal unique identifier).
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

1. Streamlining Function Import


Each entry in the URLconf includes its associated view function, passed directly as a function object.
This means it’s necessary to import the view functions at the top of the module. But as a Django
application grows in complexity, its URLconf grows, too, and keeping those imports can be tedious to
manage.

2. Using Multiple View Prefixes


The advantage of the view prefix shortcut to remove duplication. Just add multiple patterns() objects
together.

3. Special-Casing URLs in Debug Mode


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.
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

4. Using Named Groups - Keyword Arguments vs. Positional Arguments


A Python function can be called using keyword arguments or positional arguments — and, in some
cases, both at the same time. In a keyword argument call, you specify the names of the arguments along
with the values you’re passing. In a positional argument call, you simply pass the arguments without
explicitly specifying which argument matches which value; the association is implicit in the arguments’
order.

The syntax for named regular expression groups is (?Ppattern), where name is the name of the group and
pattern is some pattern to match.
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

5. Understanding the Matching/Grouping Algorithm


The algorithm the URLconf parser follows, with respect to named groups vs. non-named groups in a
regular expression:
• If there are any named arguments, it will use those, ignoring non-named arguments.
• Otherwise, it will pass all non-named arguments as positional arguments.
• In both cases, it will pass any extra options as keyword arguments. See the next section for
more information.

6. Passing Extra Options to View Functions


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:

7. Using Default View Arguments


Is to specify default parameters for a view’s argument.
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

8. 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:

9. Capturing Text in URLs

Note that int() itself raises a ValueError when you pass it a string that is not composed solely of digits,
but we’re avoiding that error in this case because the regular expression in our URLconf has ensured
that only strings containing digits are passed to the view function.

10. 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/.
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

INCLUDING OTHER URLConfs.


1. How Captured Parameters Work with include()

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.

2. How Extra URLconf Options Work with include()


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.

Prepared By,
Ranjitha J
Assistant
ProfessorDept, of
ISE
SJB Institute of Technology

You might also like