Search code examples
djangodjango-modelsdjango-viewsdjango-class-based-views

Django Class Based View for both Create and Update


Say I want to create a Class Based View which both updates and creates an object. From a previous question I worked out I could do one of the following things:

1) Use 2 generic views CreateView and UpdateView which I think would mean having two URL's pointing to two different classes.

2) Use a class based view which inherits base View, which I think would mean having two URL's pointing to just 1 class (I created which inherits View).

I have two questions:

a) Which is better?

b) ccbv.co.uk shows a base View, but I don't see any get, post etc methods documented, is this correct?


Solution

  • Why do you need to handle both create and update by a single View? It's much simpler to have two separate views, each inheriting from its respective generic view class. They can share the same form and template if you wish, and they're most likely served from different URLs, so I don't see what would you get by making it into a single view.

    So: use two views, one inheriting from CreateView and the other from UpdateView. These handle pretty much everything you might need, while the second approach would require you to reinvent the wheel yourself. If cases when you have some common "housekeeping" code that is used both when creating or updating objects, the option of using a mixin, or you can perhaps create your own view that covers both use cases, inheriting from both CreateView and UpdateView.