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/home page of the user. I want them to see the page they really requested, and not the user homepage all the time. Can you tell me what and where I can make the change, it should be where I am using 'redirect' function. I probably should save some session variable and do it but not quite getting the starting point. any thoughts?
Below is the code -
def view_or_basicauth(view, request, test_func, realm = "", *args, **kwargs):
if test_func(request.user): # Already logged in, just return the view.
return view(request, *args, **kwargs)
# They are not logged in. See if they provided login credentials
if 'HTTP_AUTHORIZATION' in request.META:
auth = request.META['HTTP_AUTHORIZATION'].split()
if len(auth) == 2:
# NOTE: We are only support basic authentication for now.
if auth[0].lower() == "basic":
uname, passwd = base64.b64decode(auth[1]).split(':')
user = authenticate(username=uname, password=passwd)
if user is not None:
if user.is_active:
login(request, user)
request.user = user
return view(request, *args, **kwargs)
# Either they did not provide an authorization header or something in the authorization attempt failed. Send a 401 back to them to ask them to authenticate.
key = request.path.split('/')
if len(key) > 1:
base_url = request.get_host()
return redirect( 'https://' + base_url + '/login/')
s = '401 Unauthorized'
response = HttpResponse(s)
response.status_code = 401
response['Content-Length'] = '%d' % len(s)
response['WWW-Authenticate'] = 'Basic realm="%s"' % realm
return response
Asked by: Marcus919 | Posted: 27-01-2022
Answer 1
It's pretty straight forward:
Add a GET parameter to to your redirect line so that your login view knows where your user is coming from. It can be anything, but I'm using "?redirect=myurl"
.
In your login view: check for the existence of that key (redirect
) in GET upon successful login. If it exists, redirect to the value.
First modify your redirect line:
# add a GET parameter to your redirect line that is the current page
return redirect( 'https://' + base_url + '/login/?redirect=%s' % request.path )
Then in your login view, just check for your variable in GET and redirect to that value if it exists.
# modify the login view to redirect to the specified url
def login(request):
# login magic here.
if login_successful:
redirect = request.GET.get('redirect') # get url
if redirect:
# redirect if a url was specified
return http.HttpResponseRedirect(redirect)
# otherwise redirect to some default
return http.HttpResponseRedirect('/account/home/')
# ... etc
Answered by: Ryan504 | Posted: 28-02-2022
Answer 2
Pass the URL as a GET parameter in the redirect, and have the redirect target redirect them back after they've entered their credentials.
Answered by: Sawyer746 | Posted: 28-02-2022Similar questions
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 - Django redirect to root from a view
I am creating a django project. However, I have come across a small hiccup. My urls.py looks like this
url(r'^login/(?P<nextLoc>)$', 'Home.views.login'),
url(r'^logout/$', 'Home.views.logout'),
My views.py in the Home app is as follows:
def login(request,nextLoc):
if request.method == "POST":
form = AuthenticationForm(request.POST)
user=auth.authen...
python - Django Redirect after Login Error
Im new to Django and I know that to redirect after login I have to set the parameter 'page'. But this only works when the login is successful. How can i do the same thing when some error occurs??
Ps: Im currently also using django-registration with simple backend
python - django redirect to parent of iframe from view
I am having a web page rendered via iframe. On successfully submitting the form in iframe, i gave,
return HttpResponseRedirect("www.google.com")
But the target page is also getting loaded within iframe. How to specify the parent to reload from django view?
python - Django redirect to custom URL
From my Django app, how to I redirect a user to somescheme://someurl.com?
To give you some context in case it helps, I have a working oauth2 server written in Python/Django and I need to allow users to register redirect_uris that have a custom URL scheme. This custom URL scheme is used for
python - Django redirect to view
I have a view that I then want to redirect to another view with a success message. The signature of the method that I want to redirect to is:
quizView(request, quizNumber, errorMessage=None, successMessage=None)
And my attempt at redirecting to that view is:
return redirect(quizView, quizNumber=quizNumber, errorMessage=None, successMessage="Success!")
python - good way to redirect url in a django app
I'm constructing a Django app where I have a main page that links to different URLs to perform actions (for example there's a link to add a record to the database). This is done using forms in the templates and changes the current URL from app/index to app/add. The problem is that when I use render_to_response in the script that manages that action it doesn't change the URL but it does change the html being used back to ...
python - Django - how to redirect to index page upon logout?
I'm trying to implement a simple page redirect to the index page if user authentication fails.
Imagine that I have two paths:
www.xyz.com/app/
www.xyz.com/app/user
The first renders the index page, and the second is the authorized user landing page on successful login.
In my views.py file, I have
def index(request):
return render(request, "app...
python - Redirect using CBV's in Django
I believe this is a simple one, just can't spot the solution. I have a view that does a bit of work on the server then passes the user back to another view, typically the original calling view.
The way I'm rendering it now, the url isn't redirected, ie it's the url of the original receiving view. So in the case the user refreshes, they'll run that server code again.
class CountSomethingView(LoginReq...
python - django add 'http' when redirect after main url
i have web example.com
and i use @login_required in views.
If user not authenticated, browser redirect to:http://example.comhttp/accounts/login/
I don't know why.
On my home laptop all working good. But on the production i see that.
Do you have some ideas?
I'm using nginx with uwsgi.
@login_require...
python - Django Redirect URL
I am new to Django, and i am now trying to use the HttpResponseRedirect() function. But I am so confused that if I use it like HttpResponseRedirect('good/'), and the current page is '/bad/', it can only be redirected to '/bad/good/', which is an url of current page appended with the url value from the HttpResponseRedirect() function. I tried to search google,...
python - Django redirect in admin failed
After saving an object by clicking saveasnew button in admin interface i want to redirect to another url:
admin.py
class AirplanesAdmin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
obj.save()
if "_saveasnew" in request.POST:
self.message_user(request, 'YAY!!!')
return HttpResponseRedirect(reverse('admin:routes_airplanes_change',
...
python - Django wont redirect me on another view from view
I will try to describe problem:
In HTML i have some AJAX call to, lets say, URL getMetaData (this is function in views.py). I that function I check POST dictionary to check is all values there. If not i want to redirect to main page ("main.html"). This main.html is rendered in function main(request) in same views.py file.
When i do this:
def main(request):
return ...
python - How can I redirect to a different URL in Django?
I have two pages, one which is to display details for a specific item and another to search for items. Let's say that the urls.py is properly configured for both of them and within views.py for my app, I have:
def item(request, id):
return render(request, 'item.html', data)
def search(request):
#use GET to get query parameters
if len(query)==1:
#here, I want to redirect my request to i...
python - Django - How to redirect after login to the same page?
My login page is set in / http://127.0.0.1:8000/ but i want after login redirect to the same page http://127.0.0.1:8000/ not http://127.0.0.1:8000/home, like Facebook login.
How could make this possible?.
python - Django redirect on error to main home page or app root
I'm trying to not hardcode the url of the app in the view (really the controller) of an app.
Code looks like this:
event/view.py
def index(request):
try:
//do stuff with response
return render(request, 'rma/service.html', response)
except:
return redirect("/rma")
In this case the app is installed on the web server under /var/www/html/rma. but in production (or a...
python - Django force a admin login redirect when I enter in the home url
Why Django auto redirect to admin login url when I enter in home url?
urlpatterns = patterns('',
url(r'^$', 'django.views.defaults.permission_denied', name='index'),
url(r'^admin/', include(admin.site.urls)),
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
)
I need that when a user enter in the home url, a http 403 response return to him, but it is not happening....
python - Django + nginx redirect loop for home /
I've a really strange problem. It's not the first page i've published in this way but the first with this behavior.
My site is configured to redirect: http://marclab.de to http://marclab.de/
BUT
it redirects also http://marclab.de/ to
python - Django - Redirect at login based on group
I am currently working on a Django project that has a number of user groups. After login, I am looking to redirect each user to a unique page created for that group.
I have already created the login functionality but for the life of me cannot figure out how to redirect based on group. If there is more efficient way of doing this, I am also open to other suggestions.
The reason for having a separate page for...
python - Django redirect after login
Im creating my first app in Django
I decided I want logging window (smal one with username/password na "Log in" button) on EACH view.
From base.html:
<div id="logging">
{% if user.is_authenticated %}
<h1>Witaj, {{user.username}}!</h1>
{% else %}
<form method="post" action="{% url 'harcowanie.views.login' %}">
{% csrf_token %}
<div style="display: inline-b...
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 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 wou...
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 - 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 <(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?
python - 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 wou...
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>&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.
Still can't find your answer? Check out these communities...
PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python