3

when I am using login_required it does not rendering to appropriate url it always render to home page only

login view

def login_view(request):
print(request.user.is_authenticated())
w="Welcome"
title = "Login"
form = UserLoginForm(request.POST or None)
if form.is_valid():
    username = form.cleaned_data.get("username")
    password = form.cleaned_data.get("password")
    user = authenticate(username=username, password=password)
    login(request, user)        
    messages.success(request, "Successfully Logged In. Welcome Back!")
    return HttpResponseRedirect("/")

return render(request, "registration/login.html", {"form":form, "title":title})

settings.py file

LOGIN_URL = '/login/'
LOGIN_REDIRECT_URL = '/'

I applied login required on contact us but when i am logging in then it is rendering to home page.

contact us view

@login_required
def contactformview(request):
form = ContactForms(request.POST or None)
if form.is_valid():
    form.save()
    return HttpResponse(' Thanks For Contacting WIth Us We Will Get Back To You Within 24 Hours')
return render(request, 'contact-us.html', {'form':form})
Alasdair
  • 298,606
  • 55
  • 578
  • 516
Mandeep Thakur
  • 655
  • 1
  • 10
  • 23
  • 2
    This wont answer your question, but in your form you always think that the website user uses correct credentials... – Jingo Feb 14 '17 at 15:58
  • Look at the answer of this question. http://stackoverflow.com/questions/16750464/django-redirect-after-login-not-working-next-not-posting – Prakhar Trivedi Feb 20 '17 at 05:22

1 Answers1

1

When Django redirects to the login page, it includes the next url in the querystring, e.g.

/login/?next=contact

Your login_view ignores the querystring and always returns HttpResponseRedirect("/"), so you will always be redirected to the homepage.

It would be better to use Django's login view instead of your own, because it handles the redirect for you. If you must use your own login view, you can look at the source code to see how Django handles the redirect, and adjust your view.

Alasdair
  • 298,606
  • 55
  • 578
  • 516
  • when I am logging in it show me /login/?next=contact url but when I get logged in then it goes to home page – Mandeep Thakur Feb 14 '17 at 16:04
  • Yes, as I said, that is because you have `return HttpResponseRedirect("/")` in your code. Please use Django's `login` view instead of trying to write your own. Writing your own can be insecure - as Jingo says, you are currently logging people in whether or not the password is correct. – Alasdair Feb 14 '17 at 16:07
  • Same problem when I used Django's login view – Mandeep Thakur Feb 15 '17 at 02:00
  • We can't help if you don't show your view, urls and template. – Alasdair Feb 15 '17 at 07:48