[Answer]-Django return to index when there is no next= in URL

1👍

The problem is that if you don’t have a next parameter specified in the GET parameters, it will be an empty string, but it will still be defined. request.POST.get('next') will never fail, but simply return an empty string. You can do the following:

def login_user(request):
    login_form = LoginForm(request.POST or None)
    if request.POST and login_form.is_valid():
        user = login_form.login(request)
        if user:
            login(request, user)
            return HttpResponseRedirect(request.POST.get('next') or reverse('index'))
            #return HttpResponseRedirect(reverse('index'))

    return render(request, 'login.html', {'login_form': login_form, 'next': request.GET.get('next', '') })

This will return the value of next, or reverse('index') if that value is empty.

👤knbk

Leave a comment