[Django]-Best practice to design django forms for CRUD operations

3đź‘Ť

Your CRUD operations seems pretty straightforward, so in this case try using Django’s Class Based Generic Views.

As the doc states, this is one of the purposes they were created for:

Django’s generic views were developed take certain common idioms and
patterns found in view development and abstract them so that you can
quickly write common views of data without having to write too much
code.

We can recognize certain common tasks, like displaying a list of
objects, and write code that displays a list of any object. Then the
model in question can be passed as an extra argument to the URLconf.

Django ships with generic views to do the following:

  • Display list and detail pages for a single object.
  • Present date-based objects in year/month/day archive pages, associated detail, and “latest” pages.
  • Allow users to create, update, and delete objects – with or without authorization.

Then you can create its forms and have a well designed codebase.

👤marcanuy

1đź‘Ť

Class based views are the answer. With class based views:

from django.views.generic.edit import (CreateView, DeleteView, UpdateView)

class MyView(CreateView):
    model = MyModel

is enough to give you a working view. Replace CreateView with UpdateView and DeleteView. This gives you all the validation in your model and automatically saves the data. You can use a list view for listing your data. You override the methods in the views to change anything you need. With this way, you aren’t giving non-admins access to the admin interface. Keep the admin interface for admins. You should not be building whole websites in it.

Also, instead of using functions as views use the TemplateView instead from django.views.generic. It makes your code a lot cleaner. You can separate post from get, and have instance methods tied to your view.

👤kagronick

0đź‘Ť

If all you need is really a crud interface to django models, you may as well use the django.contrib.admin app which is designed to do exactly that. Just give users permissions to admin only the objects they need.

See https://docs.djangoproject.com/en/1.9/ref/contrib/admin/

👤Luca Corti

Leave a comment