0

I have the following practical problem (related to Django/Python).

I'm trying to get the following in the most efficient piece of Python code ->

There are 2 items to be checked:

  1. Is the user logged in? if not show a login page, else check if the request is a post request.
  2. Is the request a post request? If not show a form, else handle the form

    def upload(request):
    if request.user.is_authenticated:
        if request.method == 'POST':
            form = forms.DocumentForm()
            return HttpResponse('Handle POST and LoggedIn Prefix Form Validation')
        else:
            return HttpResponse('POST but not logged in')
            return render(request, 'upload.html', {'form': form}
    else:
        return HttpResponse('Not Logged In Need to Make Error Landing Page')
    
BartD
  • 29
  • 1
  • 8

2 Answers2

0

i think this is quite pythonic...

def upload(request):
    if not request.user.is_authenticated:
        #return early
        return HttpResponse('Not Logged In Need to Make Error Landing Page')

    # this will only be reached if user authenticated
    if request.method == 'POST':
        form = forms.DocumentForm()
        return HttpResponse('Handle POST and LoggedIn Prefix Form Validation')
    else:
        pass # handle GET

If you need to check the authentication in multiple functions, consider using a decorator instead

@authenticated_users_only(request)
def upload(request):   
    if request.method == 'POST':
        form = forms.DocumentForm()
        return HttpResponse('Handle POST and LoggedIn Prefix Form Validation')
    else:
        pass # handle GET

If you don't know how to write a decorator yet - read this

Sebastian Loehner
  • 1,302
  • 7
  • 5
0

Avoid else when possible and use early return:

def upload(request):
    if request.user.is_authenticated:
        if request.method != 'POST':
            return HttpResponse('Not Logged In Need to Make Error Landing Page')
        form = forms.DocumentForm()
        return HttpResponse('Handle POST and LoggedIn Prefix Form Validation')

    if request.method == 'POST':
        return HttpResponse('POST but not logged in')
Juan Diego Godoy Robles
  • 14,447
  • 2
  • 38
  • 52
  • Thanks for the helpful hint here. Read some about early return and it obviously clarifies a lot. – BartD May 31 '18 at 07:55