FS-Module 3 PPT
FS-Module 3 PPT
Bangalor e -560060
Ranjitha J
Assistant Professor
Dept. of ISE
Bangalore.
COURSE OBJECTIVES
TEXT BOOKS
Textbooks:
Reference Books:
CHAPTER 6
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
Django maps the fields defined in Django forms into HTML input fields. Django handles three distinct parts of
the work involved in 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
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.
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.