Home > Enterprise >  Suggestions on improving a form view
Suggestions on improving a form view

Time:08-10

I'm building an app where the user enters data and then gets redirected to a page that shows results based on their input with some simple equations. However, every time I refresh the results page, a new model instance is saved on the database.

Is there another (more efficient and effective) way of passing the data from this view to another view where I have access to the instance of that model submitted through the form view? What's the Django way of passing form data to a view?

The only limitation is I don't want user authentication so using self.request.user is not an option unless it can be implemented in a way that doesn't require users to sign up and sign in.

I'm still somewhat new to Django so any pointers to obvious solutions that I'm overlooking would be greatly appreciated.

This is the view that processes the model form:

def createcalculation(request):
form = CalcForm()

if request.method == 'POST':
    form = CalcForm(request.POST)
    if form.is_valid():
        item = form.save()
        m_data = get_object_or_404(Calculate, id=item.id)
        context = {'c_data': form.cleaned_data, 'm_data': m_data}
        return render(request, 'calc/res_ca.html', context)

context = {'c_form': form}
return render(request, 'calc/calc.html', context)

CodePudding user response:

It is advisable to always do a redirect after a successful POST. Your code should look something like this:

from django.shortcuts import get_object_or_404, render, redirect
from django.urls import reverse
...

def createcalculation(request):
    form = CalcForm()

    if request.method == 'POST':
        form = CalcForm(request.POST)
        if form.is_valid():
            item = form.save()
            m_data = get_object_or_404(Calculate, id=item.id)
            context = {
                'c_data': form.cleaned_data,
                'm_data': m_data
            }
            return redirect(reverse('app_name:view_name', kwargs=context))

    context = {'c_form': form}
    return render(request, 'calc/calc.html', context)

You can pass the newly created item object in the context as well. Also, you should change app_name and view_name text to match your situation.

  • Related