Insights from Our Experts

Blog image

Django Class-based generic views (UpdateView)

Author Image

Renjith Raj,Chief Technology Officer

A view that displays a form for editing an existing object, re displaying 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 (unless a form class is manually specified).

BaseUpdateView implements the same behavior as UpdateView, but doesn’t include the TemplateResponseMixin.

built in methods in class UpdateView

get_object(self, queryset=None) : - Django automatically calls get_object() to get the object that needs to be updated by your form
get_queryset(self)  :- Returns the queryset that will be used to retrieve the object that this view will display. By default, get_queryset() returns the value of the queryset attribute if it is set, otherwise it constructs a QuerySet by calling the all() method on the model attribute’s default manager.
get_slug_field(self) :
def get_context_object_name(self, obj)
def get_context_data(self, **kwargs)

Example Code :

from django.views.generic import UpdateView

class UpdateBook(UpdateView):
   model = Book
   form_class = BookForm
   template_name = 'create_form.html'
   success_url = '/books/'

from django.conf.urls import *
from library.views import UpdateBook
urlpatterns = patterns('',
url('^update_book/(?P<pk>[\w-]+)$', UpdateBook.as_view(), name='update_book'),
# you MUST pass a pk or slug param to this view

I Need

Help for