0% found this document useful (0 votes)
9 views55 pages

Fullstack Development: Django Admin Guide

The document outlines the curriculum for a Fullstack Development course at SJB Institute of Technology, focusing on Chapters 6, 7, and 8. It covers topics such as activating and customizing Django admin interfaces, form processing, and URL configuration techniques. Each chapter includes specific learning objectives and practical coding examples to enhance student understanding of Django functionalities.

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

Fullstack Development: Django Admin Guide

The document outlines the curriculum for a Fullstack Development course at SJB Institute of Technology, focusing on Chapters 6, 7, and 8. It covers topics such as activating and customizing Django admin interfaces, form processing, and URL configuration techniques. Each chapter includes specific learning objectives and practical coding examples to enhance student understanding of Django functionalities.

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

SJB INSTITUTE OF TECHNOLOGY

Bangalor e -560060

INFORMATION SCIENCE & ENGINEERING

COURSE TITLE- FULLSTACK DEVELOPMENT(21CS62)


MODULE-3(CHAPTER-6,7,8)

Ranjitha J
Assistant Professor
Dept. of ISE
Bangalore.
COURSE OBJECTIVES
TEXT BOOKS
Textbooks:

Reference Books:
CHAPTER 6

In this session Students will learn


 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

In this session Students will learn


 Chapter 7
 Form Processing
 Creating Feedback forms
 Form submissions
 custom validation
 creating Model Forms
CHAPTER 8

In this session Students will learn


 Chapter 8
 URLConf Ticks
 Including Other URLConfs.
CHAPTER 6- ACTIVATING ADMIN INTERFACES

 First, make a few changes to your settings file:


1. Add '[Link]' 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 '[Link]', '[Link].
contenttypes', and '[Link]'. The Django admin site requires these
three packages.
3. Make sure MIDDLEWARE_CLASSES contains
'[Link]',
'[Link]', and '[Link].
[Link]'.
 Second, run python [Link] syncdb. This step will install the extra database tables that the
admin interface uses. The first time you run syncdb with '[Link]' in
INSTALLED_APPS, you’ll be asked about creating a superuser. If you don’t do this, you’ll need
to run python [Link] 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 [Link], remember). By default, the [Link]
generated by [Link] 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:
USING ADMIN INTERFACES
CUSTOMIZING ADMIN INTERFACES

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


 Custom ModelAdmin Classes(Customizing Change Lists, Customizing Edit Forms)
CUSTOMIZING FIELD LABELS

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 = [Link](verbose_name = "name")
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 = [Link](blank = True)
 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 = [Link](null = True)
CUSTOMIZING CHANGE LISTS

 The author change-list page


 The change-list page after list_display
 The change-list page after search_fields
 The change-list page after list_filter
 The change-list page after date_hierarchy
 The change-list page after ordering
[Link]

from [Link] import models

class Author([Link]):
name =
[Link](max_length=100,verbose_name='Author_n
ame')
birth_date = [Link]()
def __unicode__(self):
return u'%s %s' % ([Link],self.birth_date)

class Publisher([Link]):
name = [Link](max_length=100)
def __str__(self):
return [Link]

class Book([Link]):
authors = [Link](Author)
publication_date = [Link](blank=True,
null=True)
1. The author change-list page
The author change-list page after list_display

from [Link] import admin


from [Link] import Author, Book,
Publisher
# Register your models here.
class AuthorAdmin([Link]):
list_display = ('name','birth_date')
[Link](Book)
[Link](Publisher)
[Link](Author,AuthorAdmin)
from [Link] import admin
from [Link] import Author, Book,
Publisher
# Register your models here.
class AuthorAdmin([Link]):
list_display = ('name','birth_date')
search_fields = ('name','birth_date') The author change-list page after search_fields
[Link](Book)
[Link](Publisher)
[Link](Author,AuthorAdmin)
The author change-list page after list_filter

from [Link] import admin


from [Link] import Author, Book,
Publisher
# Register your models here.
class AuthorAdmin([Link]):
list_filter = ('birth_date',)
[Link](Book)
[Link](Publisher)
[Link](Author,AuthorAdmin)
from [Link] import admin
from [Link] import Author, Book,
Publisher The author change-list page after date_hierarchy
# Register your models here.
class AuthorAdmin([Link]):
date_hierarchy = 'birth_date'
[Link](Book)
[Link](Publisher)
[Link](Author,AuthorAdmin)
from [Link] import admin
from [Link] import Author, Book,
Publisher
# Register your models here. The author change-list page after ordering
class AuthorAdmin([Link]):
ordering = ('-birth_date',)
[Link](Book)
[Link](Publisher)
[Link](Author,AuthorAdmin)
CUSTOMIZING EDIT FORMS

 The book edit form after adding filter_horizontal


 The book edit form after adding raw_id_fields.
from [Link] import admin
from [Link] import Author, Book,
Publisher
# Register your models here.
class AuthorAdmin([Link]): The book edit form after adding filter_horizontal
list_display = ('name','birth_date')
search_fields = ('name','birth_date')
list_filter = ('birth_date',)
date_hierarchy = 'birth_date'
ordering = ('-birth_date',)
class BookAdmin([Link]):
filter_horizontal = ('authors',)
[Link](Book, BookAdmin)
[Link](Publisher)
[Link](Author,AuthorAdmin)
The book edit form after adding raw_id_fields.

from [Link] import admin


from [Link] import Author, Book,
Publisher
# Register your models here.
class AuthorAdmin([Link]):
list_display = ('name','birth_date')
search_fields = ('name','birth_date’)
list_filter = ('birth_date',)
date_hierarchy = 'birth_date'
ordering = ('-birth_date',)
class BookAdmin([Link]):
filter_horizontal = ('authors',)
raw_id_fields =('authors’,)
[Link](Book, BookAdmin)
[Link](Publisher)
[Link](Author,AuthorAdmin)
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.
CHAPTER 7
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:

 Preparing and restructuring data to make it ready for rendering.


 Creating HTML forms for the data.
 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([Link]):
# each field would be mapped as an input field in HTML
field_name = [Link](**options)
 [Link]
 from django import forms
 from .models import formModel
 # creating a form
 class InputForm([Link]):
 first_name = [Link](max_length = 200)
 last_name = [Link](max_length = 200)
 roll_number = [Link]( help_text = "Enter 6 digit roll number”)
 password = [Link](widget = [Link]())

 # create a ModelForm
 class InputForm([Link]):
 # specify the name of model to use
 class Meta:
 model = formModel
 fields = "__all__"

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
[Link]
[Link]
 from [Link] import render
<form action = "" method = "post">
 from [Link] import render {% csrf_token %}
 from [Link] import InputForm {{form }}
<input type="submit" value=Submit">
 # Create your views here. </form>
 def home_view(request):
 context ={}
 context['form']= InputForm()
 return render(request, "[Link]", context)
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

def start_with_s(value):
if value[0]!='s':
raise [Link]("Name should start with s")

class StuForm([Link]):
name = [Link](
validators =[start_with_s])
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
CHAPTER 8
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(‘/’).
Urlpatterns =[ slug – Matches any slug string, i.e. a string consisting of
path(‘^cdt/’,current_datetime), alphabets, digits, hyphen and under score.
path(‘cdt$/’,current_datetime),
path – Matches any non-empty string including the path
path(‘cdt/cdt1’,current_datetime),
separator(‘/’)
path('cts/<int:s>/<int:n>',create_table_of_squares),
uuid – Matches a UUID(universal unique identifier).
path('vc/<str:sentence>', vc),
path('display_string/<slug:sentence>', display_string),
]
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.

from [Link] import *

from labprg1 import views

Urlpatterns = Pattern(‘’,

(‘^cdt/’,views.current_datetime),

('cts/<int:s>/<int:n>’,views.create_table_of_squares),

)
from [Link] import *

Urlpatterns = Pattern(‘[Link]’,
(‘^cdt/’,current_datetime),
('cts/<int:s>/<int:n>’,create_table_of_squares),
)
2. Using Multiple View Prefixes
The advantage of the view prefix shortcut to remove duplication. Just add multiple
patterns() objects together.

from [Link] import *

Urlpatterns = Pattern(‘[Link]’,
(‘^cdt/’,current_datetime),
('cts/<int:s>/<int:n>’,create_table_of_squares),
)

Urlpatterns += Pattern(‘[Link]’,
(path('vc/<str:sentence>', vc),
)
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.
from [Link] import *
from [Link] import settings
Urlpatterns = Pattern(‘[Link]’,
(‘^cdt/’,current_datetime),
('cts/<int:s>/<int:n>’,create_table_of_squa
res),
)
if [Link]: In this example, the URL /debuginfo/ will only be available if
Urlpatterns += Pattern(‘[Link]’, your DEBUG setting is set to True.
(path('vc/<str:sentence>', vc),
)
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.
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 paramenters for a view’s argument.
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:
1 2

3
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
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
[Link] Django will try to match myapp/.
INCLUDING OTHER URLCONFS.

 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.
 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.
THANK YOU

Common questions

Powered by AI

Django's built-in form processing functions play the role of preparing and validating data for rendering HTML forms, handling submitted form data, and mapping form fields to HTML input fields. This allows developers to efficiently manage user data input, ensure correct format and security, and provide structured experiences for users when entering data into a web application .

To activate the Django admin interface, first, add 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', and 'django.contrib.sessions' to the INSTALLED_APPS setting in your settings file. Ensure MIDDLEWARE_CLASSES contains 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', and 'django.contrib.auth.middleware.AuthenticationMiddleware'. Next, run 'python manage.py syncdb' to install the extra database tables used by the admin interface. If a superuser isn’t created during this process, run 'python manage.py createsuperuser' to create an admin account. Finally, add the admin site to your URLconf by uncommenting the relevant lines in urls.py .

The Django admin site is particularly useful for inspecting data models to identify errors, managing acquired data from external sources like users or web crawlers, and creating quick and easy management applications for personal use rather than public deployment .

Custom validation in Django forms involves defining a validator function that checks whether a given input meets specific criteria. If the input is invalid, a ValidationError is raised. Custom validation is significant because it enhances data integrity and security by ensuring that all submitted data conform to the required formats or constraints before any processing or storage. This is critical due to the principle of 'never trust incoming data' to prevent invalid or harmful data from affecting the application .

Field labels in Django admin interfaces can be customized using the 'verbose_name' attribute in model fields. This attribute provides a human-readable name for the field, which Django uses if not explicitly set, by converting underscores to spaces in the field’s attribute name. Customizing field labels affects how fields appear within the admin interfaces, impacting user readability and comprehension .

Search filters in Django admin model views are added by specifying the 'search_fields' attribute in a ModelAdmin class. This attribute lists the fields that can be searched upon. For example, setting 'search_fields' to ('name','birth_date') means the admin interface will offer search capabilities based on the 'name' and 'birth_date' fields. This improves data presentation by allowing users to efficiently locate relevant records .

The URLconf matching and grouping algorithm ensures data integrity by using named groups in regular expressions to match parts of the URL. The algorithm prioritizes named arguments over non-named ones, using named groups to capture and pass URL segments as keyword arguments to view functions. This approach ensures URLs are properly parsed and matched, avoiding errors and ambiguities that could lead to incorrect data handling .

ModelForms offer the advantage of reducing redundant code by directly mapping a Django model to a form, which simplifies the process of building form-intensive, database-driven applications. The drawback is that it might limit customization or flexibility for forms that need to deviate significantly from the model they are based on, as the direct mapping assumes a close correspondence between form and model fields .

URLconfs manage the inclusion of other URLconfs using the include() function. When Django encounters an include(), it removes the portion of the URL matched up to that point and sends the remaining string to the included URLconf for further processing. Captured parameters work with the include(), and extra URLconf options can be passed to a normal view as a dictionary, which gets handed down to each entry in the included URLconf. This mechanism allows for a modular and organized handling of URLs .

Creating feedback forms in Django involves defining a Form class to specify necessary fields and any associated validation logic. Each field corresponds to a type of HTML input. Forms also require their structure for rendering through Django's form handling capabilities. Considerations include ensuring comprehensive data validation to maintain security, and providing clear and usable form errors when submission mistakes occur. The form's usability is enhanced by autofilling previously entered data to prevent loss on resubmission .

You might also like