Reputation: 81
I am building a django web application for admin which mainly involves CRUD (create,read, update and delete) operations. I need suggestions/best practices to design the forms. I am new to django and python and need experts suggestions. Currently I have created different methods in the views like
def create(request):
--logic to add
return HttpResponseRedirect('/createproduct')
def delete(request,obj_id):
result=products.objects.get(product_type=object_id).delete()
return HttpResponseRedirect('/listobjects/')
def getObjects(request):
products= products.objects.order_by('product_type')
return render(request,'getProducts.html',
{'results': products})
and my urls.py is like below
url(r'^createproduct/$',create),
url(r'^listobjects/',getObjects),
url(r'^deleteproduct/(?P<object_id>\d+)/$',delete)
Upvotes: 3
Views: 5029
Reputation: 23982
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:
Then you can create its forms and have a well designed codebase.
Upvotes: 3
Reputation: 545
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/
Upvotes: 0
Reputation: 2688
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.
Upvotes: 1