Chapter Two Django Basics of Dynamic Web Pages
Chapter Two Django Basics of Dynamic Web Pages
Development
Chapter Two
BY:Eng Mohamed Ahmed Mohamed
Function vs. Class Views
Django allows two styles of views – functions or class based
views
Functions – take a request object as the first parameter and
must return a response object
Class based views – allow CRUD operations with minimal
code. Can inherit from multiple generic view classes (i.e.
Mixins)
Sample – As Class Based View
from .models import Question
from django.views.generic import ListView
class QuestionList(ListView):
model = Question
context_object_name = ‘questions’
urls.py
Defines routes to send urls to various views
Can use regular expressions
Extract parameters from a url and pass to the view as a
named parameter:
r(‘^question/(?P<question_id>\d+)/$’,’views.question_detail’)
Extensible – urls.py can include additional url files from
apps:
r(‘^question/’,include(question.urls))
Views
Working with User Input
Major Steps:
1. Adding an HTML form to our template.
2. Editing the application URLconf.
3. Adding a new view function that processes user
input.
Request & Response
Request object encapsulate the request and provide access to a number
of attributes and methods for accessing cookies, sessions, the logged in
user object, meta data (i.e environment variables),
Response objects are returned to the browser. Can set content type,
content length, response does not have to return HTML or a rendered
template
Special response types allow for common functionality:
HttpResponeRedirect
Http404
HttpStreamingResponse
Quick CRUD Operations with
Generic Views
ListView
UpdateView
CreateView
If Model is specified, automagically creates a matching
ModelForm
Form will save the Model if data passes validation
Override form_valid() method to provide custom logic (i.e
sending email or setting additional fields)
Debugging Hints
The command line you use to run the development server often shows helpful
error messages
Django and the development server support hot-swap; you usually do not need to
restart the server when you change the code. Hot swap works much better on
the development server than in most servers that claim to support it. However,
it doesn’t work fif you change url mappings (see below). Also, note that your
browser may cache responses, so you may need to reload several times to see
changes.
Django Extras
CRSF Middleware – enabled by default. Include template tag in
all forms:
{%csrf_token%}
Authentication
Caching
Sessions
Messages
Email
Logging
Cross-Site Request Forgery
Django comes with a data-preserving feature that
disallows POSTs which are not secure against cross-site
request forgery (CSRF) attacks.
And
Answers