Your URL pattern [<URLPattern> ] is invalid. DJANGO Urls.py file - python

I am getting this error:
ERRORS:
app_1 | ?: (urls.E004) Your URL pattern [<URLPattern '^static/media/(?P<path>.*)$'>] is invalid. Ensure that urlpatterns is a list of path() and/or re_path() instances.
app_1 | ?: (urls.E004) Your URL pattern [<URLPattern '^static/static/(?P<path>.*)$'>] is invalid. Ensure that urlpatterns is a list of path() and/or re_path() instances.
I don't know why I am getting this error. I have correctly added everything in my url patterns
urlpatterns = [
path("admin/", admin.site.urls),
path("api/v1/jobs/", include("jobs.urls")),
path("api/v1/company/", include("company.urls")),
]
if settings.DEBUG:
urlpatterns.extend(
[
static("/static/static/", document_root="/vol/web/static"),
static("/static/media/", document_root="/vol/web/media"),
path("__debug__/", include(debug_toolbar.urls)),
]
)

The function static() returns a list already, not a single pattern. It could be that the list contains a single path element, but it is a list nonetheless.
I suggest you change your code to:
if settings.DEBUG:
# add multiple paths using 'extend()'
urlpatterns.extend(static("/static/static/", document_root="/vol/web/static"))
urlpatterns.extend(static("/static/media/", document_root="/vol/web/media"))
# add a single path using 'append()'
urlpatterns.append(path("__debug__/", include(debug_toolbar.urls)))

Related

Django 1.11 url pattern error, how to solve?

When I try to fix the url in my urlpatterns it shows me this error :
The error:
Your URL pattern "url(r'^player/[?P[-\w\x20]+]/$', PlayerDetailView.as_view(), name='player-detail-view'),"
is invalid. Ensure that urlpatterns is a list of url() instance.
try removing the string 'url(r'^player/[?P[-\w\x20]+]/$', PlayerDetailView.as_view(), name='player-detail-view'),'. The list of urlpatterns should not have a prefix string as the first element.*
My Code :
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', HomePageView.as_view(), name='home-page'),
url(r'^teams/$', TeamsListView.as_view(), name='teams-list-view'),
url(r'^scores/$', ScoresListView.as_view(), name='scores-list-view'),
url(r'^player/[?P<slug>[-\w\x20]+]/$', PlayerDetailView.as_view(), name='player-detail-view'),
]
Can anyone help me??
The syntax is a bit off, you need to use round brackets (..) instead of square brackets [..] around a "capture group":
url(
r'^player/(?P<slug>[-\w\x20]+)/$',
PlayerDetailView.as_view(),
name='player-detail-view'
),
Furthermore if I recall correctly, a slug can not contain spaces, so you might want to remove the \x20.
Note that in django-2.0 and higher, the path(..) [Django-doc] function can be used, which has support for slugs like:
# Django 2.0 and higher
path('player/<slug:slug>/', PlayerDetailView.as_view(), name='player-detail-view'),
Then Django replaces the slug with a builtin pattern, which makes the URL patterns more "declarative".

Django URL pattern doesn't work

I have my urls.py included like this:
urlpatterns = [
path('files/', include('files.urls')),
]
then, in files/urls.py, I put this:
urlpatterns = [
path('', views.index, name='index'),
path(r'(?P<name>[a-z]+)', views.check, name='check')
]
So, I assume that when example.com/files works, so should example.com/files/somename, but it doesn't:
Using the URLconf defined in example.urls, Django tried these URL
patterns, in this order:
[name='index']
files/ [name='index']
files/ (?P<name>[a-z]+) [name='check']
The current path, files/somename, didn't match any of these.
What am I missing here?
You don't need to use regexp with path method. Instead you can simply specify str as argument type:
path('<str:name>/', views.check, name='check')
If you want to use regular expression, use re_path:
re_path(r'(?P<name>[a-z]+)', views.check, name='check')

adding static() to urlpatterns only work by appending to the list

I'm pretty sure there is a duplicate lying around, but couldn't find it.
When declaring a urlpatterns in urls.py on dev, I use the following successfully:
urlpatterns = [
# some routes
]
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Which understandably, works.
But if I try the following:
urlpatterns = [
# some routes,
static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
]
django server dies complaining:
?: (urls.E004) Your URL pattern [<URLPattern '^static\/(?P<path>.*)$'>] is invalid. Ensure that urlpatterns is a list of path() and/or re_path() instances.
Why aren't the two definitions equivalent? The return of static() should be the same:
return [
re_path(r'^%s(?P<path>.*)$' % re.escape(prefix.lstrip('/')), view, kwargs=kwargs),
]
And thus valid, but only works if I concatenate the element to the list instead of defining it in the list directly.
Why one method works but not the other?
Well the static function does not return a single url, so you can not add it as a single element to the list. By using +=, you actually append all the elements of the result of the static call to the list.
Recent versions of Python however have special syntax to include an iterable in a list by using the asterisk (*), so it can still be done with:
urlpatterns = [
# some routes,
*static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
]

In Django, how can I understand include() function?

I have started learning Django, I'm not sure what the include() function means.
Here is mysite/urls.py. - project
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^polls/', include('polls.urls')),
url(r'^admin/', admin.site.urls),
]
Here is polls/urls.py. - app in project
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
]
From django document, include() function was described as follows.
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.
I'm not sure what is that point, what is remaining string.
In case of the example above, what is remining string, what is url strings which was chopped off?
For example, from this URL:
polls/5/results
the URL rule:
url(r'^polls/', include('polls.urls')),
chops off the polls/ part of URL and sends the remaining string after polls/, whatever it might be, for example (see here more):
5/results/
to urls from the poll app's urls.py, where it will then be mapped to a view based on the URL rules defined in this file
Whenever it will encounter any url with /polls then it will include all the urls of polls app.
Example:
If you type /polls/hey
Then as soon as it sees /polls it will go to polls urls file and later it will search for:
hey/ matching over there.
Lets say there is one more entry in your polls/urls.py like
url(r'^articles/(?P<year>[0-9]{4})/$', views.year_archive),
here year is the query string parameter. so your url will look like
/polls/articles/2007 so in this case /polls/articles/ will matched up and 2007 will pass to year_archive method
In your example there is no chopped string, the URL comes back as simply polls/, but when you have another url such as '^new$' then that url is being chopped, merged with polls/ and it returns polls/new, hope this makes sense..

Match all urls without the prefix in Django

I'm currently using the following urls.py:
api_patterns = [
url(r'^users/', include('users.urls', namespace='user')),
]
internal_patterns = [
# ...
]
urlpatterns = [
url(r'^api/', include(api_patterns)),
url(r'^internal/', include(internal_patterns)),
url(r'^admin/', include(admin.site.urls)),
url(r'^(?!(?:api|internal|admin)/)', MainView.as_view()),
]
The point of this config is to render MainView if url doesn't have the api, internal or admin prefix:
/api/users/... — found
/api/foo/ — not found
/foo/ — found
How can I make it simplier and more intent revealing?
I think your intent will be more clear if you do this in two urls:
url(r'^(api|internal|admin)/', SomeView.as_view()),
url(r'^.*', MainView.as_view())
MainView will be executed only if a url does not begin with api, internal or admin.
SomeView will be executed if a url begins with api/internal/admin but doesn't match the patterns above it. You can customize this view to either return a default 404 page, or perform other functions as you need.
Using your examples:
/api/users will execute include(api_patterns)
/api/foo will execute SomeView
/foo will execute MainView
Edit
To address the first point in your comment: url patterns are regexes, while you can extract these into variables to remove duplication, it can make code hard to read. Here's one example for removing duplication (I'm sure you can come up with others):
d = OrderedDict([
(r'api', api_patterns),
(r'internal', internal_patterns),
(r'admin', admin.site.urls),
])
main_view_re = r'^!({})/'.format('|'.join(d.keys()))
urlpatterns = [url(r'^{}/'.format(k), include(v)) for k, v in d]
urlpatterns.append(url(main_view_re, MainView.as_view()))
For django >= 3 rather use re_path:
from django.urls import re_path
urlpatterns = [
re_path(r'^.*',MainView.as_view())
]
urlpatterns = [
url(r'^api/', include(api_patterns)),
url(r'^internal/', include(internal_patterns)),
url(r'^admin/', include(admin.site.urls)),
url(r'', MainView.as_view()),
]
Leaving no prefix would allow you to catch any URL that a user might try after the URL conf matches the api, internal and admin url's.

Categories

Resources