I am a beginner in django and don't understand the meaning "/" in urlpatterns. Here is the urlpatterns in my project urls. My first app's name is first.
urlpatterns = [
path('admin/', admin.site.urls),
path('first', include("first.urls"))
]
I found that it didn't work unless I amended it to following:
urlpatterns = [
path('admin/', admin.site.urls),
path('first/', include("first.urls"))
]
I don't understand what the meaning of '/' is. I googled but did not find an answer. Could anyone help me on this?
Another question is that the double quotes and single quote could be used either way. But is there any convention or better practice that I can follow to use single or double quote? Thanks a lot.
Short answer: it is used as a separator for the first and for the URL paths in your first app.
You are including the urlpatterns of the first app. Imagine that this app has as URL:
# first/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('foo/', foo)
]
Without the slash, the path to trigger foo is /firstfoo/ so it appends the two.
If you work with a slash, the path to trigger foo is /first/foo.
Related
I've got a site I'm working on where I need to match a parameter at the start
of the url:
test.com/the-data-slug
What is odd is I can't figure out why the following code dosen't work.
It dosen't match at all.
path('<slug:data-slug>/', DataLandingView.as_view(), name="data_landing")
I did get the following to work, but I know path is prefered over re_path.
re_path(r'^(?P<data-slug>\w+)/$', DataLandingView.as_view(), name="data_landing")
I'm really curious what I'm doing wrong with the path call, or is this just something path can't do?
Update:
Requested from commenters.
From urls.py these are the only url patterns in use.
urlpatterns = [
# Special Project level routing. Specifically routes to handle login/logout admin
path('admin/', admin.site.urls),
path('users/', include('django.contrib.auth.urls')),
path('accounts/', include('allauth.urls')),
# We are handling all convention level routing here as it makes more
# sence here as a master control router than in the individual projects
# Global Stuff for buisness
path('', HomePageView.as_view(), name='home'),
path('about/', AboutPageView.as_view(), name='about'),
# If we don't recoginze from the above we step down to the next layer
path('<slug:data-slug>', CLandingView.as_view(), name="c_landing")
]
Going to http://127.0.0.1:8000/abc-2020
and http://127.0.0.1:8000/abc-2020/
returns a 'Page Not Found' Exception
But if I use the following route with re_path. It works.
re_path(r'^(?P<c_name>[-\w]+)/$', CLandingView.as_view(), name="c_landing")
I am new to Django and trying to make a project, but I am facing a simple problem. I am writing a path in Django 2 for root and it's not working, but for other things it works. Can anyone point out why it's not working.
What is working:
path(r'home/', home, name='home'),
This is not working:
path(r'^$', home, name='home'),
And just to be clear: I am not loading both the line together. I comment one line at a time, so no order issues.
Beginning with Django 2 a new way of defining URL routes is introduced. There are the functions path and re_path.
You seem to mix some things. Here is how it should look like when using path:
from django.urls import path
urlpatterns = [
path('', home, name='home'),
# or
path('home/', home, name='home'),
]
From this example you can obviously use only one path. I gave them both for illustrating.
As you notice the paths aren't raw strings and don't contain regular expressions like ^ or $.
For using regular expressions use re_path.
This basic url issue is giving me a headache. I have two links I wish to take a fictitious user to: localhost/prediction and localhost/prediction/. The first works, the second doesn't with an error saying that the site doesn't exist. Any clue as to why?
URl Patterns:
urlpatterns = [
# ex: /prediction/
url(r'^', views.post_list),
# ex: /prediction/<number>/
url(r'^(?P<number>[0-9]+)/$', views.show_body)
]
View:
def show_body(request, number):
return HttpResponse(number)
You should change your pattern from
url(r'^', views.post_list),
to
url(r'^$', views.post_list),
There's no need to add a leading slash, because every URL has that. See the example in the Django docs.
I have trouble figuring out what trailing slash that causing an error in Django. This is the error:
?: (urls.W002) Your URL pattern '^/' has a regex beginning with a '/'.
Remove this slash as it is unnecessary.
My urls.py looks like this:
urlpatterns += [
#url('^$', direct_to_template, {'template': 'index.html'}, name='home'),
url('^$', mezzanine.blog.views.blog_post_list, name='home'),
url('^', include('main.urls')),
url('^', include('mezzanine.urls')),
]
And in my main.urls it doesn't exist any '/' before. How can I troubleshoot where the problem exists? Can I expand the error when I run the dev server with manage.py?
Edit:
This is my main/urls.py:
from django.conf.urls import patterns, include, url
from . import views
app_name = 'main'
urlpatterns = [
# Create Blog
url(r'^create-blog/$', views.create_blog, name='create_blog'),
# Lists
url(r'^blogs/$', views.blog_list, name='blog_list'),
url(r'^blogs/new/$', views.blogs_new, name='blogs_new'),
url(r'^top/$', views.top_lists, name='top_lists'),
url(r'^latest/$', views.latest_posts, name='latest_posts'),
# Tags
url(r'^tags/(?P<tag>[\w-]+)/$', views.tag, name='tag'),
url(r'^tags/$', views.tags, name='tags'),
# Avatars
url(r'^avatar/', include('avatar.urls')),
# Various
url(r'^welcome/$', views.welcome, name='welcome'),
url(r'^faq/$', views.faq, name='faq'),
url(r'^contact-us/$', views.contact, name='contact'),
]
Looking over the question again, perhaps you have literally defined a pattern as ^/ somewhere.
?: (urls.W002) Your URL pattern '^/' has a regex beginning with a '/'. Remove this slash as it is unnecessary.
This system check by django is printing out the pattern that is causing problems. I made a quick django example, and when I put in a url such as...
urlpatterns = [
url('^test1/$', views.test1, name='test1'),
url('^/test2/$', views.test2, name='test2'),
]
?: (urls.W002) Your URL pattern '^/test2/$' [name='test2'] has a regex beginning with a '/'. Remove this slash as it is unnecessary.
As you can see it is giving me my URL pattern exactly as it is defined, ^/test2/$. I think your problem is likely in some other part of your urls.py file or one of the other urls.py files, most likely an include because you do not have the trailing $ in the pattern nor a name for the view.
Try searching through your project for a url defined as '^/' is my recommendation.
I am trying to refactor out my application a little bit to keep it from getting too unwieldily. So I started to move some of the urlpatterns out to sub files as the documentation proposes.
Besides that fact that it just doesn't seem to be working (the items are not being rerouted) but when I go to the admin, it says that 'urlpatterns has not been defined'.
The urls.py I have at the root of my application is:
if settings.ENABLE_SSL:
urlpatterns = patterns('',
(r'^checkout/orderform/onepage/(\w*)/$','checkout.views.one_page_orderform',{'SSL':True},'commerce.checkout.views.single_product_orderform'),
)
else:
urlpatterns = patterns('',
(r'^checkout/orderform/onepage/(\w*)/$','commerce.checkout.views.single_product_orderform'),
)
urlpatterns+= patterns('',
(r'^$', 'alchemysites.views.route_to_home'),
(r'^%s/' % settings.DAJAXICE_MEDIA_PREFIX, include('dajaxice.urls')),
(r'^/checkout/', include('commerce.urls')),
(r'^/offers',include('commerce.urls')),
(r'^/order/',include('commerce.urls')),
(r'^admin/', include(admin.site.urls)),
(r'^accounts/login/$', login),
(r'^accounts/logout/$', logout),
(r'^(?P<path>.*)/$','alchemysites.views.get_path'),
(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root':settings.MEDIA_ROOT}),
The urls I have moved out so far are the checkout/offers/order which are all subapps of 'commerce' where the urls.py for the apps are so to be clear.
/urls.py in questions (included here)
/commerce/urls.py where the urls.py I want to include is:
order_info = {
'queryset': Order.objects.all(),
}
urlpatterns+= patterns('',
(r'^offers/$','offers.views.start_offers'),
(r'^offers/([a-zA-Z0-9-]*)/order/(\d*)/add/([a-zA-Z0-9-]*)/(\w*)/next/([a-zA-Z0-9-)/$','offers.views.show_offer'),
(r'^reports/orders/$', list_detail.object_list,order_info),
)
and the applications offers lies under commerce.
And so the additional problem is that admin will not work at all, so I'm thinking because I killed it somewhere with my includes.
Things I have checked for:
Is the urlpatterns variable accidentally getting reset somewhere (i.e. urlpatterns = patterns, instead of urlpatterns+= patterns)
Are the patterns in commerce.urls valid (yes, when moved back to root they work).
So from there I am stumped. I can move everything back into the root, but was trying to get a little decoupled, not just for theoretical reason but for some short terms ones.
Lastly if I enter www.domainname/checkout/orderform/onepage/xxxjsd I get the correct page. However, entering www.domainname/checkout/ gets handled by the alchemysites.views.get_path.
If not the answer (because this is pretty darn specific), then is there a good way for troubleshoot urls.py? It seems to just be trial and error. Seems there should be some sort of parser that will tell you what your urlpatterns will do.
Adding the following line in my urls.py worked for me:
from django.conf.urls import include
Have a look at the django docs for including other url confs. I think you might have misunderstood them. In particular
Whenever Django encounters include(), it chops off whatever part of the URL matched up to that point and sends the remaining string to the included URLconf for further processing.
As an example, you have
(r'^/checkout/', include('commerce.urls')),
(r'^/offers',include('commerce.urls')),
(r'^/order/',include('commerce.urls')),
This means that
/checkout/offers/
/offers/offers/
/order/offers/
will all match the url pattern (r'^offers/$','offers.views.start_offers') in commerce/urls.py.
If you want to define a view for /checkout/ in commerce.py, you need to add the pattern
(r'^$', 'path_to_your_view')
because the /checkout/ part will be chopped off by the include()
As, an aside:
In /commerce/urls.py, use
urlpatterns = patterns('',
...
for the first patterns you define. You can then use urlpatterns += later in the same file.