[Answered ]-Should my forms in django be processed in a different view than the one that serves them?

1👍

Yes, that’s the way to go (you don’t need a else statement though). Django and other frameworks do this – the assumed default is GET, then you add a if statement for the POST method.

Don’t forget to return a redirect response in case you don’t want the form to be reposted. Also, if the form processing is long – you can use a separate method / service. Something like:

def my_view(request):
    form = SomeForm(data=request.POST or None)

    if request.method == 'POST':
        if form.is_valid():
            do_something(form) # form processing that could save a couple of objects, send notifications, etc.

            messages.success(request, "Some message.")
            return HttpResponseRedirect(request.path)

    return render(request, ".../template.html", locals())

This way, you keep the business logic separated and you can easily unit test it (in this example, you would unit test do_something(…)).

1👍

Yes, this is ok. This is what Django does normally. Note that the generic FormView has got get andpost methods.

(To understand how they’re called, read the dispatch method.)

👤meshy

Leave a comment