Class Based Views – UpdateView Example

Yet another simple example. I basically just took the DeleteView example and changed a couple of things.

Before:

@permission_required('calendars.change_eventtype')
def update_type(request,id):
    return update_object(request,
                         model=EventType,
                         object_id=id,
                         template_name='eventtype_form.html',
                         post_save_redirect=reverse('list_type'),
                       extra_context = {'calendar_menu': CalendarName.menu.all()})

After:

class TypeUpdateView(UpdateView):
    template_name = 'eventtype_form.html'
    model = EventType
    
    def get_success_url(self):
        return reverse('list_type')
    
    ## Override dispatch to apply the permission decorator
    @method_decorator(permission_required('calendars.change_eventtype'))
    def dispatch(self, request, *args, **kwargs):
        return super(TypeUpdateView, self).dispatch(request, *args, **kwargs)
    
    ## Additional context
    def get_context_data(self, **kwargs):
        context = super(TypeUpdateView, self).get_context_data(**kwargs)
        context['calendar_menu'] = CalendarName.menu.all()
        return context 

With another example, the generic view declared a form_class instead of a model. The model declaration is not necessary since the related model is tied to the form in its meta section. However, in the class based generic view, both were required (or a queryset could have also been used). I guess the related model info doesn’t make its way back to the class. Hmmmm.