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

FS-Module 3 PPT

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
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

FS-Module 3 PPT

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
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

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 '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:
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 = models.Field(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 = models.Field(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 = models.Field(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
Models.py

from django.db import models

class Author(models.Model):
name =
models.CharField(max_length=100,verbose_name='Author_n
ame')
birth_date = models.DateField()
def __unicode__(self):
return u'%s %s' % (self.name,self.birth_date)

class Publisher(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name

class Book(models.Model):
authors = models.ManyToManyField(Author)
publication_date = models.DateField(blank=True,
null=True)
1. The author change-list page
The author change-list page after list_display

from django.contrib import admin


from theoryexample1.models import Author, Book,
Publisher
# Register your models here.
class AuthorAdmin(admin.ModelAdmin):
list_display = ('name','birth_date')
admin.site.register(Book)
admin.site.register(Publisher)
admin.site.register(Author,AuthorAdmin)
from django.contrib import admin
from theoryexample1.models import Author, Book,
Publisher
# Register your models here.
class AuthorAdmin(admin.ModelAdmin):
list_display = ('name','birth_date')
search_fields = ('name','birth_date') The author change-list page after search_fields
admin.site.register(Book)
admin.site.register(Publisher)
admin.site.register(Author,AuthorAdmin)
The author change-list page after list_filter

from django.contrib import admin


from theoryexample1.models import Author, Book,
Publisher
# Register your models here.
class AuthorAdmin(admin.ModelAdmin):
list_filter = ('birth_date',)
admin.site.register(Book)
admin.site.register(Publisher)
admin.site.register(Author,AuthorAdmin)
from django.contrib import admin
from theoryexample1.models import Author, Book,
Publisher The author change-list page after date_hierarchy
# Register your models here.
class AuthorAdmin(admin.ModelAdmin):
date_hierarchy = 'birth_date'
admin.site.register(Book)
admin.site.register(Publisher)
admin.site.register(Author,AuthorAdmin)
from django.contrib import admin
from theoryexample1.models import Author, Book,
Publisher
# Register your models here. The author change-list page after ordering
class AuthorAdmin(admin.ModelAdmin):
ordering = ('-birth_date',)
admin.site.register(Book)
admin.site.register(Publisher)
admin.site.register(Author,AuthorAdmin)
CUSTOMIZING EDIT FORMS

 The book edit form after adding filter_horizontal


 The book edit form after adding raw_id_fields.
from django.contrib import admin
from theoryexample1.models import Author, Book,
Publisher
# Register your models here.
class AuthorAdmin(admin.ModelAdmin): 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(admin.ModelAdmin):
filter_horizontal = ('authors',)
admin.site.register(Book, BookAdmin)
admin.site.register(Publisher)
admin.site.register(Author,AuthorAdmin)
The book edit form after adding raw_id_fields.

from django.contrib import admin


from theoryexample1.models import Author, Book,
Publisher
# Register your models here.
class AuthorAdmin(admin.ModelAdmin):
list_display = ('name','birth_date')
search_fields = ('name','birth_date’)
list_filter = ('birth_date',)
date_hierarchy = 'birth_date'
ordering = ('-birth_date',)
class BookAdmin(admin.ModelAdmin):
filter_horizontal = ('authors',)
raw_id_fields =('authors’,)
admin.site.register(Book, BookAdmin)
admin.site.register(Publisher)
admin.site.register(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(forms.Form):
# each field would be mapped as an input field in HTML
field_name = forms.Field(**options)
 Form.py
 from django import forms
 from .models import formModel
 # creating a form
 class InputForm(forms.Form):
 first_name = forms.CharField(max_length = 200)
 last_name = forms.CharField(max_length = 200)
 roll_number = forms.IntegerField( help_text = "Enter 6 digit roll number”)
 password = forms.CharField(widget = forms.PasswordInput())

 # create a ModelForm
 class InputForm(forms.ModelForm):
 # 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
Views.py
Home.html
 from django.shortcuts import render
<form action = "" method = "post">
 from django.shortcuts import render {% csrf_token %}
 from formexample.form import InputForm {{form }}
<input type="submit" value=Submit">
 # Create your views here. </form>
 def home_view(request):
 context ={}
 context['form']= InputForm()
 return render(request, "home.html", 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 forms.ValidationError("Name should start with s")

class StuForm(forms.Form):
name = forms.CharField(
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 Django.conf.urls.defaults import *

from labprg1 import views

Urlpatterns = Pattern(‘’,

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

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

)
from django.conf.urls.defaults import *

Urlpatterns = Pattern(‘labprg1.views’,
(‘^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 django.conf.urls.defaults import *

Urlpatterns = Pattern(‘labprg1.views’,
(‘^cdt/’,current_datetime),
('cts/<int:s>/<int:n>’,create_table_of_squares),
)

Urlpatterns += Pattern(‘labprg2.views’,
(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 django.conf.urls.defaults import *
from Django.conf import settings
Urlpatterns = Pattern(‘labprg1.views’,
(‘^cdt/’,current_datetime),
('cts/<int:s>/<int:n>’,create_table_of_squa
res),
)
if settings.DEBUG: In this example, the URL /debuginfo/ will only be available if
Urlpatterns += Pattern(‘labprg2.views’, 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
http://www.example.com/myapp/, 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

You might also like