python
python

Reputation: 4521

How to clean up multiple nested if statements inside views in Django

I am working on a Django Project, and one of the views look like this with multiple if else statements. Is there a way to clean up the code? I am relatively new to Django, and one of my friend suggested to use decorators. Could anyone point to me how to use decorators here? or clean up this code? Any links or study material would be great.

if req.method == 'GET':
....# do stuff
elif req.method == 'POST':
....form = Form(req.POST)
....if form.is_valid():
........response = some_api_call(form.cleaned_data)
........if can_foobar(response):
............return JsonResponse({"status": "success"})
........else:
............return JsonResponse({"status": "failure", "reason": "couldn't foobar"})
....else:
........return JsonResponse({"status": "failure", "reason": "form invalid"})

Upvotes: 1

Views: 741

Answers (1)

Agustín Lado
Agustín Lado

Reputation: 1095

When Django 1.4 came out (I think it was 1.4) they boasted a new feature called Class-based Views. What you are using right now is called Function-based views, and they're so outdated they don't even have a section of the Django documentation dedicated to them.

The documentation is great, but to sum it up class-based views are a way of organizing the code inside the view (which right now is in a function) in different sections by using Classes.

This brings two benefits over function-based views.

  1. Cleaner code by separating each piece of functionality in a different class. In its most basic form having a get method and a post method instead of an if-else structure.
  2. Code reuse by pooling together basic functionality inside different classes.

For example, how awesome would it be to have a class that automatically renders and returns a Form when get is called and automatically validates the Form and creates the object or whatever and redirects to a success page when everything goes OK?

Well, Django ships with these kind of abstractions, in this case FormView. What's better, FormView executes a method called form_valid when the Form is valid and form_invalid when it's not, presenting you with an ideal way to do what you want. Basically, the only code you'd have to write would be your some_api_call call and the JsonResponses!

(The example I gave with redirecting to a success URL is the default use of FormView, in which you just define said success_url. It's the second example in the docs).

PS: If you're doing JSON I HIGHLY recommend using Django Rest Framework, which is basically class-based views for API calls. It's just beautiful.

Upvotes: 3

Related Questions