Django URL Pattern not triggered - django

I am trying to implement an approve and decline functionality of a profile using the following approach:
/user/area/decline/234322
/user/area/approve/234322
So I wrote the following URL pattern:
urlpatterns = i18n_patterns(
url(r'^user/area/decline/(?P<userid>\[0-9]+)/$', views.DeclineUser),
url(r'^user/area/approve/(?P<userid>\[0-9]+)/$', views.ApproveUser),
url(r'^user/area/$', views.Index),
.
.)
And my views:
#login_required
def DeclineUser(request, userid=""):
print("Here: " + userid)
#login_required
def ApproveUser(request, userid=""):
print("Here: " + userid)
But something is wrong and the methods are not triggered and the Index is triggered instead so I guess the problem is that the URL RegEx is not matching what I need.

Both of your url's have a \ in them so you are escaping the opening [ bracket, you just need to remove those slashes.
url(r'^user/area/decline/(?P<userid>[0-9]+)/$', views.DeclineUser),
url(r'^user/area/approve/(?P<userid>[0-9]+)/$', views.ApproveUser),

Related

Django Regex URL pattern overriding other URLs

I am working on a project which requires to display the data about a city which is requested through the url like example.com/city1 for city1 information etc.
I have used the below url pattern & view in my app. This view is working fine.
url(r'^(?P<cityId>[-\w]+)$',views.cityindex,name='cityindex'),
def cityindex(request, cityId):
city = City.objects.filter(url = cityId)
if len(city) == 0:
return redirect('/404')
return HttpResponse('City Data Extracted')
But when I try to open other urls like /admin or urls from other app it is being redirected to my cityindex view and then to 404 page as handled in my view above.
Below is the url patterns I used in my main urls.py file.
url(r'^', include('main.urls')),
url(r'^admin/', admin.site.urls),
url(r'^login_redirect/', include('loginapp.urls')),
I am presently using Django 1.11.12. Is there any way to stop this url from overriding?
Edit :
Urls in my main.urls file
url(r'^$',views.index,name='index'),
url(r'^about$', views.aboutpage,name="aboutpage"),
url(r'^terms$', views.termspage,name="termspage"),
url(r'^privacy$', views.privacypage,name="privacypage"),
url(r'^(?P<cityId>[-\w]+)$',views.cityindex,name='cityindex'),
To achieve this, think of sceanarios like this
1- www.example.com/cityname/
2- www.example.com/about/Us/
3- www.example.com/others/terms/
4- www.example.com/others/privacy/
Anytime you want to have other url like www.example.com/faculty/list
you use number 2-4 while you use the first to achieve your city name.
I have tested this to work in the following format
urlpatterns = [
url(r'^about/us/$', views.about_page), #about us or any other page
url(r'^(?P<cityname>\w+)/$', views.cityindex), #cityname
]
and in my view.py, i can catch the city name given like this
def cityindex(request, cityname):
data = cityname
#you can do anything you want here
return HttpResponse(data)
NB: the cityname could a number so you may decide to use it as city id instead, however, ensure it was converted to an integer in your view if you prefer to use cityid
I hope this helps

How can I use a catch all route using `path` or `re_path` so that Django passes all unmatched requests to my index view?

My url patterns look like this:
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('api.urls')),
re_path('.*', IndexView.as_view()),
]
This works but it matches all URLs, including those prefixed with admin and api. I want those URLs to still match, and for any unmatched URLs to render IndexView.
Before 2.0 I used this regex for this purpose. I tried using it in re_path but that didn't work, which is what led me to trying the above.
url(r'^(?P<path>.*)/$', HtmlView.as_view())
Use case is a SPA where I handle 404s client side.
Many thanks in advance.
You can use two entries (one for '/', another one for anything else), but using path for both of them, which should be (slightly) more efficient:
urlpatterns = [
path('', IndexView.as_view(), {'resource': ''}),
path('<path:resource>', IndexView.as_view())
]
In this case, I'm using <path:resource> because path catches all resource names, inluding that with / in them. But it does not capture the main index resource, /. That's why the first entry. The dictionary as last argument for it is because we need to provide a resource parameter if we want to use the same view than in the second entry.
That view, of course, should have 'resource' as a paremeter:
def as_view(request, resource):
...
So as I said in the question description, trying the regex I was using before Django 2.0 in re_path did not work. It would basically match for all requests except / (i.e., index path). I fixed this by using both that regex and a second path matching / specifically. Here's the code:
urlpatterns = [
re_path(r'^(?P<path>.*)/$', IndexView.as_view()),
path('', IndexView.as_view()),
]
With these changes my other routes would match and these two routes would account for all other urls.
One Idea to go about this is let the django catch 404.
url.py
from django.conf.urls import handler404
handler404 = 'app_name.views.bad_request'
and in your views.py
views.py
def bad_request(request):
return redirect(reverse('home'))
You can always do some regex thingy to catch unmatched urls. but hey this gets the job done. :)

(django URLconf) page not found error only for urls with '-' character

I have a weird problem can't figure out whats wrong, I get 404 errors for any url that contains a '-' character...
my urls.py in the project root works fine
url(r'^serialy/', include('movieSite.series.urls')),
next, is
urlpatterns = patterns('',
url(r'^$', views.serialy_index, name='serialy_index'), #this works
(r'^(?P<serial_title>[\w]+)/$', serial),
)
The second one, using serial_title, works only if the series' title is something like, 'Dexter,' or 'Continuum.' But other series have titles like 'Family guy,' so when I create the url I use a function that changes it to 'Family-guy,' but for some reason it won't work for those titles with the '-' characters. I always get a 404 error like this
Using the URLconf defined in movieSite.urls, Django tried these URL patterns, in this order:
^serialy/ ^$ [name='serialy_index']
^serialy/ ^(?P<serial_title>[\w]+)/$
^static\/(?P<path>.*)$
The current URL, serialy/Whats-with-Andy/, didn't match any of these.
so here the url serialy/whats-with-andy/ doesn't match, but if I visit serialy/continuum it works fine?? anyone have any ideas as to what could cause this?
Oh and this is what the view looks like
def strip(s):
s.replace('-',' ')
return s
def serial(request, serial_title=None) :
s_title = strip(serial_title)
obj = Show.objects.get(title__icontains=s_title)
#episodes = obj.episodes
des = obj.description
img = obj.image
title = obj.title
t = get_template('serial.html')
html = t.render(Context({
'the_title':title,'the_image':img,'the_description':des
}))
return HttpResponse(html)
The regex [\w]+ only matches words and not special chars like -.
If you change it to [-\w]+ it'll match "slug" urls.
I think your regex is failing because '-' is not considered a match for \w. See here:
https://docs.python.org/2/library/re.html

Django url regexp not working

I'm trying to get my head around regexp in Django urls. I'm currently developing locally and I want to be able to direct a request such as http://localhost:8000/options/items/item-string-1121/ to the 'details' view in my app called 'options', passing in the final number part of the request string (1121) as a parameter 'id' to the view function.
The signature for details in options/views.py is as follows, taking id=1 as default:
def details(request, id=1):
...
I have the following in my root urls.py:
...
urlpatterns += patterns('',
url(r'^options/, include(options.urls')),
)
and in options/urls.py:
urlpatterns = patterns('options.views',
url(r'^items/(.+)(P<id>\d+)/$', 'details'),
...
)
Now when I try to request the above URL the dev server says it tried to match against the pattern ^options/ ^items/(.+)(P<id>\d+)/$ but it doesn't match.
Can anyone see the problem?
You need a non-greedy quantifier on the (.+), so r'^items/(.+?)(P\d+)/$'. Otherwise that first glob happily eats until the end of the string, preventing the ID from ever matching.
You are missing quotes.
urlpatterns += patterns('',
url(r'^options/, include(options.urls')),
)
Should be
urlpatterns += patterns('',
url(r'^options/', include('options.urls')),
)
I'm not too sure of your expression, might try this:
urlpatterns = patterns('options.views',
url(r'^items/(?<=-)(?P<id>\d+)/$', 'details'),
...
)

django url pattern for %20

In Django what is the url pattern I need to use to handle urlencode characters such as %20
I am using (?P<name>[\w]+) but this only handles alphanumeric characters so % is causing an error
I was able to make it work using the configuration given below. Check if it will suit your needs.
(?P<name>[\w|\W]+)
If you only want to allow space:
(?P<name>[\w\ ]+)
The best way to do that and allow others chars is using '\s' that is any spaces, tabs and new lines
(?P<name>[\w\s]+)
I am using Django 2.2.
It handles the %20 (which means space) in url using Path converter: str
You simply need to use:
<name> or <str:name>
For example, following example loads view "some_view" defined in view.py
#urls.py
from django.urls import path
from . import views
urlpatterns = [
path("<name>",views.some_view),
....
]
The following function renders "some.html" after processing. In this example sending the received name to "some.html".
#view.py
def some_view(request, name):
# process here
context = { "name" : name }
return render(request,"some.html",context)