Django static url in css

Django Static Files and Templates

Static files like CSS, JavaScript, and fonts are a core piece of any modern web application. They are also typically confusing for Django newcomers since Django provides tremendous flexibility around how these files are used. This tutorial will demonstrate current best practices for configuring static files in both local development and production.

Local Development

For local development the Django web server automatically serves static files and minimal configuration is required. A single Django project often contains multiple apps and by default Django will look within each app for a static directory containing static files.

For example, if one of your apps was called blog and you wanted to add a CSS file to it called base.css , you would need to first create a new directory called blog/static and then add the file within it at the location blog/static/style.css .

However, since most Django projects involve multiple apps and shared static files, it is common on larger projects to instead create a base-level folder typically named static . This can be added from the command line with the mkdir command:

For demonstration purposes let’s also add a base.css file. Assuming you had only just started a new Django project with the startproject command your directory structure would now look like this:

├── django_project │ ├── __init__.py | ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── manage.py ├── static │ ├── base.css 

Within the settings.py file, near the bottom, there is a single line of configuration for static files called STATIC_URL, which is the location of static files in our project.

# django_project/settings.py STATIC_URL = "static/" 

This means that all static files will be stored in the location http://127.0.0.1:8000/static/ or http://localhost:8000/static/ . And if you wanted to access the base.css file its location would be http://127.0.0.1:8000/static/base.css or http://localhost:8000/static/base.css .

Читайте также:  Полосы прокрутки

Loading static files into Templates

Loading static files in a template is a two-step process:

There are two main ways to structure templates in a Django project as outlined in this tutorial. Let’s assume we are using a templates/base.html file for a Blog project. To add our static base.css file to it we’d start by adding at the top of the file and then use the tag with the path to it. Since the STATIC_URL is already set to /static/ we don’t need to write the full route out of static/base.css and can instead shorten it to base.css .

  html> head> title>Learn Djangotitle> link rel="stylesheet" href=""> head> . html> 

If you save and reload the web page, you’ll see the changes. Adding links for either images in an img folder or JavaScript in a js folder would look as follows:

collectstatic

Serving static files in production requires several additional steps and is where the confusion typically arises for Django newcomers. Local development is designed to keep things nice and easy, but it is far from performant. In a production environment it is more efficient to combine all static files in the Django project into one location and serve that a single time.

Django comes with a built-in management command, collectstatic, that does this for us.

We need three more configurations in our settings.py file though before collectstatic will work properly. The first is STATICFILES_DIRS which defines additional locations, if any, the staticfiles app should look within when running collectstatic . In our simple example the only location for local files is the static directory so we will set that now.

# django_project/settings.py STATIC_URL = "static/" STATICFILES_DIRS = [BASE_DIR / "static"] # new 

Next up is STATIC_ROOT which sets the absolute location of these collected files, typically called staticfiles . In other words, when collecstatic is run locally it will combine all available static files, as defined by STATICFILES_DIRS and place them within a directory called staticfiles . This is how we set that configuration.

# settings.py STATIC_URL = "static/" STATICFILES_DIRS = [BASE_DIR / "static"] STATIC_ROOT = BASE_DIR / "staticfiles" # new 

The final step is STATICFILES_STORAGE, which is the file storage engine used when collecting static files with the collectstatic command. By default, it is implicitly set to django.contrib.staticfiles.storage.StaticFilesStorage . Let’s make that explicit for now in our django_project/settings.py file.

# settings.py STATIC_URL = "static/" STATICFILES_DIRS = [BASE_DIR / "static"] STATIC_ROOT = BASE_DIR / "staticfiles" STATICFILES_STORAGE = "django.contrib.staticfiles.storage.StaticFilesStorage" # new 

Now we can run the command python manage.py collectstatic which will create a new staticfiles directory.

(.venv) $ python manage.py collectstatic 

If you look within it you’ll see that staticfiles also has folders for admin (the built-in admin has its own static files), staticfiles.json , and whatever directories are in your static folder.

If you now add a new static file to the static directory it will immediately be available for local usage. It is only for production where the file won’t be present unless you run python manage.py collectstatic each and every time. For this reason, running collectstatic is typically added to deployment pipelines and is done by default on Heroku.

  • STATIC_URL is the URL location of static files located in STATIC_ROOT
  • STATICFILES_DIRS tells Django where to look for static files in a Django project, such as a top-level static folder
  • STATIC_ROOT is the folder location of static files when collectstatic is run
  • STATICFILES_STORAGE is the file storage engine used when collecting static files with the collectstatic command.

Production

Even though we’ve configured our Django project to collect static files properly, there’s one more step involved which is not included in the official Django docs. That is the configuration of WhiteNoise to serve the static files in production. The first step is to install the latest version of the package:

(.venv) $ python -m pip install whitenoise==6.0.0 

Then in the django_project/settings.py file make three changes:

  • add whitenoise to the INSTALLED_APPS above the built-in staticfiles app
  • under MIDDLEWARE , add a new WhiteNoiseMiddleware on the third line
  • change STATICFILES_STORAGE to use WhiteNoise .

It should look like the following:

# settings.py INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "whitenoise.runserver_nostatic", # new "django.contrib.staticfiles", ] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "whitenoise.middleware.WhiteNoiseMiddleware", # new "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] . STATIC_URL = "static/" STATICFILES_DIRS = [BASE_DIR / "static"] STATIC_ROOT = BASE_DIR / "staticfiles" STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' # new 

That’s it! Run python manage.py collectstatic again so that the files are stored using WhiteNoise. And then deploy with confidence to the hosting platform of your choice.

CDNs

Content Delivery Networks (CDNs) are useful on very high traffic sites where performance is a concern. Rather than serving static files from your Django server you post them on a dedicated CDN network and then call them. The official WhiteNoise documentation has additional instructions on this step.

Conclusion

Configuring static files is a core part of any Django project. If you’d like to see multiple examples of real-world Django projects alongside detailed explanation, check out my book Django For Beginners. The first several chapters can be read for free online.

© LearnDjango | Django is a registered trademark of the Django Software Foundation.

Источник

Use of Django’s static templatetag in css file to set a background image

Setting an image as a background property in CSS can be a problem in Django as it recommends to refer to your static files with the static template tag, but then you realize load_static doesn’t work from CSS files. So how do you do something like background-image: url(<% static 'images/cover.jpg' %>); in CSS? Here are two approaches to solve this issue.

Concept

There is a special setting that handles how static files are served: STATIC_URL. The static ( django.templatetags.dostatic ) templatetag, joins the given path with the above mentioned STATIC_URL setting. In most cases the STATIC_URL settings is /static/ , so you can use /static/images/bg.jpg in your CSS as long as this setting doesn’t change. Having that in mind you can use it, and if not you can choose to apply that style in the HTML directly using , that way you are sure it will always use the correct setting and be accessible.

Solution 1: Background in HTML

div style="background-image: url();">   div> 

Solution 2: Static path

cover   background: url('/static/img/home-cover.jpg'); > 

References

Marcelo Canina

I’m Marcelo Canina, a developer from Uruguay. I build websites and web-based applications from the ground up and share what I learn here.

Articles

  • How to create a reusable Django app and distribute it with PIP or publish to pypi.orgJune 29, 2021
  • How To Serve Multiple Django Applications with uWSGI and Nginx in Ubuntu 20.04October 26, 2020
  • How to add favicon to Django in 4 stepsSeptember 3, 2020
  • Categories in Django with BreadcrumbsAugust 30, 2020
  • How To Migrate From SQLite To PostgreSQL In Django In 3 stepsAugust 28, 2020
  • Practical guide to internationalize a Django app in 5 steps.August 24, 2020
  • Disable new users singup when using Django’s allauth packageSeptember 3, 2019
  • How to add ads.txt to Django as requested by Google AdsenseAugust 30, 2019
  • Have multiple submit buttons for the same Django formJuly 2, 2019
  • Better Testing with Page Object Design in DjangoMay 1, 2019
  • Generating slugs automatically in Django without packages — Two easy and solid approachesFebruary 14, 2019
  • How to set up Django tests to use a free PostgreSQL database in HerokuFebruary 13, 2019
  • Dynamically adding forms to a Django FormSet with an add button using jQueryFebruary 6, 2019
  • Use of Django’s static templatetag in css file to set a background image
  • Activate Django’s manage.py commands completion in Bash in 2 stepsJanuary 29, 2019
  • Sending Emails with Django using SendGrid in 3 easy stepsJanuary 9, 2019
  • Adding Users to Your Django Project With A Custom User ModelSeptember 21, 2018
  • Setting Up A Factory For One To Many Relationships In FactoryboyApril 17, 2018
  • Generate UML class diagrams from django modelsMarch 24, 2018
  • Set Up Ubuntu To Serve A Django Website Step By StepJuly 3, 2017
  • Django Project Directory StructureJuly 16, 2016
  • How to Have Different Django Settings for Development and Production, and environment isolationJune 10, 2016
  • Django OverviewJune 2, 2016

Subcategories

Django Forms
  • Adding a Cancel button in Django class-based views, editing views and formsJuly 15, 2019
  • Using Django Model Primary Key in Custom Forms THE RIGHT WAYJuly 13, 2019
  • Django formset handling with class based views, custom errors and validationJuly 4, 2019
  • How To Use Bootstrap 4 In Django FormsMay 25, 2018
  • Understanding Django FormsApril 30, 2018
  • How To Create A Form In DjangoJuly 29, 2016

This article explains different approaches to solve the problem of having a background image url set in CSS

Simple IT 🤘 Rocks

Except as otherwise noted, the content of this page is licensed under CC BY-NC-ND 4.0 . Terms and Policy.

Источник

Оцените статью