Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 288
yivi Avatar asked May 10 '18 13:05

yivi


1 Answers

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)
]
like image 174
Willem Van Onsem Avatar answered Sep 21 '22 15:09

Willem Van Onsem