[go: up one dir, main page]

0% found this document useful (0 votes)
53 views70 pages

Django TDTU

The document provides an overview of the Django web framework. It discusses Django's MVT architecture with Models for the database schema, Views for controlling what users see, and Templates for how users see content. It also covers Django's modular design with reusable apps, and how to define models, views, templates, and URLs to build a basic web application.

Uploaded by

lukuchim2022
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)
53 views70 pages

Django TDTU

The document provides an overview of the Django web framework. It discusses Django's MVT architecture with Models for the database schema, Views for controlling what users see, and Templates for how users see content. It also covers Django's modular design with reusable apps, and how to define models, views, templates, and URLs to build a basic web application.

Uploaded by

lukuchim2022
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/ 70

The Django Web Application

Framework

Vu Dinh Hong
2021
Outline
ü Overview
ü Architecture
ü Modules
ü Example
ü Links
Outline
ü Overview
ü Architecture
ü Example
ü Modules
ü Links
Web Application Framework
Ø Define
“A software framework that is designed to support the development of
dynamic website, Web applications and Web services”(from wikipedia)
Ø The ideal framework
p Clean URLs
p Loosely coupled components
p Designer-friendly templates
p As little code as possible
p Really fast development
Web Application Framework(cont..)
Ø Ruby
Ruby on Rails (famous, beauty)
Ø Python
Django, TurboGears, Pylons, Zope, Quixote,web2py(simple)
Ø PHP
CakePHP, CodeIgniter, PRADO, ThinkPHP,QeePHP (poor performance)
Ø Others
Apache, J2EE, .NET...(complex)
Web Application Framework(cont..)
Comparsion
What a Django
Ø “Django is a high-level Python web framework that
encourages rapid development and clean, pragmatic
design.”
Ø Primary Focus
p Dynamic and database driven website
p Content based websites
Django History
Ø Named after famous Guitarist “Django Reinhardt”
Ø Developed by Adrian Holovaty & Jacob Kaplan-moss
Ø Open sourced in 2005
Ø 1.0 Version released Sep.3 2008, now 1.1 Beta
Why Use Django
Ø Lets you divide code modules into logical groups to make it flexible
to change
MVC design pattern (MVT)
Ø Provides auto generated web admin to ease the website
administration
Ø Provides pre-packaged API for common user tasks
Ø Provides you template system to define HTML template for your
web pages to avoid code duplication
DRY Principle
Ø Allows you to define what URL be for a given Function
Loosely Coupled Principle
Ø Allows you to separate business logic from the HTML
Separation of concerns
Ø Everything is in python (schema/settings)
Outline
ü Overview
ü Architecture
ü Modules
ü Example
ü Links
Django as an MVC Design Pattern
MVT Architecture:
p Models
Describes your data structure/database schema
p Views
Controls what a user sees
p Templates
How a user sees it
p Controller
The Django Framework
URL dispatcher
Django Project Layout
django-admin.py startproject
<PROJECT_ROOT>
manage.py
<PROJECT_DIR>
__init__.py
settings.py
urls.py
wsgi.py
settings.py
Ø Defines settings used by a Django application
Ø Referenced by wsgi.py to bootstrap the project
loading
Ø Techniques for managing dev vs prod settings:
p Create settings-dev.py and settings-prod.py and use symlink to link
settings.py to the correct settings
p Factor out common settings into base-settings.py and import. Use
conditionals to load correct settings based on DEBUG or other setting
Sample Settings…
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
)
Django Apps
Ø Reusable modules
Ø django-admin.py startapp <APP_NAME>
Ø Creates stub layout:
<APP_NAME>
admin.py
models.py
templates (directory)
tests.py
views.py
urls.py
Architecture Diagram

Brower

Template URL dispatcher

View

Model

DataBase
Model

Brower

Template URL dispatcher

View

Model

DataBase
Model Overview
SQL Free
ORM
Relations
API
Django Models
Ø Defined in models.py
Ø Typically inherit from django.db.models.Model
Example Model:
from django.db import models
class TestModel(models.Model):
name = models.CharField(max_length = 20)
age = models.IntegerField()
Models (cont’d)
Ø Default is to set NOT NULL on all fields. Override by
adding null = True to field definition:
name = models.CharField(max_length=20, null =
True)
Ø Relationships defined through special field types:
models.OneToOneField(model)
models.ForeignKey(model)
models.ManyToManyField(model)
Models (cont’)
Ø Need Nulls in a Boolean Field? Use
models.NullBooleanField()
Ø Set Default value with “default”:
count = models.IntegerField(default = 0)
Ø Use a inner Meta class to define additional options,
especially useful for abstract classes:
class TestModel(models.Model):
class Meta:
abstract = True
Model Methods
Ø model.save(self, *args, **kwargs)
Ø model.delete(self, *args, **kwargs)
Ø model.get_absolute_url(self)
Ø model.__str__(self) [Python 3]
model.__unicode__(self) [Python 2]
Ø Override with super(MODEL, self).save(*args,
**kwargs)
Activating a Model
Ø Add the app to INSTALLED_APPS in settings.py
Ø Run manage.py makemigrations
Ø Run manage.py migrate
Selecting Objects
Ø Models include a default manager called objects
Ø Manager methods allow selecting all or some
instances
Question.objects.all()
Question.objects.get(pk = 1)
Use try block, throws DoesNotExist
exception if no match
Question.objects.filter(created_date__lt = ‘2014-
01-01’)
Ø Returns QuerySet
Introspecting Legacy Models
Ø manage.py inspectdb
Ø It will generate code for models.
Ø Cut and paste generated code into models.py –
Easy!!
Full Sample
from django.db import models
from datetime import datetime
class TimestampedModel(models.Model):
created_datetime = models.DateTimeField()
updated_datetime = models.DateTimeField()
def save(self, *args, **kwargs):
if self.id is None:
self.created_datetime = datetime.now()
updated_datetime = datetime.now()
super(TimestampedModel,self).save(*args, **kwargs)
class Meta:
abstract = True
Full Sample (cont’d)
class Question(TimestampedModel):
question_text = models.CharField(max_length = 200)
def __str__(self):
return self.question_text
Other model example

class Category(models.Model):
name = models.CharField(max_length=200)
slug = models.SlugField(unique=True)

class Entry(models.Model):
title = models.CharField(max_length=200)
slug = models.SlugField(unique=True)
body = models.TextField()
data = models.DateTimeField(default=datetime.now)
categories = models.ManyToManyField(Category)

python manage.py makemigrations


python manage.py migrate
Model API
>>> category = Category(slug='django', name='Django')
>>> category.save()
>>> print category.name
u'Django'

>>> categories = Category.objects.all()


>>> categories = Category.objects.filter(slug='django')
>>> categories
[<Category: Category object>]

>>> entry = Entry(slug='welcome', title='Welcome', body='')


>>> entry.save()
>>> entry.categories.add( category[0] )
>>> print entry.categories.all()
[<Category: Category object>]
View

Brower

Template URL dispatcher

View

Model

DataBase
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)
View
from django.shortcuts import get_object_or_404, render
def entry_list(request):
entries = Entry.objects.all()[:5]
return render('list.html', {'entries': entries})

def entry_details(request, slug):


entry = get_object_or_404(Entry, slug = slug)
return render('details.html', {'entry': entry})
Sample – Viewing a List of Questions
Ø Function based:
from .models import Question
from django.shortcuts import render

def question_list(request):
questions = Question.objects.all()
return render(‘question_list.html’, {
‘questions’:questions})
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)
Sample – As Class Based View
from .models import Question
from django.views.generic import ListView

class QuestionList(ListView):
model = Question
context_object_name = ‘questions’
Template

Brower

Template URL dispatcher

View

Model

DataBase
Django Templates
Ø Very simple syntax:
variables = {{variable_name}}
template tags = {%tag%}
Ø Flexible – can be used to render html, text, csv,
email, you name it!
Ø Dot notation – template engine attempts to resolve
by looking for matching attributes, hashes and
methods
Question List Template
<!doctype html>
<html lang=en>
<head>
<meta charset=utf-8>
<title>List of Questions</title>
</head>
<body>
{%if questions%}
<ul>
{%for q in questions%}
<li>{{q.question_text}}</li>
{%endfor%}
</ul>
{%else%}
<p>No questions have been defined</p>
{%endif%}
</body>
</html>
Custom tags, filters
Custom tags, filters
Custom tags, filters
Template Syntax
Ø {{ variables }}, {% tags %}, filters (list.html)

<html>
<head>
<title>My Blog</title>
</head>
<body>
{% for entry in entries %}
<h1>{{ entry.title|upper }}</h1>
{{ entry.body }}<br/>
Published {{ entry.data|date:"d F Y" }},
<a href=”{{ entry.get_absolute_url }}”>link</a>.
{% endfor %}
</body>
</html>
Tag and Filter
Ø Build in Filters and Tags
Ø Custom tag and filter libraries
Put logic in tags
{% load comments %}
<h1>{{ entry.title|upper }}</h1>
{{ entry.body }}<br/>
Published {{ entry.data|date:"d F Y" }},
<a href=”{{ entry.get_absolute_url }}”>link</a>.
<h3>评论: </h3>
{% get_comment_list for entry as comment_list %}
{% for comment in comment_list %}
{{ comment.content }}
{% endfor %}
Template Inheritance
base.html index.html
<html>
<head>
<title>
{% extend “base.html” %}
{% block title %}
{% block title %}
{% endblock %}
Main page
</title>
{% endblock %}
</head>
{% block body %}
<body>
Content
{% block body %}
{% endblock %}
{% endblock %}
</body>
</html>
URL Dispatcher

Brower

Template URL Dispatcher

View

Model

DataBase
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))
Hooking up the Question List
from django.conf.urls import patterns, url, include
urlpatterns = patterns(‘’,
(r’^questions/$’,’views.QuestionList’)
)
OR:
from django.conf.urls import patterns
from views import QuestionList

urlpatterns = patterns(‘’,
(r’^questions/$’,QuestionList.as_view())
)
URL Dispatcher

#http://jianghu.leyubox.com/articles/
urlpatterns = patterns('', ((r'^articles/$', ‘article.views.index'), )

#http://jianghu.leyubox.com/articles/2003/
(r'^articles/(?P<year>\d{4})/$', ‘article.views.year_archive'),

# http://jianghu.leyubox.com/articles/2003/ 12/
(r'^articles/(?P<year>\d{4})/(?P<month>\d{2})/$',
'article.views.month_archive'),

# http://jianghu.leyubox.com/articles/2003/ 12/3
(r'^articles/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d+)/$',
'article..views.article_detail'), )
Outline
ü Overview
ü Architecture
ü Modules
ü Example
ü Links
Modules
Ø Form
Ø Adminstration interface
Ø Custom Middleware
Ø Caching
Ø Signals
Ø Comments system
Ø More...
Forms in Django
Ø django.forms provides a class to build HTML forms
and validation. Example:
from django import forms
class EditQuestionForm(forms.Form):
question_text = forms.CharField(max_length = 200)

Ø Often redundant when creating forms that work on a


single model
ModelForms
Ø Automatically generate a form from a model.
Ø Handles saving a bound model
Ø Can specify fields to be included or excluded in the form
Ø Sample:
from django.forms import ModelForm
from .models import Question

class QuestionForm(ModelForm):
class Meta:
model = Question
fields = [‘question_text’]
Using a ModelForm
Ø Create an instance of an empty form:
form = QuestionForm()
Ø Create a form to update an existing instance of a model:
question = Question.objects.get(pk = 1)
form = QuestionForm(instance = question)
Ø Pass the form into the template and use the form
methods to render the form:
form.as_p
form.as_ul
form.<field_name>
form.<field_name>.errors
Modules:Form

class ContactForm(forms.Form):
subject = forms.CharField(max_length=100)
message = forms.CharField(widget=forms.Textarea)
sender = forms.EmailField()
cc_myself = forms.BooleanField(required=False)

<form action="/contact/" method="POST">


{{ form.as_table}}
<input type="submit" value="Submit" />
</form>
Modules:Adminstration interface
Modules: Custom Middleware
chain of processes

request Common Session Authentication Profile response


Middleware Middleware Middleware Middleware
Modules: Caching

Memcached Database Filesystem Local-memory Dummy

BaseCache

template caching
Per-Site Caching Per-View Caching
Modules:More...
Ø Sessions
Ø Authentication system
Ø Internationalization and localization
Ø Syndication feeds(RSS/Atom)
Ø E-mail(sending)
Ø Pagination
Ø Signals
Authentication
Ø Django’s out of the box Auth system uses database
authentication.
Ø Changed extensively in Django 1.6 to allow custom
User objects.
Ø AUTHENTICATION_BACKENDS setting in settings.py
allows overriding how User objects are authenticated
Ø If using the Authentication middleware and
context_processors the current user is available to
code as request.user and {{user}} is defined in all
templates
Auth Decorators
Ø Live in django.contrib.auth.decorators
Ø login_required
@login_required
def function_view(request):
….
Ø user_passes_test (can be used with lambda functions for
real power) –
@user_passes_test(lambda u: u.is_staff)
def function_view(request):

Ø has_perms – test for user permissions
Decorating CBVs
Ø Decorator is applied to the dispatch method
Ø Must be converted to a method_decorator – use
django.utils.decorators.method_decorator function:
class MyView(ListView):

@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
super(MyView,self).dispatch(*args, **kwargs)
Custom Auth Backend for the Bubble

Add to settings.py
AUTHENTICATION_BACKENDS = [‘projectname.authbackend.BubbleBackend']
Sending Email
Ø django.core.mail includes functions and classes for
handling email
Ø Set EMAIL_HOST in settings.py to outgoing
mailserver
Ø Import send_mail for simple mail:
send_mail(subject, message, from, to_emails)
Ø Use django.template.render_to_string to format a
message using a template
Ø Use EmailMultiAlternatives to create a text message
and attach a html version as well.
Outline
ü Overview
ü Architecture
ü Modules
ü Example
ü Links
Example
Ø django_admin startproject leyubbs
Ø modify setting.py
p set database options
p append admin app: django.contrib.admin
Ø Run makemigrations and migrate
Ø python manager.py runserver
Ø modify urls.py, append /admin path
Example(cont...)
Ø python manager.py startapp article
Ø add a model
Ø Run makemigrations and migrate
Ø explore admin page
Ø inset a record in adminstration interface
Ø add a veiw function
Ø add a url
Outline
ü Overview
ü Architecture
ü Modules
ü Example
ü Links
Links: Who Use
Links: Resource
Ø http://www.djangoproject.com/
For more information (Documentation,Download and News)

Ø http://www.djangobook.com/
A Good book to learn Django

Ø http://www.djangopluggables.com
A lot of Django Pluggables available online Explore at

Ø http://www.pinaxproject.com/
Community Development
Thanks (Q&A)

You might also like