I have a view in Django that redirects a user to some url with aditional query string:
return redirect('search/?print_id='+str(pk))
In my urls.py, the url pattern looks like this:
path('search/', views.search, name='search'),
And the problem is when Django tries to redirect, I get the following error:
Reverse for 'search/?print_id=36' not found. 'search/?print_id=36' is not a valid view function or pattern name.
How can I modify the url pattern to accept a query string?
redirect will try to look for a view with that name. You should work with a :
from django.http import HttpResponseRedirect, QueryDict
from django.urls import reverse
# …
qd = QueryDict(mutable=True)
qd['print_id'] = pk
return HttpResponseRedirect(f"{reverse('search')}?{qd.urlencode()}")
Related
Looks like redirect(<url>) is adding <url> to the current view url, ignoring urls.py, with respect to the Code below redirecting to "<mydomain>.com/savePersonalEdits/account/" while what I wanted is: "<mydomain>.com/account/"
Code:
At the end of some Django view function I have:
return redirect('account/')
urls:
path('account/', views.accountSettings),
path('savePersonalEdits/', views.saveEdits, name="savePersonalEdits") #name needed for HTML form action url
you can use HttpResopnseRedirect for this
from django.http import HttpResponseRedirect
return HttpResponseRedirect('/account/')
also there is a better way to redirect, create name your path in ulrs.py
path('account/', views.accountSettings, name="account_url_name"),
#and in your views import reverse and HttpResponseRedirect
from django.urls import reverse
from django.http import HttpResponseRedirect
return HttpResponseRedirect(reverse("account_url_name"))
Just do it
return redirect('/account/')
or
return redirect('account')
With my (Django v 1.17) project I am using django-subdomains.
I have no problem to call index view and when I open my url https://subdomain.domain.com I will get index.html.
My issue that I wrote a new view called example for the sub-domain but when I open the url https://subdomain.domain.com/exmaple I will get error Page not found (404).
Hete is my code:
settings.py
INSTALLED_APPS = [
'subdomain'
]
SUBDOMAIN_URLCONFS = {
'subdomain': 'subdomain.urls',
}
subdomain/urls.py
from django.conf.urls import url, include
from . import views
from django.contrib.auth import views as auth_views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^$example', views.example, name='example'),
]
subdomain/views.py
from django.shortcuts import render
from django.template import loader
from django.http import HttpResponse
def index(request):
template = loader.get_template('subdomain/index.html')
return HttpResponse(template.render())
def example(request):
template = loader.get_template('subdomain/example.html')
return HttpResponse(template.render())
Error:
Page not found (404)
Request Method: GET
Request URL: https://subdomain.domain.com/example
Using the URLconf defined in subdomain.urls, Django tried these URL patterns, in this order:
1. ^$ [name='index']
2. ^$example [name='example']
The current path, econ, didn't match any of these.
Please advise how to fix this issue and write view for sub-domain.
This is unrelated to django-subdomains. The dollar should be at the end of the regex.
url(r'^example$', views.example, name='example'),
The dollar matches the end of the string, so if you have it at the beginning then it's not going to match.
Well, I have my own session and authentication routines in my app. When a user goes to app/login/ page, if he or she is not loggen in, then he/she sees a form to submit, otherwise I want to redirect the user to the root page app/. login view looks like this:
def index(request):
if sessionCheck(request):
# here I want to redirect one level above to app/
pass
else:
template = loader.get_template('login/login.html')
... other code which is not important
In PHP, I think, I would do it like this:
header("Location: /");
exit;
But how should I do exactly the same thing in Django?
You can use the redirect shortcut function:
from django.shortcuts import redirect
return redirect('some-view-name')
You can also specify a URL apart from a named view. So if your index url does not have a name, you can specify '/'.
This shortcut function is essentially the same as:
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
return HttpResponseRedirect(reverse('some-view-name'))
In order to have a named view, in your urls.py you have to provide a name argument. For instance:
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^some-view$', views.something, name='some-view-name'),
]
More on that on Django tutorial, Django URL dispatcher.
You can use redirect
if sessionCheck(request):
redirect(your_url)
else:
...
I have a ModelViewSet registered in a router
from django.conf.urls import url, include
from rest_framework import routers
from . import views
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
urlpatterns = [
url(r'^', include(router.urls)),
]
So i try to reverse the url with a primary key
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
user = User.objects.get(pk=1)
url_with_args = reverse('user-list', args=[user.pk])
url_with_kwargs = reverse('user-list', kwargs={'format':user.pk})
but the value of the urls is
url_with_args == '/api/users/.1'
url_with_kwargs == '/api/users/.1'
why is there a period in the primary key value?
I have also tried the same process with
rest_framework.reverse.reverse
but the values returned values are:
'/api/users/.1'
The issue here was that you were using user-list instead of user-detail for the named URL. user-list is meant to go to the list view /api/resource while user-detail is meant to go to the detail view /api/resource/1.
The reason why user-list was giving you /api/users/.1 is because the regex that it is matching is /api/users/.(?<format>) where format is the optional string that can be things like xml or json and control what renderer is used`.
The regex for user-detail is /api/users/(?<pk>) where pk is a non-optional parameter used for matching the primary key when retrieving the object.
I'm on a page with a variable url /emails/edit/32/, and I want to update the form and refresh the page...how do I issue an HttpResponseRedirect to the current page, which has a variable extension?
My urls.py is:
urlpatterns = patterns('',
(r'^emails/edit/$', 'email_edit'), # this is the page it is re-directing to
(r'^emails/edit/(?P<email_id>\d+)/$', 'emails_single'),
)
And my views.py is:
def emails_single(request, email_id):
...(stuff)...
Email.objects.filter(id=request.POST['id']).update(email=request.POST['email'])
return HttpResponseRedirect(reverse('emails_single',args=[email_id]))
Update: what it is doing is just chopping off the ending of the URL (even when using the reverse examples). For example: http://127.0.0.1:8000/emails/edit/42/ --> http://127.0.0.1:8000/emails/edit/
from django.core.urlresolvers import reverse
return HttpResponseRedirect(reverse('emails_single', args=[email_id]))
reverse()
from django.core.urlresolvers import reverse
def myview(request):
return HttpResponseRedirect(reverse('urlname', args=[1945]))