Generic views (Visões genéricas)¶
Escrever aplicações Web pode ser monotono, pois nós repetimos certos padrões repetidamente. No Django, os mais comuns dentre esses padrões são abstraidos dentro de “generic views” que permitem você rapidamente fornecer views comuns de um objeto sem precisar escrever qualquer código Python.
Uma introdução geral d generic views pode ser encontrado em topic guide.
Esta referência contém detalhes das generic views embutidas do Django, junto com
uma lista de todos os argumentos que uma generic view espera. Lembre-se que
argumentos podem vir tanto de uma URL quanto de infomações adicionais num
dicionário extra-context
.
A maioria dos generic views requer a chave queryset
, que é uma instância do
QuerySet
; veja Fazendo consultas para mais informações sobre objetos
QuerySet
.
“Simple” generic views¶
O módulo django.views.generic.simple
contém views simples para manipular
alguns casos comuns: renderizar um template quando nenhuma view lógica é
necessária, e emitir redirecionamentos.
django.views.generic.simple.direct_to_template
¶
Descrição:
Renderiza um dado template, passando-o uma variável de template
{{ params }}
, que é um dicionário de parametros capturados numa URL.
Argumentos obrigatórios:
template
: O nome completo de um template a se usar.
Argumentos opcionais:
extra_context
: Um dicionário de valores para adicionar ao contexto do template. Por padrão, este é um dicionário vazio. Se um valor no dicionário for chamável, o generic view o chamará assim que estiver renderizando o template.mimetype
: O tipo MIME a ser usado no documento resultante. Por padrão é o valor da configuraçãoDEFAULT_CONTEXT_TYPE
.
Exemplo:
Dados os seguintes padrões de URL:
urlpatterns = patterns('django.views.generic.simple',
(r'^foo/$', 'direct_to_template', {'template': 'foo_index.html'}),
(r'^foo/(?P<id>\d+)/$', 'direct_to_template', {'template': 'foo_detail.html'}),
)
... uma requisição para /foo/
renderizaria o template foo_index.html
, e
uma requisição para /foo/15/
renderizaria o foo_detail.html
com uma
variável de contexto {{ params.id }}
que está setado como 15
.
django.views.generic.simple.redirect_to
¶
Descrição:
Redireciona para uma dada URL.
A dada URL pode conter strings na forma de dicionário, que serão intercaladas
contra os parametros capturados na URL. Pois a interpolação de chaves é
sempre feita (mesmo se nenhum argumento for passado), qualquer caracter
"%"
na URL deve ser escrito como "%%"
assim o Python os converterá para
um único sinal de percentual na saída.
Se uma dada URL é None
, o Django retornará um HttpResponseGone
(410).
Argumentos obrigatórios:
url
: A URL para onde redirecionar, como uma string. OuNone
para lançar um erro HTTP 410 (Gone).
Exemplo:
Este exemplo redireciona de /foo/<id>/
para /bar/<id>/
:
urlpatterns = patterns('django.views.generic.simple',
('^foo/(?P<id>\d+)/$', 'redirect_to', {'url': '/bar/%(id)s/'}),
)
Este exemplo retorna um erro HTTP 410 para a requisição /bar/
:
urlpatterns = patterns('django.views.generic.simple',
('^bar/$', 'redirect_to', {'url': None}),
)
Este exemplo mostra como caracteres "%"
devem ser escritos na URL afim de
evitar confusão com os marcadores de strings do Python. Se a strings de
redirecionamento é escrita como "%7Ejacob/"
(com somente um %
), uma
exceção poderia ser lançada:
urlpatterns = patterns('django.views.generic.simple',
('^bar/$', 'redirect_to', {'url': '%%7Ejacob.'}),
)
Date-based generic views¶
Date-based generic views (in the module django.views.generic.date_based
)
are views for displaying drilldown pages for date-based data.
django.views.generic.date_based.archive_index
¶
Descrição:
A top-level index page showing the “latest” objects, by date. Objects with
a date in the future are not included unless you set allow_future
to
True
.
Argumentos obrigatórios:
queryset
: AQuerySet
of objects for which the archive serves.date_field
: The name of theDateField
orDateTimeField
in theQuerySet
‘s model that the date-based archive should use to determine the objects on the page.
Optional arguments:
num_latest
: The number of latest objects to send to the template context. By default, it’s 15.template_name
: The full name of a template to use in rendering the page. This lets you override the default template name (see below).template_loader
: The template loader to use when loading the template. By default, it’sdjango.template.loader
.extra_context
: A dictionary of values to add to the template context. By default, this is an empty dictionary. If a value in the dictionary is callable, the generic view will call it just before rendering the template.allow_empty
: A boolean specifying whether to display the page if no objects are available. If this isFalse
and no objects are available, the view will raise a 404 instead of displaying an empty page. By default, this isTrue
.context_processors
: A list of template-context processors to apply to the view’s template.mimetype
: The MIME type to use for the resulting document. Defaults to the value of theDEFAULT_CONTENT_TYPE
setting.allow_future
: A boolean specifying whether to include “future” objects on this page, where “future” means objects in which the field specified indate_field
is greater than the current date/time. By default, this isFalse
.
template_object_name
: Designates the name of the template variable to use in the template context. By default, this is'latest'
.
Template name:
If template_name
isn’t specified, this view will use the template
<app_label>/<model_name>_archive.html
by default, where:
<model_name>
is your model’s name in all lowercase. For a modelStaffMember
, that’d bestaffmember
.<app_label>
is the right-most part of the full Python path to your model’s app. For example, if your model lives inapps/blog/models.py
, that’d beblog
.
Template context:
In addition to extra_context
, the template’s context will be:
date_list
: A list ofdatetime.date
objects representing all years that have objects available according toqueryset
. These are ordered in reverse. This is equivalent toqueryset.dates(date_field, 'year')[::-1]
.The behaviour depending ontemplate_object_name
is new in this version.
latest
: Thenum_latest
objects in the system, ordered descending bydate_field
. For example, ifnum_latest
is10
, thenlatest
will be a list of the latest 10 objects inqueryset
.This variable’s name depends on the
template_object_name
parameter, which is'latest'
by default. Iftemplate_object_name
is'foo'
, this variable’s name will befoo
.
django.views.generic.date_based.archive_year
¶
Descrição:
A yearly archive page showing all available months in a given year. Objects
with a date in the future are not displayed unless you set allow_future
to True
.
Argumentos obrigatórios:
year
: The four-digit year for which the archive serves.queryset
: AQuerySet
of objects for which the archive serves.date_field
: The name of theDateField
orDateTimeField
in theQuerySet
‘s model that the date-based archive should use to determine the objects on the page.
Optional arguments:
template_name
: The full name of a template to use in rendering the page. This lets you override the default template name (see below).template_loader
: The template loader to use when loading the template. By default, it’sdjango.template.loader
.extra_context
: A dictionary of values to add to the template context. By default, this is an empty dictionary. If a value in the dictionary is callable, the generic view will call it just before rendering the template.allow_empty
: A boolean specifying whether to display the page if no objects are available. If this isFalse
and no objects are available, the view will raise a 404 instead of displaying an empty page. By default, this isFalse
.context_processors
: A list of template-context processors to apply to the view’s template.template_object_name
: Designates the name of the template variable to use in the template context. By default, this is'object'
. The view will append'_list'
to the value of this parameter in determining the variable’s name.make_object_list
: A boolean specifying whether to retrieve the full list of objects for this year and pass those to the template. IfTrue
, this list of objects will be made available to the template asobject_list
. (The nameobject_list
may be different; see the docs forobject_list
in the “Template context” section below.) By default, this isFalse
.mimetype
: The MIME type to use for the resulting document. Defaults to the value of theDEFAULT_CONTENT_TYPE
setting.allow_future
: A boolean specifying whether to include “future” objects on this page, where “future” means objects in which the field specified indate_field
is greater than the current date/time. By default, this isFalse
.
Template name:
If template_name
isn’t specified, this view will use the template
<app_label>/<model_name>_archive_year.html
by default.
Template context:
In addition to extra_context
, the template’s context will be:
date_list
: A list ofdatetime.date
objects representing all months that have objects available in the given year, according toqueryset
, in ascending order.year
: The given year, as a four-character string.object_list
: If themake_object_list
parameter isTrue
, this will be set to a list of objects available for the given year, ordered by the date field. This variable’s name depends on thetemplate_object_name
parameter, which is'object'
by default. Iftemplate_object_name
is'foo'
, this variable’s name will befoo_list
.If
make_object_list
isFalse
,object_list
will be passed to the template as an empty list.
django.views.generic.date_based.archive_month
¶
Descrição:
A monthly archive page showing all objects in a given month. Objects with a
date in the future are not displayed unless you set allow_future
to
True
.
Argumentos obrigatórios:
year
: The four-digit year for which the archive serves (a string).month
: The month for which the archive serves, formatted according to themonth_format
argument.queryset
: AQuerySet
of objects for which the archive serves.date_field
: The name of theDateField
orDateTimeField
in theQuerySet
‘s model that the date-based archive should use to determine the objects on the page.
Optional arguments:
month_format
: A format string that regulates what format themonth
parameter uses. This should be in the syntax accepted by Python’stime.strftime
. (See the strftime docs.) It’s set to"%b"
by default, which is a three-letter month abbreviation. To change it to use numbers, use"%m"
.template_name
: The full name of a template to use in rendering the page. This lets you override the default template name (see below).template_loader
: The template loader to use when loading the template. By default, it’sdjango.template.loader
.extra_context
: A dictionary of values to add to the template context. By default, this is an empty dictionary. If a value in the dictionary is callable, the generic view will call it just before rendering the template.allow_empty
: A boolean specifying whether to display the page if no objects are available. If this isFalse
and no objects are available, the view will raise a 404 instead of displaying an empty page. By default, this isFalse
.context_processors
: A list of template-context processors to apply to the view’s template.template_object_name
: Designates the name of the template variable to use in the template context. By default, this is'object'
. The view will append'_list'
to the value of this parameter in determining the variable’s name.mimetype
: The MIME type to use for the resulting document. Defaults to the value of theDEFAULT_CONTENT_TYPE
setting.allow_future
: A boolean specifying whether to include “future” objects on this page, where “future” means objects in which the field specified indate_field
is greater than the current date/time. By default, this isFalse
.
Template name:
If template_name
isn’t specified, this view will use the template
<app_label>/<model_name>_archive_month.html
by default.
Template context:
In addition to extra_context
, the template’s context will be:
month
: Adatetime.date
object representing the given month.next_month
: Adatetime.date
object representing the first day of the next month. If the next month is in the future, this will beNone
.previous_month
: Adatetime.date
object representing the first day of the previous month. Unlikenext_month
, this will never beNone
.object_list
: A list of objects available for the given month. This variable’s name depends on thetemplate_object_name
parameter, which is'object'
by default. Iftemplate_object_name
is'foo'
, this variable’s name will befoo_list
.
django.views.generic.date_based.archive_week
¶
Descrição:
A weekly archive page showing all objects in a given week. Objects with a date
in the future are not displayed unless you set allow_future
to True
.
Argumentos obrigatórios:
year
: The four-digit year for which the archive serves (a string).week
: The week of the year for which the archive serves (a string). Weeks start with Sunday.queryset
: AQuerySet
of objects for which the archive serves.date_field
: The name of theDateField
orDateTimeField
in theQuerySet
‘s model that the date-based archive should use to determine the objects on the page.
Optional arguments:
template_name
: The full name of a template to use in rendering the page. This lets you override the default template name (see below).template_loader
: The template loader to use when loading the template. By default, it’sdjango.template.loader
.extra_context
: A dictionary of values to add to the template context. By default, this is an empty dictionary. If a value in the dictionary is callable, the generic view will call it just before rendering the template.allow_empty
: A boolean specifying whether to display the page if no objects are available. If this isFalse
and no objects are available, the view will raise a 404 instead of displaying an empty page. By default, this isTrue
.context_processors
: A list of template-context processors to apply to the view’s template.template_object_name
: Designates the name of the template variable to use in the template context. By default, this is'object'
. The view will append'_list'
to the value of this parameter in determining the variable’s name.mimetype
: The MIME type to use for the resulting document. Defaults to the value of theDEFAULT_CONTENT_TYPE
setting.allow_future
: A boolean specifying whether to include “future” objects on this page, where “future” means objects in which the field specified indate_field
is greater than the current date/time. By default, this isFalse
.
Template name:
If template_name
isn’t specified, this view will use the template
<app_label>/<model_name>_archive_week.html
by default.
Template context:
In addition to extra_context
, the template’s context will be:
week
: Adatetime.date
object representing the first day of the given week.object_list
: A list of objects available for the given week. This variable’s name depends on thetemplate_object_name
parameter, which is'object'
by default. Iftemplate_object_name
is'foo'
, this variable’s name will befoo_list
.
django.views.generic.date_based.archive_day
¶
Descrição:
A day archive page showing all objects in a given day. Days in the future throw
a 404 error, regardless of whether any objects exist for future days, unless
you set allow_future
to True
.
Argumentos obrigatórios:
year
: The four-digit year for which the archive serves (a string).month
: The month for which the archive serves, formatted according to themonth_format
argument.day
: The day for which the archive serves, formatted according to theday_format
argument.queryset
: AQuerySet
of objects for which the archive serves.date_field
: The name of theDateField
orDateTimeField
in theQuerySet
‘s model that the date-based archive should use to determine the objects on the page.
Optional arguments:
month_format
: A format string that regulates what format themonth
parameter uses. This should be in the syntax accepted by Python’stime.strftime
. (See the strftime docs.) It’s set to"%b"
by default, which is a three-letter month abbreviation. To change it to use numbers, use"%m"
.day_format
: Likemonth_format
, but for theday
parameter. It defaults to"%d"
(day of the month as a decimal number, 01-31).template_name
: The full name of a template to use in rendering the page. This lets you override the default template name (see below).template_loader
: The template loader to use when loading the template. By default, it’sdjango.template.loader
.extra_context
: A dictionary of values to add to the template context. By default, this is an empty dictionary. If a value in the dictionary is callable, the generic view will call it just before rendering the template.allow_empty
: A boolean specifying whether to display the page if no objects are available. If this isFalse
and no objects are available, the view will raise a 404 instead of displaying an empty page. By default, this isFalse
.context_processors
: A list of template-context processors to apply to the view’s template.template_object_name
: Designates the name of the template variable to use in the template context. By default, this is'object'
. The view will append'_list'
to the value of this parameter in determining the variable’s name.mimetype
: The MIME type to use for the resulting document. Defaults to the value of theDEFAULT_CONTENT_TYPE
setting.allow_future
: A boolean specifying whether to include “future” objects on this page, where “future” means objects in which the field specified indate_field
is greater than the current date/time. By default, this isFalse
.
Template name:
If template_name
isn’t specified, this view will use the template
<app_label>/<model_name>_archive_day.html
by default.
Template context:
In addition to extra_context
, the template’s context will be:
day
: Adatetime.date
object representing the given day.next_day
: Adatetime.date
object representing the next day. If the next day is in the future, this will beNone
.previous_day
: Adatetime.date
object representing the given day. Unlikenext_day
, this will never beNone
.object_list
: A list of objects available for the given day. This variable’s name depends on thetemplate_object_name
parameter, which is'object'
by default. Iftemplate_object_name
is'foo'
, this variable’s name will befoo_list
.
django.views.generic.date_based.archive_today
¶
Descrição:
A day archive page showing all objects for today. This is exactly the same as
archive_day
, except the year
/month
/day
arguments are not used,
and today’s date is used instead.
django.views.generic.date_based.object_detail
¶
Descrição:
A page representing an individual object. If the object has a date value in the
future, the view will throw a 404 error by default, unless you set
allow_future
to True
.
Argumentos obrigatórios:
year
: The object’s four-digit year (a string).month
: The object’s month , formatted according to themonth_format
argument.day
: The object’s day , formatted according to theday_format
argument.queryset
: AQuerySet
that contains the object.date_field
: The name of theDateField
orDateTimeField
in theQuerySet
‘s model that the generic view should use to look up the object according toyear
,month
andday
.Either
object_id
or (slug
andslug_field
) is required.If you provide
object_id
, it should be the value of the primary-key field for the object being displayed on this page.Otherwise,
slug
should be the slug of the given object, andslug_field
should be the name of the slug field in theQuerySet
‘s model. By default,slug_field
is'slug'
.
Optional arguments:
month_format
: A format string that regulates what format themonth
parameter uses. This should be in the syntax accepted by Python’stime.strftime
. (See the strftime docs.) It’s set to"%b"
by default, which is a three-letter month abbreviation. To change it to use numbers, use"%m"
.day_format
: Likemonth_format
, but for theday
parameter. It defaults to"%d"
(day of the month as a decimal number, 01-31).template_name
: The full name of a template to use in rendering the page. This lets you override the default template name (see below).template_name_field
: The name of a field on the object whose value is the template name to use. This lets you store template names in the data. In other words, if your object has a field'the_template'
that contains a string'foo.html'
, and you settemplate_name_field
to'the_template'
, then the generic view for this object will use the template'foo.html'
.It’s a bit of a brain-bender, but it’s useful in some cases.
template_loader
: The template loader to use when loading the template. By default, it’sdjango.template.loader
.extra_context
: A dictionary of values to add to the template context. By default, this is an empty dictionary. If a value in the dictionary is callable, the generic view will call it just before rendering the template.context_processors
: A list of template-context processors to apply to the view’s template.template_object_name
: Designates the name of the template variable to use in the template context. By default, this is'object'
.mimetype
: The MIME type to use for the resulting document. Defaults to the value of theDEFAULT_CONTENT_TYPE
setting.allow_future
: A boolean specifying whether to include “future” objects on this page, where “future” means objects in which the field specified indate_field
is greater than the current date/time. By default, this isFalse
.
Template name:
If template_name
isn’t specified, this view will use the template
<app_label>/<model_name>_detail.html
by default.
Template context:
In addition to extra_context
, the template’s context will be:
object
: The object. This variable’s name depends on thetemplate_object_name
parameter, which is'object'
by default. Iftemplate_object_name
is'foo'
, this variable’s name will befoo
.
List/detail generic views¶
The list-detail generic-view framework (in the
django.views.generic.list_detail
module) is similar to the date-based one,
except the former simply has two views: a list of objects and an individual
object page.
django.views.generic.list_detail.object_list
¶
Descrição:
A page representing a list of objects.
Argumentos obrigatórios:
queryset
: AQuerySet
that represents the objects.
Optional arguments:
paginate_by
: An integer specifying how many objects should be displayed per page. If this is given, the view will paginate objects withpaginate_by
objects per page. The view will expect either apage
query string parameter (viaGET
) or apage
variable specified in the URLconf. See Notes on pagination below.page
: The current page number, as an integer, or the string'last'
. This is 1-based. See Notes on pagination below.template_name
: The full name of a template to use in rendering the page. This lets you override the default template name (see below).template_loader
: The template loader to use when loading the template. By default, it’sdjango.template.loader
.extra_context
: A dictionary of values to add to the template context. By default, this is an empty dictionary. If a value in the dictionary is callable, the generic view will call it just before rendering the template.allow_empty
: A boolean specifying whether to display the page if no objects are available. If this isFalse
and no objects are available, the view will raise a 404 instead of displaying an empty page. By default, this isTrue
.context_processors
: A list of template-context processors to apply to the view’s template.template_object_name
: Designates the name of the template variable to use in the template context. By default, this is'object'
. The view will append'_list'
to the value of this parameter in determining the variable’s name.mimetype
: The MIME type to use for the resulting document. Defaults to the value of theDEFAULT_CONTENT_TYPE
setting.
Template name:
If template_name
isn’t specified, this view will use the template
<app_label>/<model_name>_list.html
by default.
Template context:
paginator
and page_obj
context variables are new.In addition to extra_context
, the template’s context will be:
object_list
: The list of objects. This variable’s name depends on thetemplate_object_name
parameter, which is'object'
by default. Iftemplate_object_name
is'foo'
, this variable’s name will befoo_list
.is_paginated
: A boolean representing whether the results are paginated. Specifically, this is set toFalse
if the number of available objects is less than or equal topaginate_by
.
If the results are paginated, the context will contain these extra variables:
paginator
: An instance ofdjango.core.paginator.Paginator
.page_obj
: An instance ofdjango.core.paginator.Page
.
Notes on pagination¶
If paginate_by
is specified, Django will paginate the results. You can
specify the page number in the URL in one of two ways:
Use the
page
parameter in the URLconf. For example, this is what your URLconf might look like:(r'^objects/page(?P<page>[0-9]+)/$', 'object_list', dict(info_dict))
Pass the page number via the
page
query-string parameter. For example, a URL would look like this:/objects/?page=3
To loop over all the available page numbers, use the
page_range
variable. You can iterate over the list provided bypage_range
to create a link to every page of results.
These values and lists are 1-based, not 0-based, so the first page would be
represented as page 1
.
For more on pagination, read the pagination documentation.
As a special case, you are also permitted to use last
as a value for
page
:
/objects/?page=last
This allows you to access the final page of results without first having to determine how many pages there are.
Note that page
must be either a valid page number or the value last
;
any other value for page
will result in a 404 error.
django.views.generic.list_detail.object_detail
¶
A page representing an individual object.
Descrição:
A page representing an individual object.
Argumentos obrigatórios:
queryset
: AQuerySet
that contains the object.Either
object_id
or (slug
andslug_field
) is required.If you provide
object_id
, it should be the value of the primary-key field for the object being displayed on this page.Otherwise,
slug
should be the slug of the given object, andslug_field
should be the name of the slug field in theQuerySet
‘s model. By default,slug_field
is'slug'
.
Optional arguments:
template_name
: The full name of a template to use in rendering the page. This lets you override the default template name (see below).template_name_field
: The name of a field on the object whose value is the template name to use. This lets you store template names in the data. In other words, if your object has a field'the_template'
that contains a string'foo.html'
, and you settemplate_name_field
to'the_template'
, then the generic view for this object will use the template'foo.html'
.It’s a bit of a brain-bender, but it’s useful in some cases.
template_loader
: The template loader to use when loading the template. By default, it’sdjango.template.loader
.extra_context
: A dictionary of values to add to the template context. By default, this is an empty dictionary. If a value in the dictionary is callable, the generic view will call it just before rendering the template.context_processors
: A list of template-context processors to apply to the view’s template.template_object_name
: Designates the name of the template variable to use in the template context. By default, this is'object'
.mimetype
: The MIME type to use for the resulting document. Defaults to the value of theDEFAULT_CONTENT_TYPE
setting.
Template name:
If template_name
isn’t specified, this view will use the template
<app_label>/<model_name>_detail.html
by default.
Template context:
In addition to extra_context
, the template’s context will be:
object
: The object. This variable’s name depends on thetemplate_object_name
parameter, which is'object'
by default. Iftemplate_object_name
is'foo'
, this variable’s name will befoo
.
Create/update/delete generic views¶
The django.views.generic.create_update
module contains a set of functions
for creating, editing and deleting objects.
django.views.generic.create_update.create_object
and
django.views.generic.create_update.update_object
now use the new forms
library to build and display the form.
django.views.generic.create_update.create_object
¶
Descrição:
A page that displays a form for creating an object, redisplaying the form with validation errors (if there are any) and saving the object.
Argumentos obrigatórios:
Either
form_class
ormodel
is required.If you provide
form_class
, it should be adjango.forms.ModelForm
subclass. Use this argument when you need to customize the model’s form. See the ModelForm docs for more information.Otherwise,
model
should be a Django model class and the form used will be a standardModelForm
formodel
.
Optional arguments:
post_save_redirect
: A URL to which the view will redirect after saving the object. By default, it’sobject.get_absolute_url()
.post_save_redirect
may contain dictionary string formatting, which will be interpolated against the object’s field attributes. For example, you could usepost_save_redirect="/polls/%(slug)s/"
.login_required
: A boolean that designates whether a user must be logged in, in order to see the page and save changes. This hooks into the Django authentication system. By default, this isFalse
.If this is
True
, and a non-logged-in user attempts to visit this page or save the form, Django will redirect the request to/accounts/login/
.template_name
: The full name of a template to use in rendering the page. This lets you override the default template name (see below).template_loader
: The template loader to use when loading the template. By default, it’sdjango.template.loader
.extra_context
: A dictionary of values to add to the template context. By default, this is an empty dictionary. If a value in the dictionary is callable, the generic view will call it just before rendering the template.context_processors
: A list of template-context processors to apply to the view’s template.
Template name:
If template_name
isn’t specified, this view will use the template
<app_label>/<model_name>_form.html
by default.
Template context:
In addition to extra_context
, the template’s context will be:
form
: Adjango.forms.ModelForm
instance representing the form for creating the object. This lets you refer to form fields easily in the template system.For example, if the model has two fields,
name
andaddress
:<form action="" method="post"> <p>{{ form.name.label_tag }} {{ form.name }}</p> <p>{{ form.address.label_tag }} {{ form.address }}</p> </form>
See the forms documentation for more information about using
Form
objects in templates.
django.views.generic.create_update.update_object
¶
Descrição:
A page that displays a form for editing an existing object, redisplaying the form with validation errors (if there are any) and saving changes to the object. This uses a form automatically generated from the object’s model class.
Argumentos obrigatórios:
Either
form_class
ormodel
is required.If you provide
form_class
, it should be adjango.forms.ModelForm
subclass. Use this argument when you need to customize the model’s form. See the ModelForm docs for more information.Otherwise,
model
should be a Django model class and the form used will be a standardModelForm
formodel
.Either
object_id
or (slug
andslug_field
) is required.If you provide
object_id
, it should be the value of the primary-key field for the object being displayed on this page.Otherwise,
slug
should be the slug of the given object, andslug_field
should be the name of the slug field in theQuerySet
‘s model. By default,slug_field
is'slug'
.
Optional arguments:
post_save_redirect
: A URL to which the view will redirect after saving the object. By default, it’sobject.get_absolute_url()
.post_save_redirect
may contain dictionary string formatting, which will be interpolated against the object’s field attributes. For example, you could usepost_save_redirect="/polls/%(slug)s/"
.login_required
: A boolean that designates whether a user must be logged in, in order to see the page and save changes. This hooks into the Django authentication system. By default, this isFalse
.If this is
True
, and a non-logged-in user attempts to visit this page or save the form, Django will redirect the request to/accounts/login/
.template_name
: The full name of a template to use in rendering the page. This lets you override the default template name (see below).template_loader
: The template loader to use when loading the template. By default, it’sdjango.template.loader
.extra_context
: A dictionary of values to add to the template context. By default, this is an empty dictionary. If a value in the dictionary is callable, the generic view will call it just before rendering the template.context_processors
: A list of template-context processors to apply to the view’s template.template_object_name
: Designates the name of the template variable to use in the template context. By default, this is'object'
.
Template name:
If template_name
isn’t specified, this view will use the template
<app_label>/<model_name>_form.html
by default.
Template context:
In addition to extra_context
, the template’s context will be:
form
: Adjango.forms.ModelForm
instance representing the form for editing the object. This lets you refer to form fields easily in the template system.For example, if the model has two fields,
name
andaddress
:<form action="" method="post"> <p>{{ form.name.label_tag }} {{ form.name }}</p> <p>{{ form.address.label_tag }} {{ form.address }}</p> </form>
See the forms documentation for more information about using
Form
objects in templates.object
: The original object being edited. This variable’s name depends on thetemplate_object_name
parameter, which is'object'
by default. Iftemplate_object_name
is'foo'
, this variable’s name will befoo
.
django.views.generic.create_update.delete_object
¶
Descrição:
A view that displays a confirmation page and deletes an existing object. The
given object will only be deleted if the request method is POST
. If this
view is fetched via GET
, it will display a confirmation page that should
contain a form that POSTs to the same URL.
Argumentos obrigatórios:
model
: The Django model class of the object that the form will create.Either
object_id
or (slug
andslug_field
) is required.If you provide
object_id
, it should be the value of the primary-key field for the object being displayed on this page.Otherwise,
slug
should be the slug of the given object, andslug_field
should be the name of the slug field in theQuerySet
‘s model. By default,slug_field
is'slug'
.post_delete_redirect
: A URL to which the view will redirect after deleting the object.
Optional arguments:
login_required
: A boolean that designates whether a user must be logged in, in order to see the page and save changes. This hooks into the Django authentication system. By default, this isFalse
.If this is
True
, and a non-logged-in user attempts to visit this page or save the form, Django will redirect the request to/accounts/login/
.template_name
: The full name of a template to use in rendering the page. This lets you override the default template name (see below).template_loader
: The template loader to use when loading the template. By default, it’sdjango.template.loader
.extra_context
: A dictionary of values to add to the template context. By default, this is an empty dictionary. If a value in the dictionary is callable, the generic view will call it just before rendering the template.context_processors
: A list of template-context processors to apply to the view’s template.template_object_name
: Designates the name of the template variable to use in the template context. By default, this is'object'
.
Template name:
If template_name
isn’t specified, this view will use the template
<app_label>/<model_name>_confirm_delete.html
by default.
Template context:
In addition to extra_context
, the template’s context will be:
object
: The original object that’s about to be deleted. This variable’s name depends on thetemplate_object_name
parameter, which is'object'
by default. Iftemplate_object_name
is'foo'
, this variable’s name will befoo
.