Reputation:
I am new to Django and not sure what the best way is to go about this. I am using a ModelForm to create forms for inserting/updating. However, my question is if I should have a single view for both operations, or if it is best to have two separate ones?
EXAMPLE SEPARATE VIEWS:
def insert(request):
form = ModelForm(request.POST or None)
if form.is_valid():
form.save()
return redirect('next_view')
context = { 'form': form}
return render(request, 'modelform.html', context)
def update(request, id):
instance = Model.objects.get(id=id)
form = ModelForm(request.POST or None, instance=instance)
if form.is_valid():
form.save()
return redirect('next_view')
context = { 'form': form}
return render(request, 'modelform.html', context)
EXAMPLE SINGLE VIEW
def modelform(request, id=False):
if id:
instance = Model.objects.get(id=id)
form = ModelForm(request.POST or None, instance=instance)
else:
form = ModelForm(request.POST or None)
if form.is_valid():
form.save()
return redirect('next_view')
context = { 'form': form}
return render(request, 'modelform.html', context)
What is the recommended way of doing this? I feel the combined view is simpler, but not sure what the best way is of doing this. Also, if there are any other comments on this code please let me know.
Using Django 2.0.
Upvotes: 1
Views: 367
Reputation: 4603
I would keep the two views separated, but use class based views instead (CreateView
and UpdateView
). These views already implement most of the functionality you have currently duplicated in your two views. A small example:
from django.views.generic import CreateView, UpdateView
class ModelCreateView(CreateView):
model = Model
form_class = ModelForm
success_url = reverse('next_view')
template_name = 'modelform.html'
class ModelUpdateView(UpdateView):
model = Model
form_class = ModelForm
success_url = reverse('next_view')
template_name = 'modelform.html'
With this solution you need to make a small change to your URLs. Instead of something like:
path('model/create/', views.insert, ..),
path('model/<int:pk>/update/', views.update, ..),
You now need to write something like:
path('model/create/', views.ModelCreateView.as_view(), ..),
path('model/<int:pk>/update/', views.ModelCreateView.as_view(), ..),
For more information on class-based views you can read the documentation.
Upvotes: 1