Redirect with parameters. NoReverseMatch at /test/ - django

views.py:
def demo(request, **kwargs):
print response
......
def test(request):
......
kwargs = {'response': response}
return redirect('demo', **kwargs)
urls.py:
from django.conf.urls import patterns, url
from django.contrib.sitemaps.views import sitemap
urlpatterns = patterns('clients.views',
url(r'^test/', 'test', name='test'),
url(r'^demo/', 'demo', name='demo'),
)
Why I have this error:
NoReverseMatch at /test/
Reverse for 'demo' with arguments '()' and keyword arguments
'{'response': {u'status': u'ok'}}' not found.
Request Method: POST Request URL: http ://127.0.0.1:8000/test/

When using the redirect() shortcut you're actually doing a HttpResponseRedirect() and therefore need not to include the response in your kwargs.
Furthermore if you would like to redirect with keyworded arguments then the call would be
redirect('/myurl/', momma="im comin' home")
or
redirect('/myurl/', kwargs={'loads_a_kwargs':'cowboy'})
The error you're getting is because your regexp url(r'^demo/', 'demo', name='demo') does not accept any parameters. Also, normally you would end all your url regexes with $ to denote that the capturing should stop.

Thats error simply been raised not from your test view but from your demo view. As per url reverse matching .. demo url must match to the demo view function parameters.
for example : url : demo/ should be demo/<response>
And In case you don't want to change the url pattern then make your response as GET parameter to demo view.

When you say redirect('demo', **kwargs), internally its trying to find the urlpattern demo/(?P<response>\d+). Actually it could be either \d+ or \w+ or whatever. But you don't have this urlpattern defined and so its failing.
So, it will pass if you define such url pattern. But another problem with your code is that response in kwargs is a dictionary and there is no way you can capture a dictionary in the url pattern.
Any particular reason you want to redirect to demo along with status code?

NoReverseMatch Exception Occurs when a matching URL in your URLconf cannot be identified based on the parameters you have given. Refer the django Docs https://docs.djangoproject.com/en/dev/ref/exceptions/#noreversematch
I am looking at your url.py You didn't included $
url(r'^test/$', 'test', name='test'),

Related

using Handler404 in django url dispatcher cause server error

I followed this https://stackoverflow.com/a/31381075/10087274 because I want when url does not exist a json shows error but the problem is here that I get server error 500 when I add handler404 in my url dispatcher
here is my project url :
from django.urls import path, include
from django.conf.urls import handler404
from api.exception import custom404
handler404 = custom404
urlpatterns = [
path('api/v1/', include('acl.urls')),
]
and I have exception.py inside my project folder (near settings.py) contains this:
from django.http import JsonResponse
def custom404(request):
return JsonResponse({
'status_code': 404,
'error': 'The resource was not found'
})
I dont know how can I solve my problem
Unfortunately, you haven't provided much information regarding the error traceback. Anyway, The very first thing I noticed in your code, you've missed one optional parameter to the custom404 function. That function should take two parameters, request and exception
def custom404(request, exception=None):
response = {
'status_code': 404,
'error': 'The resource was not found'
}
return JsonResponse(response, status=404)
Reference
1. Custom Error Views
Well django rest framework is open source, so if you want to replicate certain behaviour you can read the code and pick and chose what you like. For instance, you can see that the Generic Error view (custom server and bad request error views) provided in drf docs are located inside exceptions.py inside rest_framework you can look it up here and see how it can be done.
Create a custom 404 view, like this:
def not_found(request, exception, *args, **kwargs):
""" Generic 404 error handler """
data = {
'error': 'Not Found (404)'
}
return JsonResponse(data, status=status.HTTP_404_NOT_FOUND)

django url regular expressions capture invalid url

I want to understand how to create urls / regular expressions to capture and redirect to views those patterns that do not match any defined pattern.
I have a pattern in the url for the project where I am looking for waitlist.
I that does not match I want a to direct it to a project view, which I was assuming would be
caught by the second url below
url(r'^waitlist/', include('waitlist.urls')),
url(r'^.*$', views.my_default_2),
If the user does include the url for waitlist, then it should pass to the app url for a match
and if no match pass through to the wild card, the second line.
url(r'^$', views.index, name='index')
url(r'^.*$', views.my_default),
Is this the correct way to capture invalid/ incorrect url input through the project and the app?
For project you can override 404 view
https://docs.djangoproject.com/en/dev/topics/http/views/#customizing-error-views
for default django raise exception when none found. but you can customize this for your need
You can use default page not found view
Follow this
project/waitlist/urls.py
from django.conf.urls import patterns, url
from waitlist import views
urlpatterns = patterns('waitlist.views',
url(r'^$', 'index', name='index'),
)
handler404 = 'mysite.views.my_custom_page_not_found_view'
project/waitlist/views.py
defaults.page_not_found(request, template_name='404.html')
For reference how defaults.page_not_found works see this link

redirect error with django

I have a problem with the redirect of Django 1.4.3
#-*- coding: utf-8 -*-
from django.http import HttpResponse, Http404
from django.shortcuts import redirect
def redirect_test(request):
print("redirect_test() called.")
return redirect('redirectionFunc')
def redirectionFunc(request):
return HttpResponse("You have been redirected.")
My url is :
url(r'^redirectTest/$', 'redirect_test')
When I try to open
http://xxx/blogz/redirectTest
I got the following error :
NoReverseMatch at /blogz/redirectTest/
Reverse for 'redirectionFunc' with arguments '()' and keyword arguments '{}' not found.
Whereas the terminal I have :
redirect_test() called.
What's wrong ??
The 'redirect' method, takes the python path to the url, or the name of the url.
In the first case, if your "redirect_func" view is in app/views.py, your code should be:
return redirect('app.views.redirect_func')
If you want to name your url, for example "redirect_test", in your url configuration you should give the name parameter to the url method:
url(r'^redirectTest/$', 'app.views.redirect_func', name='redirect_test')
Then you can call redirect with the name of your url:
return redirect('redirect_test')
You can check the documentation on naming urls here

Django URL kwargs both in main app and subapp, reverse fails

EDIT: Never mind, it was something completely unrelated (wrong URL name).
I have a Django urls.py that includes another urls.py from a subapp. I get "reverse not found" errors when trying to use reverse(). I use keyword arguments in the URL both before and after the include, it's basically:
First urls.py:
urlpatterns = patterns(
'',
# Change requests are in a subapp
url(r'^projects/(?P<project_slug>[^/]+)/changerequests/',
include('myapp.changerequests.urls')),
)
And in the subapp's urls.py:
urlpatterns = patterns(
'',
url(r'^detail/(?P<request_id>\d+)/$',
views.RequestDetailPage.as_view(),
name='changerequests_detail'),
)
Now I want to find an URL with something like
url = reverse('changerequests_detail', kwargs={
'project_slug': self.project.slug,
'request_id': str(self.id)})
So it uses two kwargs, that are spread out over both urls.pys. But the reverse fails to find an answer (Reverse for 'changerequests_main' with arguments '()' and keyword arguments '{u'project_slug': u'123-2013_monitoring_slibaanwas-hdsr', u'request_id': '2'}' not found.).
Is that the problem? Is spreading kwargs over urls files this way not possible?
Maybe error occurs because it's trying to reverse 'changerequests_main' URL, not 'changerequests_detail'.

Redirection in Django URLs

How do I redirect all URLs starting from a particular pattern to another?
Description:
I want to be able to redirect as follows:
/pattern1/step1/ to /pattern2/step1/
/pattern1/step2/ to /pattern2/step2/
/pattern1/continue/ to /pattern2/continue/
What is the easiest way of doing this in Django URL patterns?
RedirectView works. Capture the remainder of the path with a named kwarg. It will be passed into RedirectView.get_redirect_url, so you can interpolate it into the url you provide.
url(r'^pattern1/(?P<url>.+)$', RedirectView.as_view(url="/pattern2/%(url)s")),
# ^ ^
# | this url appears here |
You can use redirect_to generic view and add redirection urls in urls.py as:
from django.views.generic.simple import redirect_to
urlpatterns = patterns('',
('^pattern1/step1/$', redirect_to, {'url': '/pattern2/step1/'}),
#any more patters.
)
Here is documentation: Generic view redirect_to . These can take the parameters as well.
Redirections could also be handled at the web server level.