Django static files: any way to get finer control?

The Django static files feature allows you to specify specific directories that are “compiled” into a shared folder. This is great, but is there a way to get more granular control than just having specific folders? For example, is there a way to indicate ...

  • Include specific files
  • Exclusion of specific files
  • Exclude individual subdirectories

For example, I would say "collect all the files in this folder, except for this one file and this one directory." Alternatively, I could do the same if I could select specific files, and then select all the subdirectories of this one directory (except the one I don’t need).

Is it possible?

+4
source share
1 answer

I wrote a custom django-admin command to enable the parameter COLLECT_STATIC_IGNORE.

First create the following structure in any application folder:

appname/
    management/
        __init__.py
        commands/
            __init__.py
            _private.py
            collectstatic.py

In collectstatic.py put:

from django.contrib.staticfiles.management.commands.collectstatic import Command
from django.conf import settings

class Command(Command):

    def set_options(self, **options):
        """
        Set instance variables based on an options dict
        """
        self.interactive = options['interactive']
        self.verbosity = int(options.get('verbosity', 1))
        self.symlink = options['link']
        self.clear = options['clear']
        self.dry_run = options['dry_run']
        ignore_patterns = options['ignore_patterns']
        if options['use_default_ignore_patterns']:
            ignore_patterns += ['CVS', '.*', '*~']
            ignore_patterns += settings.COLLECT_STATIC_IGNORE # Added.
        self.ignore_patterns = list(set(ignore_patterns))
        self.post_process = options['post_process']

Or, better yet, like @CantucciHQ, use super :

class Command(Command):

    def set_options(self, **options):
        super(Command, self).set_options(**options)
        self.ignore_patterns += settings.COLLECT_STATIC_IGNORE        
        self.ignore_patterns = list(set(self.ignore_patterns))

This overrides the function set_optionsfrom the built-in command collectstatic.

In settings.py add COLLECT_STATIC_IGNORE. This example ignores scss files and all files in the admin folders.

COLLECT_STATIC_IGNORE = ['*.scss', 'admin', ... ] 

Then:

python manage.py collectstatic

Flags work this way by adding something to COLLECT_STATIC_IGNORE, you can use --clearto clear existing files before trying to copy or link the source file.

python manage.py collectstatic --clear
+3
source

Source: https://habr.com/ru/post/1527354/


All Articles