Django URL template match (everything except pattern) - django

I need a django regex that will actually work for the url router to do the following:
Match everything that does not contain "/api" in the route.
The following does not work because django can't reverse (?!
r'^(?!api)

The usual way to go about this would be to order the route declarations so that the catch-all route is shadowed by the /api route, i.e.:
urlpatterns = patterns('',
url(r'^api/', include('api.urls')),
url(r'^other/', 'views.other', name='other'),
url(r'^.*$', 'views.catchall', name='catch-all'),
)
Alternatively, if for some reason you really need to skip some routes but cannot do it with the set of regexes supported by Django, you could define a custom pattern matcher class:
from django.core.urlresolvers import RegexURLPattern
class NoAPIPattern(RegexURLPattern):
def resolve(self, path):
if not path.startswith('api'):
return super(NoAPIPattern, self).resolve(path)
urlpatterns = patterns('',
url(r'^other/', 'views.other', name='other'),
NoAPIPattern(r'^.*$', 'views.catchall', name='catch-all'),
)

Use a negative look behind like so:
r'^(?!/api).*$'
This link explains how to do that:
http://www.codinghorror.com/blog/2005/10/excluding-matches-with-regular-expressions.html

I had this problem integrating django with react router, I check this link to fix it.
decoupled frontend and backend with Django, webpack, reactjs, react-router

Related

the current path ,About.html didn't match any of these in django

from django.conf.urls import url
from .import views
urlpatterns = [
url(r'^$', views.index,name='index'),
url(r'^About/', views.About,name='About'),
url(r'^checkout/', views.checkout,name='checkout'),
url(r'^contact', views.contact,name='contact'),
url(r'^faqs', views.faqs,name='faqs'),
url(r'^help', views.help,name='help'),
url(r'^icons', views.icons,name='icons'),
url(r'^payment', views.payment,name='payment'),
url(r'^privacy', views.privacy,name='privacy'),
]
The error message:
Page not found (404)
Request Method:
GET
Request URL:
http://127.0.0.1:8000/About.html
Using the URLconf defined in shop.urls, Django tried these URL patterns,
in this order:
admin/
^$ [name='index']
^about/$ [name='about']
^checkout/$ [name='checkout']
^contact/$ [name='contact']
^static\/(?P<path>.*)$
The current path, About.html, didn't match any of these.
This kind of an error could occur from 2 or 3 different scenarios.
In your case, you seem to put the wrong URL in the browser address bar.
Your correct URL should be http://127.0.0.1:8000/About (as you've written in the URL patterns).
Remember, About.html - is the HTML template you create inside the templates folder. Even though you route to the html page (with a string like: app_name/About.html) - the actual URL in the address bar will be according to what you write in the regex path r'^url_name'. If you write r'^About.html' in url patterns, then http://127.0.0.1:8000/About.html should work perfectly.
The second scenario (based on my experience) which could produce this type of an error is when you forget to pass the 'request' argument inside the method that defines view of the URL - in the respective views.py file.
You should be having a method named About which would look like this in views.py
def About(request):
return render(request,'app_name/About.html')
If you forget to pass argument in the paranthesis of About, this kind of an error could occur.
Finally, if you are using django 2, please start using re_path method to serve regex url patterns. The url method is likely to be depracated in future release.
Refer re_path documentation.
your URL will not be http://127.0.0.1:8000/About.html it will just be http://127.0.0.1:8000/about (remember urls are case insensitive), this will take you to your view which is named About, in your view you should reference your template in its render (about.html)
have you read the my first Django app https://docs.djangoproject.com/en/2.0/intro/tutorial01/ its a great place to start if you are unfamiliar with how django operates
What you are trying to hit is not a valid url, you have to hit http://127.0.0.1:8000/About as written in urls.py.
You have to understand the difference between urls and html templates, this About.html would be used in views while rendering like:
return render(request, 'your_app/about.html')
And for sure you can write a url if you want like this:
urlpatterns = [
url(r'^$', views.index,name='index'),
url(r'^About.html/', views.About,name='About'),
.
.
]
Check the documentation
The url which you provide in url ( ) method doesn't contain any suffix of .html
You can goto the about page directly by /About

Django index url confusion

Hi thanks for looking into this.
I have been following Django's tutorial on URLs and got a bit confused/stuck on this part:
https://docs.djangoproject.com/en/1.4/intro/tutorial03/#decoupling-the-urlconfs
what I do not understand is if, say, on page mypage.com I provide only 2 possible URLs for mypage.com/polls and mypage.com/admin, what happens if the user goes to mypage.com? Obviously, I thought, the user will need to see some sort of 'welcome' page so I decided to add another URL to that urls.py:
urlpatterns = patterns('',
url(r'^/', 'myapp.views.welcome'), #when it's just mysite.com
url(r'^myapp/', include('myapp.urls')), #includes everything with mysite.com/myapp/...
url(r'^admin/', include(admin.site.urls)),
)
But then I get redirected to that welcome view from whichever page, whether i go to /myapp or not. So, I decided to create a views.py file outside myapps folder and put that welcome page there, and it seems to have worked, apart from that I get a 404.
I am so confused! Could you explain in lamers' terms please
Thanks,
blargie-bla
It should be
url(r'^$', 'myapp.views.welcome')
otherwise any URL will match the pattern. Django will call the view for the first pattern in urlpatterns that matches, so you need to be specific and include the end-of-the-line character ($) into the pattern.

Django urlconf sometimes failing?

I've got a django urls.py file like so:
Base file:
urlpatterns = patterns('',
(r'^', include('sp.sp_app.urls')),
(r'^', include('sp.sp_api_activity.urls')),
(r'^', include('sp.sp_api_player.urls')),
(r'^', include('sp.sp_web.urls')),
)
In the sp.sp_web.urls file, I have the following:
from django.conf.urls.defaults import *
urlpatterns = patterns('superproof.superproof_web.views',
(r'^$','index'), #Shows your home page
(r'^challenge$','spcreatechallenge'),
(r'^player/`$','getlastactivity'),
(r'^yearlysummary/','yearlysummary'),
(r'^processchallenge$','processchallenge'),
(r'^activity/(\w{32})$','activitydetail'),
)
The yearlysummary url is loading sometimes. Other times, I get a 404 error. This happens with the exact same valid URL. I don't change anything in the URL, or in the code.
When I get the 404 error with debug turned on, my yearlysummary URL pattern isn't on the list.
Any ideas?
A couple things I noticed that could be an issue...
I notice you are not namespacing your included urls for each app. Not knowing what the other urls modules look like, I can assume its possible that you can have colliding urls. I Would recommend doing something like this:
urlpatterns = patterns('',
(r'', include('sp.sp_app.urls')),
(r'^activity/', include('sp.sp_api_activity.urls')),
(r'^player/', include('sp.sp_api_player.urls')),
(r'^web/', include('sp.sp_web.urls')),
)
Normally when you have url includes, they are for different apps, so you would want to namespace them to avoid two apps specifying the same url pattern.
Also, whats that back-tick in one of your urls? Did you mean to expect that?
(r'^player/`$','getlastactivity'),
jdi is spot on, on the analysis. I'll try to explain why exactly is there the issue, in your case.
You will notice that if you include (r'^', include('sp.sp_web.urls') as the first pattern in the main urls.py, your view will rightly load always.
When you have it as the last pattern, the reason it doesn't match the other times is that, that pattern is matching some other pattern in the earlier pattern, say [/w+]. The debug page, on a 404 of the url pattern, displays all the sub-url patterns of one of the patterns it matches. This is exactly why the pattern isn't on the urls displayed on the debug page.
Like jdi mentions it is a good practice to namespace the urls properly, so this doesn't occur. You can probably do it even without namespacing, but your regexes have to be proper, with the end character $ included, at least.

Django named routes not working with django.views.generic.simple.redirect_to

Having an issue with django's named routes. Django keeps raising the NoReverseMatch error when called as follows:
urlpatterns += patterns('django.views.generic.simple',
# tutorials
url(r'^tutorials/?$', 'redirect_to', {'url':'/tutorials/markers/'}, name='tutorials'),
(r'^tutorials/markers/?$', 'direct_to_template', {'template': 'page_tutorials_markers.html'}),
)
# in template:
tutorials
It looks pretty self-explanatory, yet I can't figure out why this route isn't being recognized as having a named route.
Thanks,
J
Reverse match tends to fail when you have optional characters. How will Django know whether to add the trailing slash or not?
I would recommend you remove the question mark, to enforce that the URLs end in a slash, and rely on the CommonMiddleware class to add the slashes as necessary.

redirect rule for nginx?

I am running my django app using nginx. I want to write a redirect rule such that
if user hit the url http://example.com/django/nginx/ then it redirect it to
http://example.com/django/#!/nginx/. I want o know the regex for it.
Thanks
You'll want to handle this on the client side (through Javascript, most likely), not through nginx.
From what I understand, the point of # in URLs (as per the spec) is that the portion that comes after # doesn't reach the server.
Also, see this question for some info on JS libraries for working with hash-bang urls: Are there any javascript libraries for working with hashbang/shebang (#!) urls?
Given you example I'm assuming that you are working with URLs in the form "http://1/2/3/" only, so nothing going beyond 3. Where you want to separate 2 and 3 with "/#!/". If that is the case you can try the following.
from django.views.generic.simple import redirect_to
urlpatterns = patterns('',
('^django/(?P<ajax_section>\w+)/$', redirect_to, {'url': '/django/#!/%(ajax_section)s/'}),
)
The above assumes that 2("django") in the URL will be fixed. If that is not the case you will have to try and make it a parameter as well.