[Answered ]-How to utilize django generic view?

1👍

Django’s generic views cover a lot of common use cases. For example:

  • CreateView – a view for creating an instance of a model
  • UpdateView – a view for updating an existing instance of a model
  • DeleteView – a view for deleting an existing instance of a model
  • DetailView – a view for displaying the details of an exsting instance of a model
  • ListView – a view for displaying a list of instances of a model

There are more around if you need them, and they cover the majority of views you are likely to need. You can also extend them to meet your needs quite easily. As a general rule of thumb, they make such a huge difference to how quickly you can get something built that I would recommend using them by default, and only switching over to writing your own views when absolutely necessary. If you haven’t yet learned them, I think doing so will be a very good investment of your time – you will make up the time spent very quickly. For a lot of view types, it’s just a case of specifying the model, setting up the URLs and the template, and you’re done.

If you need to pass through additional data, then you can extend the generic view in question and override the get_context_data() method. If the same needs to be applied to several different generic views, you can create a mixin that includes that method and include it in that generic view.

For views that include forms, like the CreateView and UpdateView, as Drewness said, you can pass through a ModelForm instance to tell it what form to use, and that form can itself be overriden, so you still have a lot of control over what the form will do. For instance, you might define the following form:

from django.forms import ModelForm

class CategoryForm(ModelForm):
    exclude = ['date_created']

And the following view

from django.views.generic.edit import CreateView

class CategoryCreateView(CreateView):
    model = Category
    form_class = CategoryForm

The Django tutorial covers generic views pretty well.

1👍

You can use Django’s ModelForm with a FormView.

Then all of the fields in your model will be available in your form and in your form view. You should also look at mixins. Mixins allow you to use combinations of class-based views.

Finally, if you want to use more than one form (model) in a view you can use a FormSet.

Leave a comment