[Django]-Django application deployed at suburl, redirect to home page after login

0👍

Quick read

Method to solve this:

  • Add LOGIN_REDIRECT_URL = '/djangoapp/homeit' in settings.py
  • Change your urls.py line 9 to url(r'^accounts/login/$', 'django.contrib.auth.views.login', {'extra_context': {'next':'/djangoapp/homeit'}}),

Explanation

Check for the documentation of django.contrib.auth.views.login present here

The code for def login is as follows:

def login(request, template_name='registration/login.html',
          redirect_field_name=REDIRECT_FIELD_NAME,
          authentication_form=AuthenticationForm,
          current_app=None, extra_context=None):
    """
    Displays the login form and handles the login action.
    """
    redirect_to = request.POST.get(redirect_field_name,
                                   request.GET.get(redirect_field_name, ''))

    if request.method == "POST":
        form = authentication_form(request, data=request.POST)
        if form.is_valid():

            # Ensure the user-originating redirection url is safe.
            if not is_safe_url(url=redirect_to, host=request.get_host()):
                redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL)

            # Okay, security check complete. Log the user in.
            auth_login(request, form.get_user())

            return HttpResponseRedirect(redirect_to)
    else:
        form = authentication_form(request)

    current_site = get_current_site(request)

    context = {
        'form': form,
        redirect_field_name: redirect_to,
        'site': current_site,
        'site_name': current_site.name,
    }
    if extra_context is not None:
        context.update(extra_context)

    if current_app is not None:
        request.current_app = current_app

    return TemplateResponse(request, template_name, context)

What is happening:

  • django.contrib.auth.views.login takes redirect_field_name and redirect accordingly
  • Default value of redirect_field_name is next.
  • Currently as you aren’t passing anything as next parameter, it is making redirect_to = '' automatically.
  • HttpResponseRedirect is being called as HttpResponseRedirect('')
  • Thus it end up redirecting to your homepage, and not /djangoapp.
👤skbly7

Leave a comment