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)
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With