Django class based views in action - forms handling
Django class based views offer a wide range of features - supporting forms, objects lists and many more. In this article I'll show some of the class based views in action - those related to forms and object lists.
"Category" is quite plain, while for "Entry" we will need more complicated form with limited fields editable for the user - just to show the class based views in action.
You should check each view type documentation to get the methods and attributes it has via Mixins it inherits. For CreateView we need the model name, optionally our own template name and get_success_url (or success_url) with a url to which form will redirect.
Entry views are bit more complicated:
AddEntryView has a "get_form_kwargs" method defined. It's a very handy method for views handling forms. Via kwargs we can set initial object, get the POSTed data or pass additional data to the form object (like for custom validation, customized field values). In this case I set "instance" with the Entry object having values for every required field that isn't in the form:
DeleteView can be used for object deletion - it has a empty form and the template should ask for confirmation (like in admin panel delete actions).
UpdateView can be used to handle a form for editing given entry. If we won't define "queryset" it will try the default behavior - using "pk" variable from the URLs (named variable from urls are under self.kwargs, unnamed in self.args - like self.kwargs['pk']):
Sometimes to validate things you need the current logged in user object or other external data. You can pass them to the form through get_form_kwargs:And define __ini__ in the form class: In "clean" methods or other you can access the User object via self.current_user.