How to Redirect To Same Page on Failed Login

The Django framework easily handles redirecting when a user fails to log in properly. However, this redirection goes to a separate login page. I can set the template to be the same as the page I logged in on, but none of my other objects exist in the new page.

For example, I have a front page that shows a bunch of news articles. On the sidebar is a login form. When the user logs in, but fails to authenticate, I would like it to return to the front page and preserve all the news articles that show. As of current, none of the news articles show up.

How can I fix this problem? Any help is appreciated.

Edit: Remember that I have dynamic content that is being displayed, and I would like it to still display! Futhermore, the main page is not the only place a user can log in. The sidebar never changes, so the user can potentially log in from any page on the site, and all of the content on that page exactly as it was still needs to be displayed upon failure to log in.


Asked by: Julia883 | Posted: 30-11-2021






Answer 1

Do you want to redirect to the referring page on failed login?

... authentication code above

if user.is_authenticated():
    #show success view
else:
    return HttpResponseRedirect(request.META.get('HTTP_REFERER', reverse('index'))

you might want to check that referring page url is set correctly, otherwise set it to default url (assuming that your default url is named "index").

Answered by: Adrian920 | Posted: 01-01-2022



Answer 2

  1. Use an <IFRAME> in the sidebar to call the login view -- all postbacks will happen within the iframe, so your page stays intact. If the visitor logs in successfully, you can use javascript to redirect the parent page to some other URL
  2. Use AJAX to post the login form -- acheives the same effect as (1), but it means your visitors will need to have javascript-enabled browsers

I personally prefer to have the login on a separate page. If you're only worried about your visitors losing their current page (and not say, bound by a fussy client), you can have the login show up in a lightbox. I've used all three approaches in the past, and I'd be happy to post some code samples if you're interested.

Answered by: Blake761 | Posted: 01-01-2022



Answer 3

This is because redirecting to a view misses the original context you use to render the page in the first place.

You are missing just a simple logic here. You are trying to render the same template again, but with no news_article list.

I suppose (in the first place), you are rendering the template which shows you Articles as well as login form, by sending two things 1. Login Form, and 2. Articles List. But secondly, when user fails to authenticate, you are not passing the same things again. Pass those variables again as context (you can also add error message if your form is not handling error messages).

if user.is_authenticated():
    #show success view
else:
    return render_to_response('same_template.html', {
        'error_msg': 'Username or password you provided was incorrect',
        'news_articles': NewsArticles.objects.all()[:3],
        'login_form': LoginForm(request.POST);
    })

Edit: The reality is that, a context is used to render a template, and it's the complete responsibility of that template, what it wants to pass in further navigation. And as I see, if you are not passing something further, you are not getting it further.

If you want some automated context, develop your own context processor, something like the auth-context-processor, which automatically adds like 'user', always available to the template.

And by the way, you are going to miss that kind of context anyway, even if login is authenticated. So if that particular context is really important, either try sending the primary keys of articles along with the login form submit, or store that in global (ugliest thing ever) or just reconsider and separate the flow (good thing, I feel).

Answered by: Catherine438 | Posted: 01-01-2022



Similar questions

python - CSRF Failed SSO Django after redirect

I'm trying to configure Google's SSO for my django app. Google is the Identity provider and my app is the Service provider. I'm using python3-saml for the SSO and I used the files like in the django demo. Whenever I click login, Google trie...


Python + Django page redirect

How do I accomplish a simple redirect (e.g. cflocation in ColdFusion, or header(location:http://) for PHP) in Django?


cgi - How to redirect to another page in Python in CGIAr

If I want to redirect the user from a cgi script to a HTML page using core libraries from the following: import cgi Please could someone point me in the right direction. Nothing more. Simply redirect from cgi script to html page. How ever you would do this Python. If you have to physically write out the HTTP Response Headers to achieve this, then I would appreciate any i...


python - redirect prints to log file

Okay. I have completed my first python program.It has around 1000 lines of code. During development I placed plenty of print statements before running a command using os.system() say something like, print "running command",cmd os.system(cmd) Now I have completed the program. I thought about commenting them but redirecting all these unnecessary print (i can't remov...


python - Pylons redirect to 404 error page

What function to I use to redirect to the default 404 error page? Sample code appreciated. Thank you!


python - Error using redirect in pylons

Using Pylons verson 1.0: Working on the FormDemo example from the Pylons book: http://pylonsbook.com/en/1.1/working-with-forms-and-validators.html My controller has the following functions: class FormtestController(BaseController): def form(self): return render('/simplefor...


Python CGI script - redirect doesn't always work

I'm writing a small CGI script for an assignment (Python 2.4) that takes form data, runs a shell command with it, and then displays one or another version of its own page depending on what it just did. E.g. if you add a comment, it reloads the "item" version of the page rather than the "list of all items" view, incorporating the new comment. There are several places in the program where it's supposed to reload itself. In o...


python - how to redirect to particular url on 404

@error(404) def error404(error): return 'Nothing here, sorry' This is the way to response 404 in bottle framework. But On 404 I want to redirect to particular url say http://abc.com/. Is it possible?


python - how to redirect form after submit

I've a form, where users select the years and gender, then they click on submit. With these values I'm calculating the numbers, drawing some pictures, etc. Everything fine so far. What I would like to do is open these pictures and data into a pdf file, with the help of documentation. The thing is that I'm not able to redire...


python - Django redirect the right way?

I have a similar question to this - Conditional login redirect in Django But I couldn't understand how to achieve the result from answers there. I am relatively new to django. I reused this code from somewhere, which redirects the user to login page. But after login I always get to the start/ho...


python - Check secure OpenID redirect?

The process for openid login for my server redirects to google, for example, then google redirects back to a page with parameters in the parameter string. how do I verify this really came from google?


bash - Redirect command to input of another in Python

I would like to replicate this in python: gvimdiff &lt;(hg cat file.txt) file.txt (hg cat file.txt outputs the most recently committed version of file.txt) I know how to pipe the file to gvimdiff, but it won't accept another file: $ hg cat file.txt | gvimdiff file.txt - Too many edit arguments: "-" Getting to the python part... # hg...


Python + Django page redirect

How do I accomplish a simple redirect (e.g. cflocation in ColdFusion, or header(location:http://) for PHP) in Django?


python - How to pass information using an HTTP redirect (in Django)

I have a view that accepts a form submission and updates a model. After updating the model, I want to redirect to another page, and I want a message such as "Field X successfully updated" to appear on this page. How can I "pass" this message to the other page? HttpResponseRedirect only accepts a URL. I've seen this done bef...


python - Django: Redirect to previous page after login

I'm trying to build a simple website with login functionality very similar to the one here on SO. The user should be able to browse the site as an anonymous user and there will be a login link on every page. When clicking on the login link the user will be taken to the login form. After a successful login the user should be taken back to the page from where he clicked the login link in the first place. I'm guessing that I ...


How to redirect the output of .exe to a file in python?

In a script , I want to run a .exe with some command line parameters as "-a",and then redirect the standard output of the program to a file? How can I implement that?


cgi - How to redirect to another page in Python in CGIAr

If I want to redirect the user from a cgi script to a HTML page using core libraries from the following: import cgi Please could someone point me in the right direction. Nothing more. Simply redirect from cgi script to html page. How ever you would do this Python. If you have to physically write out the HTTP Response Headers to achieve this, then I would appreciate any i...


How to redirect stderr in Python? Via Python C API?

This is a combination of my two recent questions: [1] Python instance method in C [2] How to redirect stderr in Python? I would like to log the output of both stdout and stderr from a python script. The thing I want to ask is...


How to redirect stderr in Python?

I would like to log all the output of a Python script. I tried: import sys log = [] class writer(object): def write(self, data): log.append(data) sys.stdout = writer() sys.stderr = writer() Now, if I "print 'something' " it gets logged. But if I make for instance some syntax error, say "print 'something# ", it wont get logged - it will go into the console instead. Ho...


linux - Redirect stderr to stdout on exec-ed process from python?

In a bash script, I can write: exec 2&gt;&amp;1 exec someprog And the stderr output of someprog would be redirected to stdout. Is there any way to do a similar thing using python's os.exec* functions? This doesn't have to be portable, just work on Linux.


python - How to set cookies with redirect in Pylons

In light of the cookie-handling bugs affecting Safari and Chrome (see this thread), and Pylons implementation of redirect_to as an exception, is it possible to reliably set a tracking cookie and redirect at the same time? Is the META refresh method looked down upon?






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top