为了处理数据的显示、保存或更新,我在视图中有以下代码。
代码看起来不规则,似乎可以简化。我可以做些什么来完成上述要求,同时不重复自己并尽可能简单的逻辑?
def details(request, pk=None):
customer = request.user.customer
existing_detail = Detail()
detail_queryset = Detail.objects.filter(customer_id=customer.id)
if detail_queryset:
existing_detail = detail_queryset[0]
if request.method == 'POST':
form = detailForm(request.POST)
if form.is_valid():
pay_out = form.cleaned_data['title']
if detail_queryset:
existing_detail.title = title
existing_detail.save()
else:
detail = Detail(customer=customer, payoutType=title)
detail.save()
return HttpResponseRedirect('/settings/details/')
else:
if detail_queryset:
form = detailForm(initial={'title': existing_detail.title})
else:
form = detailForm()
context = {
'title':'details',
'view':'detail',
'form': form
}
return render(request, 'customers/detail.html', context)