Atma
Atma

Reputation: 29767

simplest way to save or display data for form in django

I have the following code in a view for the purpose of handling the display, save, or update of data.

The code looks unruly and seems like it can be simplified. What can I do to accomplish the requirements above while not repeating myself and have as simple logic as possible?

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)

Upvotes: 3

Views: 2999

Answers (1)

karthikr
karthikr

Reputation: 99620

You can use a ModelForm for this purpose.

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)

Upvotes: 2

Related Questions