Python + Django page redirect

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


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






Answer 1

It's simple:

from django.http import HttpResponseRedirect

def myview(request):
    ...
    return HttpResponseRedirect("/path/")

More info in the official Django docs

Update: Django 1.0

There is apparently a better way of doing this in Django now using generic views.

Example -

from django.views.generic.simple import redirect_to

urlpatterns = patterns('',   
    (r'^one/$', redirect_to, {'url': '/another/'}),

    #etc...
)

There is more in the generic views documentation. Credit - Carles Barrobés.

Update #2: Django 1.3+

In Django 1.5 redirect_to no longer exists and has been replaced by RedirectView. Credit to Yonatan

from django.views.generic import RedirectView

urlpatterns = patterns('',
    (r'^one/$', RedirectView.as_view(url='/another/')),
)

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



Answer 2

Depending on what you want (i.e. if you do not want to do any additional pre-processing), it is simpler to just use Django's redirect_to generic view:

from django.views.generic.simple import redirect_to

urlpatterns = patterns('',
    (r'^one/$', redirect_to, {'url': '/another/'}),

    #etc...
)

See documentation for more advanced examples.


For Django 1.3+ use:

from django.views.generic import RedirectView

urlpatterns = patterns('',
    (r'^one/$', RedirectView.as_view(url='/another/')),
)

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



Answer 3

There's actually a simpler way than having a view for each redirect - you can do it directly in urls.py:

from django.http import HttpResponsePermanentRedirect

urlpatterns = patterns(
    '',
    # ...normal patterns here...
    (r'^bad-old-link\.php',
     lambda request: HttpResponsePermanentRedirect('/nice-link')),
)

A target can be a callable as well as a string, which is what I'm using here.

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



Answer 4

Since Django 1.1, you can also use the simpler redirect shortcut:

from django.shortcuts import redirect

def myview(request):
    return redirect('/path')

It also takes an optional permanent=True keyword argument.

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



Answer 5

If you want to redirect a whole subfolder, the url argument in RedirectView is actually interpolated, so you can do something like this in urls.py:

from django.conf.urls.defaults import url
from django.views.generic import RedirectView

urlpatterns = [
    url(r'^old/(?P<path>.*)$', RedirectView.as_view(url='/new_path/%(path)s')),
]

The ?P<path> you capture will be fed into RedirectView. This captured variable will then be replaced in the url argument you gave, giving us /new_path/yay/mypath if your original path was /old/yay/mypath.

You can also do ….as_view(url='…', query_string=True) if you want to copy the query string over as well.

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



Answer 6

With Django version 1.3, the class based approach is:

from django.conf.urls.defaults import patterns, url
from django.views.generic import RedirectView

urlpatterns = patterns('',
    url(r'^some-url/$', RedirectView.as_view(url='/redirect-url/'), name='some_redirect'),
)

This example lives in in urls.py

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



Answer 7

Beware. I did this on a development server and wanted to change it later.

I had to clear my caches to change it. In order to avoid this head-scratching in the future, I was able to make it temporary like so:

from django.views.generic import RedirectView

url(r'^source$', RedirectView.as_view(permanent=False, 
                                      url='/dest/')),

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



Answer 8

You can do this in the Admin section. It's explained in the documentation.

https://docs.djangoproject.com/en/dev/ref/contrib/redirects/

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



Answer 9

page_path = define in urls.py

def deletePolls(request):
    pollId = deletePool(request.GET['id'])
    return HttpResponseRedirect("/page_path/")

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



Answer 10

This should work in most versions of django, I am using it in 1.6.5:

from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
urlpatterns = patterns('',
    ....
    url(r'^(?P<location_id>\d+)/$', lambda x, location_id: HttpResponseRedirect(reverse('dailyreport_location', args=[location_id])), name='location_stats_redirect'),
    ....
)

You can still use the name of the url pattern instead of a hard coded url with this solution. The location_id parameter from the url is passed down to the lambda function.

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



Similar questions

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 - 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&lt;nextLoc&gt;)$', '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=&quot;Success!&quot;)


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: &lt;div id="logging"&gt; {% if user.is_authenticated %} &lt;h1&gt;Witaj, {{user.username}}!&lt;/h1&gt; {% else %} &lt;form method="post" action="{% url 'harcowanie.views.login' %}"&gt; {% csrf_token %} &lt;div style="display: inline-b...


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 - 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 - 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&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