I creating an application and one of its urlconf is as follows
urlpatterns = [
path('', DashboardView.as_view(),name='dashboard:index'),
]
I am coming from PHP background (say Laravel) where we name our routes like below
dashboard:index - for get
dashboard:store - for post
dashboard:update - for patch etc...
So I named my route as above, but while performing the system check, the following warning comes up.
System check identified some issues:
WARNINGS: ?: (urls.W003) Your URL pattern '' [name='dashboard:index']
has a name including a ':'. Remove the colon, to avoid ambiguous
namespace references.
System check identified 1 issue (0 silenced).
So my question is what is the ideal naming format of URLs in Django in general.
dashboard_index ?
dashboard.index ?
I guess the best place to find some kind of convention is in the django admin app, where I found this:
urlpatterns = [
url(r'^$',
views.BaseAdminDocsView.as_view(template_name='admin_doc/index.html'),
name='django-admindocs-docroot'),
url(r'^bookmarklets/$',
views.BookmarkletsView.as_view(),
name='django-admindocs-bookmarklets'),
# and so on...
]
So, a string representing the url with dashes between words. I think is also important the name to be very explicit, not acronyms or shortened names.
EDIT:
Example of general url/path naming from the docs (2.1):
path('archive/', views.archive, name='news-archive')
Also it's a good idea to have in mind python code style.
Related
http://example.com/de/id-button/ - 200 OK
http://example.com/id/id-button/ - 200 OK
http://example.com/any-other-slug/ - 200 OK
http://example.com/id-button/ - 404 error:
Using the URLconf defined in example.urls, Django tried these URL patterns, in this order:
id/
The current path, id-button/, didn't match any of these.
urls.py file:
urlpatterns = i18n_patterns(
path('admin/', admin.site.urls),
path('', cache_page(cache_homepage)(homepage_views.index), name='index'),
path('search/', search_views.search, name='search'),
path('<slug:slug>/', item_views.item, name='item'),
prefix_default_language=False,
)
The item have a slug field in DB "id-button".
If I rename this to "idbutton":
http://example.com/idbutton/ - 200 OK
But I need to have url like: http://example.com/id-button/
Update:
It's accepted as a bug, but it's not moving for now:
https://code.djangoproject.com/ticket/31540
This is due to an interaction between LocaleMiddleware and i18n_patterns.
When LocaleMiddleware sees the request coming in, it tries to parse the language from the request. See https://github.com/django/django/blob/92507bf3ea4dc467f68edf81a686548fac7ff0e9/django/utils/translation/trans_real.py#L46 for the regular expression used. The allowed format is: any sequence of word characters, and optionally a dash and more word characters, after that it expects either the end of the string, or a /. In this case, it matches id-domain/, and understands that id-domain is the language prefix for that request, causing Django to activate the id language.
Then, the request goes through the URL routing layer, reaching as one of the first stops the https://github.com/django/django/blob/master/django/urls/resolvers.py#L301 . The get_language() command returns id, and the prefix thus searched for is id/, which id-domain/ does not match against. As the LocalePrefixPattern is the top-level resolver, it not matching causes nothing else to be tried.
(Is it a bug in Django? Maybe, I'd expect it seeing id-domain/ as language would make it also be used for language-prefix for the URL resolving. But even then it might not resolve your problem)
Hy all!
I'm new to python / django and I came across a problem that I can not solve. I have a route configured for the site's home (1) and a route configured for categories (2):
1) url(r'^$', IndexView().home, name='home')
2) url(r'^categoria/(?P<path>.*)/$', IndexView().by_category, name='by_category')
I need to set my home url to open a category by default, something like www.mysite.com/c=defaul_category
I tried in some ways, including: url (r '^ / (? P \ w +) / $', IndexView (). Home, name = 'home'). But I know it's incorrect.
So... I have no idea how to do this. Could someone help me?
Thank you
You should tell django that path in by_category url may be omitted. You have at least two options here:
1 - create one more url without path but with passed path variable as 3-rd argument in url:
url(r'^/(?P<c=vinhos>\w+)/$', IndexView().home, name='home')
url(r'^categoria/(?P<path>.*)/$', IndexView().by_category, name='by_category')
url(r'^categoria/$', IndexView().by_category,
{'path': 'default_path'}, name='default_category')
2 - change regex pattern to make it possible to omit path parameter. Here | (or sign) added in the end of path group:
url(r'^categoria/(?P<path>.*|)/$', IndexView().by_category, name='by_category')
More about omitting url parameters Django optional url parameters
I have this in my urls.py
from httpproxy.views import HttpProxy
urlpatterns += patterns('',
url(r'^proxy/(?P<url>.*)$', HttpProxy.as_view(base_url=settings.PROXY_URL))
)
And my settings.py
...
PROXY_URL = 'http://external.com'
...
My problem is when accessing the URL http://localhost:8000/proxy/, I can see from the log of http://external.com it is returning 404 because the url has an extra slash prepended so for example:
http://localhost:8000/proxy/test/ will log "GET //test/ HTTP/1.1" 404 15447
I have been digging but couldn't find the bone! If all the masters would be kind enough to lend a bone for this hunger?
Cheers!
Since no one answered (I even got a badge because no one answered, how cool is that?), I will post my solution, which was solved 2 days after the question was asked.
1 - Because of this issue pointed out by a friend, I have steered away from using django-http-proxy.
2 - So I resorted to a better library which proxies all HTTP Methods, unlike django-http-proxy that can only proxy GET. Meet django-revproxy.
3 - Which introduces another problem — The Cookie Conflict. This happens because I have two django instances. The solution is to explicitly declare the cookie path in one of your django app so it won't be using the same path. Just add in settings.py these two lines:
SESSION_COOKIE_NAME = "yourApp_session_id"
CSRF_COOKIE_NAME = "yourApp_csrftoken"
4 - That's it. I hope this solution will help those on the lookout.
I am building a site in english and simply want to offer a small subset of currencies. For SEO and caching I am planning to develop the following url structure with the prices being displayed in the relevant currencies.
Home(s)
site.com/
site.com/au/
site.com/us/
...
Categories Index Pages
site.com/categories/
site.com/au/categories/
site.com/us/categories/
...
Product Index Pages
site.com/categories/category1/
site.com/au/categories/category1/
site.com/us/categories/category1/
...
Product Pages
site.com/categories/category1/product-1/
site.com/au/categories/category1/product-1/
site.com/us/categories/category1/product-1/
...
This is my attempted url.py
urlpatterns = patterns('',
#url(r'^$', views.homeCurrency, {'cur_slug': '' }, name='home'),
url(r'^(?P<cur_slug>[:au|nz|us|eu|ca|uk]+)/$', views.homeCurrency, name='home'),
url(r'^categories/', include('parts.urls', namespace="parts")),
url(r'^(?P<cur_slug>[:au|nz|us|eu|ca|uk]+)/bike-parts/', include('parts.urls', namespace="parts")),
)
This is the sort of dynamic url I need in my base.html
Home
My problem is two fold (I think)
Firstly, I can't allow for the default case i.e. site.com(/) in the url pattern so that there is a common url name that can be used dynamically throughout each version of the site.
Secondly, even ignoring the default case, I am getting the following error:
Request Method: GET
Request URL: site.com/au/
Django Version: 1.5.4
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'home' with arguments '()' and keyword arguments '{}' not found.
Any help would be greatly appreciated as this is my first project in Django. Cheers
The first problem is with your regex. [] means character class, i.e. [a|bc] would match a, |, b or c but never bc.
Hence, your regex should be using groups ():
url(r'^(?P<cur_slug>au|nz|us|eu|ca|uk)/$', views.homeCurrency, name='home'),
If you're not 100% confident with regex, you should have a look into the excellent surlex library, which provides a neat little DSL for writing URL patterns.
from surlex.dj import surl
// a macro for valid currencies
surlex.register_macro('$', r'au|nz|us|eu|ca|uk')
urlpatterns = patterns('',
// macros are only used in match groups (surrounded with `<>`)
surl(r'<cur_slug:$>/$', views.homeCurrency, name='home'),
surl(r'<cur_slug:$>/bike-parts/$', include('parts.urls', namespace="parts")),
)
regarding your choice of "dynamic url", why not instead base your url roots on locale, and choose the correct currency based on locale. REF
I've been looking all over and can't find what I'm looking for.
I've found a way to redirect urls without parameters and keywords - but how to do it with parameters?
I want to redirect this:
(r'^andelsboligforeninger/(?P<page>[\d]*?)/$', 'cooperatives'),
to this:
(r'^liste-over-andelsboligforeninger/(?P<page>[\d]*?)/$', 'cooperatives'),
It should be a permanent redirect. This will be good for the SEO, and I get so many debug mails because of googlebot.
It seems I've found my answer in the django docs - I didn't look hard enought after all!
https://docs.djangoproject.com/en/1.1/ref/generic-views/
urlpatterns = patterns('django.views.generic.simple',
('^foo/(?P<id>\d+)/$', 'redirect_to', {'url': '/bar/%(id)s/'}),
)
First of all you need to do some changes in the url. Use url function and then give a name to the url. You have some issues in your url, for example you have used ?P but did'nt give a name to the capturing group. Second [\d]*? there is no need for ? because * means there can be a digit or not at all. So after considering all the above mentioned bugs and techniques in the end your url should look like this:
url(r'^liste-over-andelsboligforeninger/(?P<cooperative_id>\d*)/$', 'cooperatives', name="cooperatives")
Then in the view you can use reverse url resolution as:
redirect(reverse('cooperatives', kwargs={'cooperative_id': some_id}))