2

In Django, the canonical way of processing forms is:

if request.method == 'POST':
    form = SomeForm(request.POST)
    if form.is_valid():
        use the form data

I want to execute the same code whether there was no POST or the form was invalid - it's a few lines of code, so I'm wondering if there is a nicer way of doing this than having two duplicate else blocks (one for the inner if and one for the outer)?

3 Answers 3

6

Use a separate function:

if request.method != 'POST':
    return do_something_function_for_invalid(request)

form = SomeForm(request.POST)
if not form.is_valid():
    return do_something_function_for_invalid(request)

# do something

and then define do_something_function_for_invalid() as:

def do_something_function_for_invalid(request):
    # do something

    return response

Alternatively, use exception handling:

try:
    if request.method != 'POST':
        raise ValueError('invalid form')

    form = SomeForm(request.POST)
    if not form.is_valid():
        raise ValueError('not a POST request')

     # do something
except ValueError as ve:
    # handle ve exception, ve.args[0] is the error message
Sign up to request clarification or add additional context in comments.

7 Comments

You might even define do_something_function locally and don't worry about passing arguments.
@freakish: there is a (very small) cost when you do that; just define the function outside the view function and pass in arguments instead.
Here you have two duplicate else blocks that is what the OP is trying to avoid.
@furins: Reduced to less nesting, removing the else statements.
There's a simpler way of doing this, as I've demonstrated in my answer.
|
5

A very concise way that does not require a separate function, and doesn't repeat conditions:

form = SomeForm(request.POST) if request.method == 'POST' else None

if form and form.is_valid():
    # do your valid-submission stuff
else:
    # do your invalid-submission stuff

Comments

0

As simple as

if (request.method != 'POST') or (not SomeForm(request.POST).is_valid()):
   do something

4 Comments

-1: keeping reference to SomeForm object is probably crucial.
Please let the OP say that, he may just require this code in order to output a message
@furins You are suggesting that OP creates form but he's not using it anywhere neither in if nor else block? He doesn't have state it, it is obvious.
It's not stated so the only one who knows that is the OP. It may be a honeypot-like code to check if fake requests are provided to a given url

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.