在django中保存或显示表单数据的最简单方法

时间:2013-07-14 01:05:42

标签: python django django-forms django-views

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

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

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)

1 个答案:

答案 0 :(得分:2)

您可以使用ModelForm来实现此目的。

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)