Kategorier: Alla - template - context - object

av Kenny Belitzky för 16 årar sedan

7250

Generic Views API for Django

The text provides detailed information about using Django's generic views, specifically focusing on `list_detail.object_detail` and `date_based` views. It describes common arguments for these views, such as `extra_

Generic Views API for Django

Djeneric Views (Django)

Extending views

Wrap view function for plain text
def author_list_plaintext(request): response = list_detail.object_list( queryset = Author.objects.all(), mimetype = "text/plain", template_name = "bookstore/author_list.txt" ) response["Content-Disposition"] = "attachment; filename=authors.txt" return response
Wrap view function to update field
import datetime from bookstore.models import Author from django.views.generic import list_detail from django.shortcuts import get_object_or_404 def author_detail(request, author_id): # Look up the Author (and raise a 404 if she's not found) author = get_object_or_404(Author, pk=author_id) # Record the last accessed date author.last_accessed = datetime.datetime.now() author.save() # Show the detail page return list_detail.object_detail( request, queryset = Author.objects.all(), object_id = author_id, )
from bookstore.views import author_detail urlpatterns = patterns('', #... (r'^authors/(?Pd+)/$', author_detail), )
add the last_accessed field to your Author model
Wrap view function to filter
from bookstore.models import Book from django.views.generic import list_detail def browse_alphabetically(request, letter): return list_detail.object_list( request, queryset = Book.objects.filter(title__startswith=letter), template_name = "bookstore/browse_alphabetically.html", extra_context = { 'letter' : letter, } )
from bookstore.views import browse_alphabetically urlpatterns = patterns('', # ... (r'^books/by-title/([a-z])/$', browse_alphabetically) )
This works because there’s really nothing special about generic views — they’re just Python functions. Like any view function, generic views expect a certain set of arguments and return HttpResponse objects. Thus, it’s incredibly easy to wrap a small function around a generic view that does additional work before — or after; see below — handing things off to the generic view.
Add extra_context

Common Arguments (Optional)

override 'object'/'object_list'.
override queryset default = /_list.html, e.g., bookstore/author_list.html
used for resulting document
book_info = { "queryset" : Book.objects.all(), "date_field" : "publication_date", "extra_context" : { "publisher_list" : Publisher.objects.all(), } }
any callable called just before render.
context_processors (template)
list
else 404

Complex

create_update. (CRUD CReate/Update/Delete)
delete_object (_confirm_delete.html)

If this view is fetched with GET, it will display a confirmation page (i.e. “do you really want to delete this object?”). If the view is submitted with POST, the object will be deleted without confirmation.

update_object (_form.html)

object

w/r/t template_object_name

form (FormWrapper instance)

commonargs (5)

from django.conf.urls.defaults import * from django.views.generic import list_detail, date_based, create_update from bookstore.models import Publisher, Author, Book book_info = { "queryset" : Book.objects.all(), "date_field" : "publication_date", } urlpatterns = patterns('', (r'^books/edit/(?P\d+)/$', create_update.update_object, {'model' : Book}), )

create_object (_form.html)

FormWrapper example

{{ form.name }}

{{ form.address }}

form (FormWrapper instance)

commonargs (4)

mimetype (?)

login_required

default = False

post_save_redirect

• post_save_redirect may contain dictionary string formatting, which will be interpolated against the object's field attributes. For example, you could use post_save_redirect="/polls/%(slug)s/".

default = object.get_absolute_url()

model

from django.conf.urls.defaults import * from django.views.generic import list_detail, date_based, create_update from bookstore.models import Publisher, Author, Book book_info = { "queryset" : Book.objects.all(), "date_field" : "publication_date", } urlpatterns = patterns('', (r'^books/create/$', create_update.create_object, {'model' : Book}), )

"very rough idea of security"

Note that these views all have a very rough idea of security. Although they take a login_required attribute which if given will restrict access to logged-in users, that’s as far as it goes. They won’t, for example, check that the user editing an object is the same user that created it, nor will they validate any sort of permissions. Much of the time, however, those features can be accomplished by writing a small wrapper around the generic view; see “extending generic views”, below, for more about this topic.

date_based.
object_detail (_detail.html)

object (w/r/t template_object_name parameter)

week (datetime.date object)

from django.conf.urls.defaults import * from django.views.generic import list_detail, date_based, create_update from bookstore.models import Publisher, Author, Book book_info = { "queryset" : Book.objects.all(), "date_field" : "publication_date", } urlpatterns = patterns('', (r'^(?P\d{4})/(?P[a-z]{3})/(?P\d{2})/(?P[\w-]+)/$', date_based.object_detail, book_info), )

archive_today. (_archive_today.html)

as archive_day.

archive_day. (_archive_day.html)

previous_day

next_day

day_format

default = "%d" (decimal 01-31)

day

from django.conf.urls.defaults import * from django.views.generic import list_detail, date_based, create_update from bookstore.models import Publisher, Author, Book book_info = { "queryset" : Book.objects.all(), "date_field" : "publication_date", } urlpatterns = patterns('', (r'^(?P\d{4})/(?P[a-z]{3})/(?P\d{2})/$', date_based.archive_day, book_info), )

archive_week. (_archive_week.html)

week (datetime.date object)

week

from django.conf.urls.defaults import * from django.views.generic import list_detail, date_based, create_update from bookstore.models import Publisher, Author, Book book_info = { "queryset" : Book.objects.all(), "date_field" : "publication_date", } urlpatterns = patterns('', (r'^(?P\d{4})/(?P\d{2})/$', date_based.archive_week, book_info), )

archive_month (_archive_month.html)

previous_month

next_month

month (datetime.date object)

month_format

default = "%b", e.g., "jan", "feb", etc. re: time.strftime. "%m" is numbers.

month

from django.conf.urls.defaults import * from django.views.generic import list_detail, date_based, create_update from bookstore.models import Publisher, Author, Book book_info = { "queryset" : Book.objects.all(), "date_field" : "publication_date", } urlpatterns = patterns('', (r'^(?P\d{4})/(?P[a-z]{3})/$', date_based.archive_month, book_info), )

archive_year (_archive_year.html)

make_object_list

default = False (whether to retrieve full year list of objects)

year

from django.conf.urls.defaults import * from django.views.generic import list_detail, date_based, create_update from bookstore.models import Publisher, Author, Book book_info = { "queryset" : Book.objects.all(), "date_field" : "publication_date", } urlpatterns = patterns('', (r'^books/(?P\d{4})/?$', date_based.archive_year, book_info), )

archive_index (_archive.html)

latest

date_list (list of datetime.date objects)

template_object_name (?)

num_latest

default = 15

allow_future

default = False (allows publication of post-dated objects)

date_field

from django.conf.urls.defaults import * from django.views.generic import list_detail, date_based, create_update from bookstore.models import Publisher, Author, Book book_info = { "queryset" : Book.objects.all(), "date_field" : "publication_date", } urlpatterns = patterns('', (r'^books/$', date_based.archive_index, book_info), )

list_detail.object_detail. (_detail.html)

'object'

default name = 'object', e.g., override with template_object_name = 'foo', then object name will be 'foo'.

commonargs (6)

allow_empty (?)

template_name_field

fieldname whose value names the template to use, i.e., 'the_template' --> 'foo.html' --> generic view using foo.html.

or

slug + slug_field

object_id

from django.conf.urls.defaults import * from django.views.generic import list_detail, date_based, create_update from bookstore.models import Publisher, Author, Book author_detail_info = { "queryset" : Author.objects.all(), "template_object_name" : "author", } urlpatterns = patterns('', (r'^authors/(?P\d+)/$', list_detail.object_detail, author_detail_info), )

list_detail.object_list. (_list.html)
context

is_paginated

hits

pages

previous

next

page

has_previous

has_next

results_per_page

using page string paramater (GET), or page variable (URLconf)

/objects/?page=3

author_detail_info = { "queryset" : Author.objects.all(), "template_object_name" : "author", } urlpatterns = patterns('', (r'^objects/page(?P[0-9]+)/$', 'object_list', dict(info_dict)), )

object_list

commonargs (7)

template_object_name

template_name

template_loader

mimetype

extra_context

context_processors

allow_empty

optargs

paginate_by

reqargs

queryset

URLconf example

from django.conf.urls.defaults import * from django.views.generic import list_detail, date_based, create_update from bookstore.models import Publisher, Author, Book author_list_info = { 'queryset' : Author.objects.all(), 'allow_empty': True, } urlpatterns = patterns('', (r'authors/$', list_detail.object_list, author_list_info), )

Simple

redirect_to
urlpatterns = patterns('django.views.generic.simple', ('^foo/(?p\d+)/$', 'redirect_to', {'url': '/bar/%(id)s/'}), ('^bar/$', 'redirect_to', {'url': None}), )
direct_to_template
urlpatterns = patterns('django.views.generic.simple', (r'^foo/$', 'direct_to_template', {'template': 'foo_index.html'}), (r'^foo/(?P\d+)/$', 'direct_to_template', {'template': 'foo_detail.html'}), )

URLconf

from django.conf.urls.defaults import * from django_website.apps.blog.models import Entry info_dict = { 'queryset': Entry.objects.all(), 'date_field': 'pub_date', } urlpatterns = patterns('django.views.generic.date_based', (r'^(?P\d{4})/(?P[a-z]{3})/(?P\w{1,2})/(?P[-\w]+)/$', 'object_detail', dict(info_dict, slug_field='slug')), (r'^(?P\d{4})/(?P[a-z]{3})/(?P\w{1,2})/$', 'archive_day', info_dict), (r'^(?P\d{4})/(?P[a-z]{3})/$', 'archive_month', info_dict), (r'^(?P\d{4})/$', 'archive_year', info_dict), (r'^/?$', 'archive_index', info_dict), )