Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Generic views allow you to write much shorter code.</p> <p>Compare:</p> <pre><code>from django.http import HttpResponse, HttpResponseRedirect, Http404 from django.shortcuts import render_to_response, get_object_or_404, redirect from myapp.models import Context def edit(request, item_id): object = get_object_or_404(Context, pk=item_id) if request.method == 'POST': form = ContextForm(request.POST, instance=object) if form.is_valid(): form.save() return redirect('myapp-context-index') else: form = ContextForm(instance=object) return render_to_response("myapp/context/edit.html", {'object': object, 'form': form}) </code></pre> <p>with:</p> <pre><code>from django.core import urlresolvers from django.views.generic.create_update import update_object from myapp.models import Context def edit(request, item_id): return update_object(request, object_id=item_id, form_class=ContextForm, template_name="myapp/context/edit.html", post_save_redirect=urlresolvers.reverse("myapp-context-index") ) </code></pre> <p>Like your normal views, they are just normal functions. It is possible to configure the view completely in the URLconf if you like, through I find this usage above a bit more clear.</p> <p>As a BONUS, you also get:</p> <ul> <li>Login authentication checks (pass <code>login_required=True</code>)</li> <li>Success status message from <code>django.contrib.messages</code>.</li> <li>Less code to check for errors.</li> <li>A default <code>ModelForm</code> when you provide a <code>model</code> parameter instead of <code>form_class</code>.</li> </ul> <p>The <code>template_name</code> has a default of "appname/model_form.html", but that's a bit too much for me.</p> <hr> <p>Here is the form class they both share:</p> <pre><code>class ContextForm(forms.ModelForm): """The form for a context""" class Meta: model = Context exclude = ('collection',) def save(self, commit=True): """Overwritten save to force collection_id to a value""" model = super(ContextForm, self).save(commit=False) model.collection_id = 1 if commit: model.save() return model </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload