defform_invalid(self,form):"""If the form is invalid, render the invalid form."""returnself.render_to_response(self.get_context_data(form=form))
ModelFormMixin
If the form is valid, save the associated model.
123
124
125
126
defform_valid(self,form):"""If the form is valid, save the associated model."""self.object=form.save()returnsuper().form_valid(form)
FormMixin
If the form is valid, redirect to the supplied URL.
55
56
57
defform_valid(self,form):"""If the form is valid, redirect to the supplied URL."""returnHttpResponseRedirect(self.get_success_url())
FormMixin
Insert the form into the context dict.
63
64
65
66
67
defget_context_data(self,**kwargs):"""Insert the form into the context dict."""if'form'notinkwargs:kwargs['form']=self.get_form()returnsuper().get_context_data(**kwargs)
SingleObjectMixin
Insert the single object into the context dict.
91
92
93
94
95
96
97
98
99
100
defget_context_data(self,**kwargs):"""Insert the single object into the context dict."""context={}ifself.object:context['object']=self.objectcontext_object_name=self.get_context_object_name(self.object)ifcontext_object_name:context[context_object_name]=self.objectcontext.update(kwargs)returnsuper().get_context_data(**context)
defget_context_object_name(self,obj):"""Get the name to use for the object."""ifself.context_object_name:returnself.context_object_nameelifisinstance(obj,models.Model):returnobj._meta.model_nameelse:returnNone
Return an instance of the form to be used in this view.
29
30
31
32
33
defget_form(self,form_class=None):"""Return an instance of the form to be used in this view."""ifform_classisNone:form_class=self.get_form_class()returnform_class(**self.get_form_kwargs())
defget_form_class(self):"""Return the form class to use in this view."""ifself.fieldsisnotNoneandself.form_class:raiseImproperlyConfigured("Specifying both 'fields' and 'form_class' is not permitted.")ifself.form_class:returnself.form_classelse:ifself.modelisnotNone:# If a model has been explicitly provided, use itmodel=self.modelelifgetattr(self,'object',None)isnotNone:# If this view is operating on a single object, use# the class of that objectmodel=self.object.__class__else:# Try to get a queryset and extract the model class# from thatmodel=self.get_queryset().modelifself.fieldsisNone:raiseImproperlyConfigured("Using ModelFormMixin (base class of %s) without ""the 'fields' attribute is prohibited."%self.__class__.__name__)returnmodel_forms.modelform_factory(model,fields=self.fields)
FormMixin
Return the form class to use.
25
26
27
defget_form_class(self):"""Return the form class to use."""returnself.form_class
ModelFormMixin
Return the keyword arguments for instantiating the form.
103
104
105
106
107
108
defget_form_kwargs(self):"""Return the keyword arguments for instantiating the form."""kwargs=super().get_form_kwargs()ifhasattr(self,'object'):kwargs.update({'instance':self.object})returnkwargs
FormMixin
Return the keyword arguments for instantiating the form.
35
36
37
38
39
40
41
42
43
44
45
46
defget_form_kwargs(self):"""Return the keyword arguments for instantiating the form."""kwargs={'initial':self.get_initial(),'prefix':self.get_prefix(),}ifself.request.methodin('POST','PUT'):kwargs.update({'data':self.request.POST,'files':self.request.FILES,})returnkwargs
Return the initial data to use for forms on this view.
17
18
19
defget_initial(self):"""Return the initial data to use for forms on this view."""returnself.initial.copy()
Return the object the view is displaying.
Require `self.queryset` and a `pk` or `slug` argument in the URLconf.
Subclasses can override this to return any object.
defget_object(self,queryset=None):""" Return the object the view is displaying. Require `self.queryset` and a `pk` or `slug` argument in the URLconf. Subclasses can override this to return any object. """# Use a custom queryset if provided; this is required for subclasses# like DateDetailViewifquerysetisNone:queryset=self.get_queryset()# Next, try looking up by primary key.pk=self.kwargs.get(self.pk_url_kwarg)slug=self.kwargs.get(self.slug_url_kwarg)ifpkisnotNone:queryset=queryset.filter(pk=pk)# Next, try looking up by slug.ifslugisnotNoneand(pkisNoneorself.query_pk_and_slug):slug_field=self.get_slug_field()queryset=queryset.filter(**{slug_field:slug})# If none of those are defined, it's an error.ifpkisNoneandslugisNone:raiseAttributeError("Generic detail view %s must be called with either an object ""pk or a slug in the URLconf."%self.__class__.__name__)try:# Get the single item from the filtered querysetobj=queryset.get()exceptqueryset.model.DoesNotExist:raiseHttp404(_("No %(verbose_name)s found matching the query")%{'verbose_name':queryset.model._meta.verbose_name})returnobj
Return the prefix to use for forms.
21
22
23
defget_prefix(self):"""Return the prefix to use for forms."""returnself.prefix
Return the `QuerySet` that will be used to look up the object.
This method is called by the default implementation of get_object() and
may not be called if get_object() is overridden.
defget_queryset(self):""" Return the `QuerySet` that will be used to look up the object. This method is called by the default implementation of get_object() and may not be called if get_object() is overridden. """ifself.querysetisNone:ifself.model:returnself.model._default_manager.all()else:raiseImproperlyConfigured("%(cls)s is missing a QuerySet. Define ""%(cls)s.model, %(cls)s.queryset, or override ""%(cls)s.get_queryset()."%{'cls':self.__class__.__name__})returnself.queryset.all()
Get the name of a slug field to be used to look up by slug.
78
79
80
defget_slug_field(self):"""Get the name of a slug field to be used to look up by slug."""returnself.slug_field
ModelFormMixin
Return the URL to redirect to after processing a valid form.
110
111
112
113
114
115
116
117
118
119
120
121
defget_success_url(self):"""Return the URL to redirect to after processing a valid form."""ifself.success_url:url=self.success_url.format(**self.object.__dict__)else:try:url=self.object.get_absolute_url()exceptAttributeError:raiseImproperlyConfigured("No URL to redirect to. Either provide a url or define"" a get_absolute_url method on the Model.")returnurl
FormMixin
Return the URL to redirect to after processing a valid form.
49
50
51
52
53
defget_success_url(self):"""Return the URL to redirect to after processing a valid form."""ifnotself.success_url:raiseImproperlyConfigured("No URL to redirect to. Provide a success_url.")returnstr(self.success_url)# success_url may be lazy