Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want an exception, if django template tag `static` renders a broken URL

I want to see an exception, if settings.DEBUG is true and line like this gets processed by the template engine:

  <link rel="stylesheet" type="text/css" 
        href="{% static "foo/css/file-name-with-typo.css" %}">

Docs for the static template tag: https://docs.djangoproject.com/en/1.9/ref/contrib/staticfiles/#static

Background: An exception would trigger our Continous Integration system to fail and the broken could would not go live. I don't want to run code in production which produces broken links.

like image 691
guettli Avatar asked Oct 31 '22 10:10

guettli


1 Answers

Override the url() method to raise an error if the file doesn't exist:

from django.core.files.storage import FileSystemStorage


class CustomFileSystemStorage(FileSystemStorage):
    def url(self, name):
        if not self.exists(name):
            raise ValueError('"%s" does not exist.' % name)
        return super(CustomFileSystemStorage, self).url(name)

In your settings.py:

DEFAULT_FILE_STORAGE = 'mymodule.CustomFileSystemStorage'
like image 118
Seán Hayes Avatar answered Nov 09 '22 12:11

Seán Hayes