Django Course 20090503 2nd
-
Upload
alina75101 -
Category
Documents
-
view
226 -
download
0
Transcript of Django Course 20090503 2nd
-
8/14/2019 Django Course 20090503 2nd
1/109
Django Tutorial IIDjango ( )Django: a high-level Python Web
framework that encourages rapiddevelopment and clean,pragmatic design.
On Freenode IRC: #python.twSpeaker: timchen119 (aka. tim/
)
-
8/14/2019 Django Course 20090503 2nd
2/109
Review:Web Announce System
#1: Start project (django-admin.pystartproject)
#2: Create application (manage.pystartapp)
#3: Write your model (models.py)#4: Create Database/Install Models
(settings.py)#5: Add admin site (admin.py)#6: Write URLConf (urls.py)
-
8/14/2019 Django Course 20090503 2nd
3/109
Review:
MVCDjango File StructuresDevelopment Environment/Web
ServerHelloWorldSettings.pyAdmin Interface (admin.py)
Very Basic URLConf Usage
Very Basic Template Usage
-
8/14/2019 Django Course 20090503 2nd
4/109
Controller (DjangosView)
ModelView (Djangos
Template)
HTTPRequest
-
8/14/2019 Django Course 20090503 2nd
5/109
-
8/14/2019 Django Course 20090503 2nd
6/109
Django 4-2
Write Books Management SystemMost Examples/Explanations comeFrom Django Book Chapter 5 Learn Object-relational mapper(ORM)
Learn Django Database Shell
-
8/14/2019 Django Course 20090503 2nd
7/109
Follow me. #1: Startproject
django-admin startproject mysite
mysite/
__init__.py
manage.py
settings.py
urls.py
-
8/14/2019 Django Course 20090503 2nd
8/109
Follow me #2: Createapplication
cd mysite
python manage.py startapp books
mysite/books/
__init__.py
models.py
views.py
# t
-
8/14/2019 Django Course 20090503 2nd
9/109
o ow me # - : r temodel
mysite/books/models.pyfrom django.db import models #autogenerate
class Publisher(models.Model):name =
models.CharField(max_length=30)
address =models.CharField(max_length=50)
city = models.CharField(max_length=60)
state_province
-
8/14/2019 Django Course 20090503 2nd
10/109
Follow me #3-2: Writemodel
class Author(models.Model):first_name =
models.CharField(max_length=30)last_name =
models.CharField(max_length=40)email = models.EmailField()
class Book(models.Model):title =
models.CharField(max_length=100)=
-
8/14/2019 Django Course 20090503 2nd
11/109
Explain Model
each model is represented by aPython class that is a subclass ofdjango.db.models.Model.
parent class, Model, contains all themachinery necessary to make theseobjects capable of interacting with a
databaseEach model generally corresponds to
a single database table, and each
attribute on a model generally
-
8/14/2019 Django Course 20090503 2nd
12/109
SQL: Publisher model
CREATE TABLE "books_publisher" ( "id" serial NOT NULL PRIMARY KEY,
"name" varchar(30) NOT NULL,"address" varchar(50) NOT NULL,"city" varchar(60) NOT NULL,"state_province" varchar(30) NOT
NULL,"country" varchar(50) NOT NULL,"website" varchar(200) NOT NULL
);
-
8/14/2019 Django Course 20090503 2nd
13/109
id
we havent explicitly defined aprimary key in any of these models.Unless you instruct it otherwise,Django automatically gives everymodel an auto-incrementing integerprimary key field calledid. Each
Django model is required to have asingle-column primary key.
-
8/14/2019 Django Course 20090503 2nd
14/109
More Model Definition
FieldsCharFieldEmailField IPAddressFieldDateTimeField .... lots of fields to define
http://www.djangobook.com/en/1.0/app
http://www.djangobook.com/en/1.0/appendixB/http://www.djangobook.com/en/1.0/appendixB/ -
8/14/2019 Django Course 20090503 2nd
15/109
Follow me #4: CreateDatabase
notepad++ settings.py
DATABASE_ENGINE : sqlite3
DATABASE_NAME : books.db INSTALLED_APPS = 'mysite.books'
python manage.py syncdb
# also create a superuser
-
8/14/2019 Django Course 20090503 2nd
16/109
Review: What Did WeDo?
Project: mysite (a python package dir with __init__.py)
App: books (another python package dir with __init__.py)
Models: models.py (python module a .py file)
INSTALLED_APPS: mysite.books insettings.py
-
8/14/2019 Django Course 20090503 2nd
17/109
Stop Here!
We Can Finish This.(just like We wrote a Web Announce
System Last Time)
Could just: Add admin.pyAdd Some Views (controllers)
Add Some Templates (HTMLpages)However,Let's Playing Django Models First.
-
8/14/2019 Django Course 20090503 2nd
18/109
Try Some Commands
python manage.py validatepython manage.py sqlall bookspython manage.py syncdbpython manage.py dbshellpython manage.py shell
-
8/14/2019 Django Course 20090503 2nd
19/109
Basic Data Access(CRUD)CRUD: Create,Read,Update,Deletepython manage.py shell>>> from books.models import Publisher
>>> p1 = Publisher(name='Apress',address='2855 TelegraphAvenue',city='Berkeley',state_province='CA', country='U.S.A.',website='http://www.apress.com/')
>>> p1.save()You Create and Saved a Publisher Object
to Database! :)
-
8/14/2019 Django Course 20090503 2nd
20/109
Basic Data Access(CRUD)
>>> p2 = Publisher(name="O'Reilly",address='10 Fawcett St.',
... city='Cambridge',state_province='MA',country='U.S.A.',
... website='http://www.oreilly.com/')
>>> p2.save()>>> publisher_list =
Publisher.objects.all()
>>> publisher_list
-
8/14/2019 Django Course 20090503 2nd
21/109
2 Create Methods
p1 = Publisher(...)# At this point, p1 is not saved to the
database yet!p1.save()=========================
================
>>> p1 =Publisher.objects.create(name='Apress',
... address='2855 Telegraph Avenue',
... city='Berkeley', state_province='CA',=' '
-
8/14/2019 Django Course 20090503 2nd
22/109
__unicode__()
>>> publisher_list =Publisher.objects.all()
>>> publisher_list [,
]A __unicode__() method tells Python
how to display the unicoderepresentation of an object.
Was __str__()
-
8/14/2019 Django Course 20090503 2nd
23/109
Add __unicode__ tomodels
from django.db import models
class Publisher(models.Model):name =
models.CharField(max_length=30)address =
models.CharField(max_length=50)....
def __unicode__(self):
-
8/14/2019 Django Course 20090503 2nd
24/109
Add __unicode__ tomodels
class Author(models.Model):first_name =
models.CharField(max_length=30)last_name =
models.CharField(max_length=40)email = models.EmailField()
def __unicode__(self):return u'%s %s' %
(self.first_name, self.last_name)
-
8/14/2019 Django Course 20090503 2nd
25/109
Add __unicode__ tomodels
class Book(models.Model):title =
models.CharField(max_length=100)authors =
models.ManyToManyField(Author)publisher =
models.ForeignKey(Publisher)publication_date =
models.DateField()
-
8/14/2019 Django Course 20090503 2nd
26/109
__unicode__() effect
Was:>>> publisher_list[,
]Now:>>> from books.models import
Publisher>>> publisher_list =
Publisher.objects.all()
>>> publisher_list
-
8/14/2019 Django Course 20090503 2nd
27/109
Advanced: lambda,anonymous functions
Publisher.__unicode__ = lambda self:self.name
Author.__unicode__ = lambda self:u'%s %s' % (self.first_name,self.last_name)
Book.__unicode__ = lambda self:
self.titleYou could just define a Named
function and bind it in the django
shell without use lambda.
bj
-
8/14/2019 Django Course 20090503 2nd
28/109
Create More Objects(INSERT)
>>> p = Publisher(name='Apress',... address='2855 Telegraph Ave.',... city='Berkeley',... state_province='CA',... country='U.S.A.',... website='
http://www.apress.com/')>>> p.save()
http://www.apress.com/http://www.apress.com/ -
8/14/2019 Django Course 20090503 2nd
29/109
SQL
INSERT INTO books_publisher(name, address, city, state_province,
country, website)VALUES
('Apress', '2855 Telegraph Ave.','Berkeley', 'CA',
'U.S.A.', 'http://www.apress.com/');
-
8/14/2019 Django Course 20090503 2nd
30/109
SQL queries Django is
running?>>> from django.db import connection>>> connection.queriesDEBUG=True (settings.py)``sql`` -- The raw SQL statement``time`` -- How long the statement
took to execute, in seconds.
-
8/14/2019 Django Course 20090503 2nd
31/109
EDIT Objects (UPDATE)
>>> p.id52>>> p.name = 'Apress Publishing'>>> p.save()
-
8/14/2019 Django Course 20090503 2nd
32/109
SQL
UPDATE books_publisher SETname = 'Apress Publishing',address = '2855 Telegraph Ave.',city = 'Berkeley',state_province = 'CA',country = 'U.S.A.',
website = 'http://www.apress.com'WHERE id = 52;
-
8/14/2019 Django Course 20090503 2nd
33/109
Selecting Objects
>>> Publisher.objects.all()[,
-
8/14/2019 Django Course 20090503 2nd
34/109
SQL
SELECT id, name, address, city,state_province, country, website
FROM books_publisher;
-
8/14/2019 Django Course 20090503 2nd
35/109
Manager
Publisher.objects.all()
Manager
-
8/14/2019 Django Course 20090503 2nd
36/109
Advanced: Manager
All models automatically get a objectsmanager; youll use it any time youwant to look up model instances.
a models manager is an objectthrough which Django modelsperform database queries.
Each Django model has at least onemanager, and you can create custommanagers in order to customize
database access.
-
8/14/2019 Django Course 20090503 2nd
37/109
commonly executed
queries in DSLs.DSL: Domain Specific Language.You DON'T really NEED it.Use it when you feel comfortable.Add a class extended
django.db.models.Manager.Write a custom function.
Replace default manager 'objects'.Benefit: Prevent Duplicate Code.Defects: Create Difficult Code.
(possibly)
-
8/14/2019 Django Course 20090503 2nd
38/109
class BookManager(models.Manager):def title_count(self, keyword):
return
self.filter(title__icontains=keyword).count()class Book(models.Model):title =
models.CharField(max_length=100)
authors =models.ManyToManyField(Author)publisher = models.ForeignKey(Publisher)
publication date = models.DateField()
Advanced: Book Manager
-
8/14/2019 Django Course 20090503 2nd
39/109
Examples:
>>> Book.objects.title_count('django')4>>> Book.objects.title_count('python')18
H t ll SQL
-
8/14/2019 Django Course 20090503 2nd
40/109
How to manually use SQLin models?
Standard Python DBAPI>>> from django.db import connection>>> cursor = connection.cursor()>>> cursor.execute("""... SELECT DISTINCT first_name... FROM people_person
... WHERE last_name = %s""",['Lennon'])
>>> row = cursor.fetchone()
>>> print row' '
-
8/14/2019 Django Course 20090503 2nd
41/109
Usage: Custom SQL in
Modelsfrom django.db import connection,models
classPersonManager(models.Manager):def first_names(self, last_name):
cursor = connection.cursor()cursor.execute("""
SELECT DISTINCT first_name
FROM people person= """
Custom SQL define in
-
8/14/2019 Django Course 20090503 2nd
42/109
Custom SQL define inmodels
class Person(models.Model):first_name =
models.CharField(max_length=50)last_name =
models.CharField(max_length=50)objects = PersonManager()
-
8/14/2019 Django Course 20090503 2nd
43/109
SQL? Didn't see it now.
>>>Person.objects.first_names('Lennon')
['John', 'Cynthia']
-
8/14/2019 Django Course 20090503 2nd
44/109
Filtering Data
>>>Publisher.objects.filter(name='Apress')
[]
-
8/14/2019 Django Course 20090503 2nd
45/109
SQL
SELECT id, name, address, city,state_province, country, website
FROM books_publisherWHERE name = 'Apress';
-
8/14/2019 Django Course 20090503 2nd
46/109
Filtering Data (more)
>>>Publisher.objects.filter(country="U.S.A.", state_province="CA")
[]
-
8/14/2019 Django Course 20090503 2nd
47/109
SQL
SELECT id, name, address, city,state_province, country, website
FROM books_publisherWHERE country = 'U.S.A.'AND state_province = 'CA';
-
8/14/2019 Django Course 20090503 2nd
48/109
XXX__contains
>>>Publisher.objects.filter(name__contains="press")
[]
-
8/14/2019 Django Course 20090503 2nd
49/109
SQL
SELECT id, name, address, city,state_province, country, website
FROM books_publisher
WHERE name LIKE '%press%';
-
8/14/2019 Django Course 20090503 2nd
50/109
Lookup Examples:
>>>Entry.objects.filter(headline__istartswith='will')
>>>Entry.objects.filter(headline__endswith='cats')
>>>Entry.objects.filter(headline__iendswith='cats')
>>> start_date = datetime.date(2005, 1,
-
8/14/2019 Django Course 20090503 2nd
51/109
More Field Lookups
_ _ ==> MAGICS in python__contains__icontains (case insensitive contains)__startswith__endswith__range (SQL between)
....http://www.djangobook.com/en/1.0/app
http://www.djangobook.com/en/1.0/appendixC/http://www.djangobook.com/en/1.0/appendixC/ -
8/14/2019 Django Course 20090503 2nd
52/109
Retrieving Single Objects
filter() returned a QuerySet>>> Publisher.objects.filter(country="U.S.A.",
state_province="CA")[]>>> Publisher.objects.get(name="Apress")>>> Publisher.objects.get(country="U.S.A.")
Traceback (most recent call last):...MultipleObjectsReturned: get() returned more
than one Publisher --
it returned 2! Lookup parameters were' ' ' '
-
8/14/2019 Django Course 20090503 2nd
53/109
DoesNotExist exception
>>>Publisher.objects.get(name="Penguin")
Traceback (most recent call last):...
DoesNotExist: Publisher matching
query does not exist.
-
8/14/2019 Django Course 20090503 2nd
54/109
Handle Exception
try:p =
Publisher.objects.get(name='Apress')
except Publisher.DoesNotExist:print "Apress isn't in the database
yet."
else:print "Apress is in the database."
-
8/14/2019 Django Course 20090503 2nd
55/109
Ordering Data
>>>Publisher.objects.order_by("name")
[, , ]
>>>"
-
8/14/2019 Django Course 20090503 2nd
56/109
Ordering Data
order by multiple fields>>>
Publisher.objects.order_by("state_pro
vince", "address")[, ,
-
8/14/2019 Django Course 20090503 2nd
57/109
Default ordering inmodel
class Publisher(models.Model):name =
models.CharField(max_length=30)
address =models.CharField(max_length=50)city =
models.CharField(max_length=60)state_province =
models.CharField(max_length=30)country =
=
-
8/14/2019 Django Course 20090503 2nd
58/109
Chaining Lookups
>>>Publisher.objects.filter(country="U.S.A.").order_by("-name")
[
-
8/14/2019 Django Course 20090503 2nd
59/109
SQL
SELECT id, name, address, city,state_province, country, website
FROM books_publisher
WHERE country = 'U.S.A'ORDER BY name DESC;
-
8/14/2019 Django Course 20090503 2nd
60/109
Slicing Data
>>>Publisher.objects.order_by('name')[0]
SQL:SELECT id, name, address, city,
state_province, country, websiteFROM books_publisherORDER BY nameLIMIT 1;
-
8/14/2019 Django Course 20090503 2nd
61/109
Slicing Data
>>>Publisher.objects.order_by('name')[0:2]
SELECT id, name, address, city,state_province, country, website
FROM books_publisherORDER BY nameOFFSET 0 LIMIT 2;
Django Slice: No
-
8/14/2019 Django Course 20090503 2nd
62/109
Django Slice: NoNegative indexing
>>>Publisher.objects.order_by('name')[-1]
Traceback (most recent call last):...
AssertionError: Negative indexing is
not supported.
Publisher.objects.order_by('-name')[0]
Tips: SQL optimize
-
8/14/2019 Django Course 20090503 2nd
63/109
Tips: SQL optimizeTricks: update()
update()Update Objects using save()
>>> p =Publisher.objects.get(name='Apress')
>>> p.name = 'Apress Publishing'
>>> p.save()
Problem: updates all columns in arow.
-
8/14/2019 Django Course 20090503 2nd
64/109
SQL
SELECT id, name, address, city, state_province,country, website
FROM books_publisher
WHERE name = 'Apress';UPDATE books_publisher SETname = 'Apress Publishing',address = '2855 Telegraph Ave.',
city = 'Berkeley',state_province = 'CA',country = 'U.S.A.',website = 'http://www.apress.com'
WHERE id = 52;
-
8/14/2019 Django Course 20090503 2nd
65/109
Update Objects Idioms
update()
>>>
Publisher.objects.filter(id=52).update(name='Apress Publishing')
-
8/14/2019 Django Course 20090503 2nd
66/109
SQL
UPDATE books_publisherSET name = 'Apress Publishing'WHERE id = 52;
d Q S
-
8/14/2019 Django Course 20090503 2nd
67/109
Update QuerySet
update() method works on anyQuerySet
>>>
Publisher.objects.all().update(country='USA')
2
2 -- an integer representing howmany records changed
D l i Obj
-
8/14/2019 Django Course 20090503 2nd
68/109
Deleting Objects
>>> p =Publisher.objects.get(name="O'Reilly")
>>> p.delete()
>>> Publisher.objects.all()[]>>>
Publisher.objects.filter(country='USA').delete()>>> Publisher.objects.all().delete()>>> Publisher.objects.all()
D l ti Obj t
-
8/14/2019 Django Course 20090503 2nd
69/109
Deleting Objects
Delete All Objects:>>> Publisher.objects.all().delete()Delete Subset Objects:
>>>Publisher.objects.filter(country='USA').delete()
Remember use all()
>>> Publisher.objects.delete()Traceback (most recent call last):
File "", line 1, in
AttributeError: 'Manager' object has no
D i W b Sit
-
8/14/2019 Django Course 20090503 2nd
70/109
Dynamic Web Site
Template
R b H ll ld?
-
8/14/2019 Django Course 20090503 2nd
71/109
Remember Helloworld?
from django.http import HttpResponse
def hello(request):
return HttpResponse("Hello world")
What do you need for a
-
8/14/2019 Django Course 20090503 2nd
72/109
What do you need for adjango program?
You Just need these things inDjango's view: Define a function
IN: Request
OUT: ResponseNo template Need.
No models (database) Need.Just view and urlconf are enough for
web scripts.
i
-
8/14/2019 Django Course 20090503 2nd
73/109
views.py
from django.http import HttpResponseimport datetime
def current_datetime(request):now = datetime.datetime.now()html = "It is now
%s." % nowreturn HttpResponse(html)
Wh t' W ?
-
8/14/2019 Django Course 20090503 2nd
74/109
What's Wrong?
HTML is mixed in python code UGLY.
Any change to the design of the page
requires a change to the Pythoncode. -- The design of a site tends tochange far more frequently.
Writing Python code and designingHTML are two different disciplines --Designers and HTML/CSS codersshouldnt be required to edit Python
-
8/14/2019 Django Course 20090503 2nd
75/109
T l t
-
8/14/2019 Django Course 20090503 2nd
76/109
Templates
A template is simply a text file. It cangenerate any text-based format(HTML, XML, CSV, etc.).
A template contains variables, whichget replaced with values when thetemplate is evaluated, and tags,
which control the logic of thetemplate.TEMPLATE_DIRS
i i l t l t
-
8/14/2019 Django Course 20090503 2nd
77/109
a minimal template
{% extends "base_generic.html" %}{% block title %}{{ section.title }}{% endblock
%}{% block content %}{{ section.title }}{% for story in story_list %}
{{ story.headline|upper }}
{{ story.tease|truncatewords:"100" }}
{% endfor %}{% endblock %}
V i bl
-
8/14/2019 Django Course 20090503 2nd
78/109
Variables
{{ variable }}Use a dot (.) to access attributes of a
variable. * Dictionary lookup * Attribute lookup * Method call
* List-index lookup http://docs.djangoproject.com/en/dev/topics/templates/#using-the-built-in-rExample:{{ section.title }}
Variables
http://docs.djangoproject.com/en/dev/topics/templates/#using-the-built-in-referencehttp://docs.djangoproject.com/en/dev/topics/templates/#using-the-built-in-reference -
8/14/2019 Django Course 20090503 2nd
79/109
Variables
{% extends "base_generic.html" %}{% block title %}{{ section.title }}{%
endblock %}
{% block content %}{{ section.title }}{% for story in story_list %} {{ story.headline|upper }}
{{ story.tease|
truncatewords:"100" }}
Filters
-
8/14/2019 Django Course 20090503 2nd
80/109
Filters
modify variables for display by usingfilters.
{{ name|lower }}This displays the value of the
{{ name }} variable after beingfiltered through the lower filter, which
converts text to lowercase.{{ text|escape|linebreaks }} is a
common idiom for escaping textcontents, then converting line breaks
default filter
-
8/14/2019 Django Course 20090503 2nd
81/109
default filter
If a variable is false or empty, usegiven default. Otherwise, use thevalue of the variable
{{ value|default:"nothing" }}
If value isn't provided or is empty, theabove will display "nothing".
length filter
-
8/14/2019 Django Course 20090503 2nd
82/109
length filter
Returns the length of the value. Thisworks for both strings and lists;
{{ value|length }}
If value is ['a', 'b', 'c', 'd'], the output
will be 4.
striptags filter
-
8/14/2019 Django Course 20090503 2nd
83/109
striptags filter
Strips all [X]HTML tags
{{ value|striptags }}
If value is "Joelis a
slug", the output willbe "Joel is a slug".
-
8/14/2019 Django Course 20090503 2nd
84/109
Tags
-
8/14/2019 Django Course 20090503 2nd
85/109
Tags
Tags look like this:{% tag %}more complex than variables control flow load external information
create text in the output
....
for
-
8/14/2019 Django Course 20090503 2nd
86/109
for
{% for athlete in athlete_list %}
{{ athlete.name }}
{% endfor %}
if else
-
8/14/2019 Django Course 20090503 2nd
87/109
if else
{% if athlete_list %}Number of athletes: {{ athlete_list|
length }}
{% else %}No athletes.
{% endif %}
ifequal and ifnotequal
-
8/14/2019 Django Course 20090503 2nd
88/109
ifequal and ifnotequal
{% ifequal athlete.name coach.name%}...
{% endifequal %}
{% ifnotequal athlete.name "Joe" %}
...{% endifnotequal %}
Comments
-
8/14/2019 Django Course 20090503 2nd
89/109
Comments
comment syntax: {# #}{# greeting #}hello Only render 'hello'
A comment can contain any templatecode {# {% if foo %}bar{% else %} #}
only be used for single-line commentsMultiple lines: {% comment %} and {% endcomment
%}
Template inheritance
-
8/14/2019 Django Course 20090503 2nd
90/109
Template inheritance
block and extends -- tagsFor extra readability, you can
optionally give a name to your {%
endblock %} tag. For example:
{% block content %}
...{% endblock content %}
Base html
-
8/14/2019 Django Course 20090503 2nd
91/109
Base.html
{% block title %}My amazing site{% endblock%}
{% block sidebar %}HomeBlog
{% endblock %}
{% block content %}{% endblock %}
Child html
-
8/14/2019 Django Course 20090503 2nd
92/109
Child.html
{% extends "base.html" %}
{% block title %}My amazing blog{%
endblock %}
{% block content %}
{% for entry in blog_entries %}{{ entry.title }}
{{ entry.body }}
{% endfor %}
Final Result
-
8/14/2019 Django Course 20090503 2nd
93/109
Final Result
My amazing blog
HomeBlog
Entry one
This is my first entry.
Entry twoThis is my second entry.
tips for template
-
8/14/2019 Django Course 20090503 2nd
94/109
inheritance
the child template didn't define thesidebar block, the value from theparent template is used instead.
Content within a {% block %} tag ina parent template is always used as afallback.
If you use {% extends %} in atemplate, it must be the firsttemplate tag in that template.
Template inheritance won't work,
tips for template
-
8/14/2019 Django Course 20090503 2nd
95/109
inheritance
More {% block %} tags in your basetemplates are better. Remember, childtemplates don't have to define all parentblocks, so you can fill in reasonabledefaults in a number of blocks, then onlydefine the ones you need later. It's betterto have more hooks than fewer hooks.
you can't define multiple {% block %}tags with the same name in the sametemplate.
tips for template
-
8/14/2019 Django Course 20090503 2nd
96/109
inheritance
{{ block.super }} variable can getthe content of the block from theparent template, This is useful if you
want to modify/add to the contents ofa parent block instead of completelyoverriding it.
example:{% block menu %}{{ block.super }}another stuff
Custom tag and filter
-
8/14/2019 Django Course 20090503 2nd
97/109
libraries
To access custom tags and filters in atemplate, use the {% load %} tag
Example:
{% load comments %}
{% comment_form for blogs.entries
entry.id with is_public yes %}
{% load comments i18n %}
Forms
-
8/14/2019 Django Course 20090503 2nd
98/109
Forms
interactive Web sitesGoogles search boxaccess user-submitted form data,
validate it and do something with it. HttpRequest and Form objects.
Hello World Again
-
8/14/2019 Django Course 20090503 2nd
99/109
Hello World Again
from django.http import HttpResponse
def hello(request):
return HttpResponse("Hello world")
HttpRequest
-
8/14/2019 Django Course 20090503 2nd
100/109
HttpRequest
Have Information About SubmittedData
request.GET and request.POSTPOST data generally is submitted
from an HTML GET data can come from a or
the query string in the pages URL.
Django 6
-
8/14/2019 Django Course 20090503 2nd
101/109
Django 6
views.pyfrom django.shortcuts import
render_to_response
def search_form(request):return
render_to_response('search_form.html')
HTML
-
8/14/2019 Django Course 20090503 2nd
102/109
HTML
search_form.html
Search
urls.py
-
8/14/2019 Django Course 20090503 2nd
103/109
urls.py
from mysite.books import views
urlpatterns = patterns('',
# ... (r'^search-form/$',
'books.views.search_form'),
# ...)
Add Search function
-
8/14/2019 Django Course 20090503 2nd
104/109
Add Search function
# urls.py
urlpatterns = patterns('',
# ...(r'^search-form/$',
'books.views.search_form'),
(r'^search/$', 'books.views.search'),# ...)
views.py (1 -- Easy)
-
8/14/2019 Django Course 20090503 2nd
105/109
views.py (1 Easy)
# views.py
def search(request):
if 'q' in request.GET:message = 'You searched for: %r'
% request.GET['q']
else:message = 'You submitted anempty form.'return HttpResponse(message)
views.py (2-1 UseD B )
-
8/14/2019 Django Course 20090503 2nd
106/109
DataBase)
from django.http import HttpResponsefrom django.shortcuts import
render_to_response
from mysite.books.models import Book
-
8/14/2019 Django Course 20090503 2nd
107/109
search results.html
-
8/14/2019 Django Course 20090503 2nd
108/109
search_results.html
You searched for:{{ query }}
{% if books %}
Found {{ books|length }} book{{ books|pluralize }}.
{% for book in books %}
{{ book.title }}{% endfor %}
{% else %}
No books matched your search
Thanks
-
8/14/2019 Django Course 20090503 2nd
109/109
Thanks
To Be Continued!
! Django ( )