2019-05-24
Not able to redirect to view after login
stackoverflow
Question

I am trying to create a redirect when the user logs in. For example when user tries to access a link to create blog post he is prompted to log in , and after he gets logged in he is redirected to the page to create the post. I am extracting the next parameter from the url.

blog.urls

from django.conf.urls import url
from blog import views

urlpatterns=[

    url(r'^$',views.index,name="index"),
    url(r'^signup/$',views.signup_view,name="signup_view"),
    url(r'^login/$',views.login_view,name="login_view"),
    url(r'^create-post/$',views.create_blog,name="create_post"),
    url(r'^logout/$',views.logout_view,name="logout_view"),    
]

blog.views:

def login_view(request):

    if request.method == 'POST':
        form=LoginForm(request.POST)
        if form.is_valid():
            username=form.cleaned_data['username']
            password=form.cleaned_data['password']

            user=authenticate(username=username,password=password)
            if user is not None:
                if user.is_active:
                    login(request,user)
                    go_to=request.GET.get('next','/')
                    print go_to
                    return HttpResponseRedirect(go_to)
                else:
                    return HttpResponse("Not active")
            else:
                return HttpResponse("User doesn't exist")

    else:
        form=LoginForm()
    return render(request,'blog/login.html',{'form':form})

and blog/login.html

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>Login</title>
</head>
<body>
        <form method="POST" action="/login/">
            {% csrf_token %}
            <table>
                {{form.as_table}}
            </table>
            <button type="submit">Submit</button>
        </form>
</body>
</html>

Whenever I login it shows the next parameter as '/' while there is "next=/create-blog/" in the url. Please suggest any solution.

Answer
1

you need:

action="/login/{% if request.GET.next %}?next={{ request.GET.next }}{% endif %}"
Not able to redirect to view after login
See more ...