3

为了处理数据的显示、保存或更新,我在视图中有以下代码。

代码看起来不规则,似乎可以简化。我可以做些什么来完成上述要求,同时不重复自己并尽可能简单的逻辑?

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)
4

1 回答 1

2

ModelForm为此,您可以使用 a 。

class DetailsForm(forms.ModelForm):
    class Meta:
        model = Detail

@login_required
def details(request, pk=None):
    customer = request.user.customer

    try:
        existing_detail = Detail.objects.get(customer_id=customer.id)
    except:
        existing_detail = None

    details_form = DetailsForm(instance = existing_detail)

    if request.method == 'POST':
        form = DetailsForm(request.POST, instance=existing_details)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/settings/details/')
    context = {
        'title':'details',
        'view':'detail',
        'form': form
    }
    return render(request, 'customers/detail.html', context)
于 2013-07-14T02:07:17.860 回答