How to use static files in Django templates



Image not found!!

In Django, static files such as CSS, JavaScript, and images are typically stored in the "static" directory within your Django app. To use these static files in your templates, you can follow these steps:

  1. Organize your static files: Place your static files in a "static" directory inside your app. The structure might look like this:

    arduino
    your_app/ ├── static/ │ ├── your_app/ │ │ ├── css/ │ │ │ └── style.css │ │ ├── js/ │ │ │ └── script.js │ │ └── img/ │ │ └── logo.png
  2. Settings Configuration: Make sure that the django.contrib.staticfiles app is included in your INSTALLED_APPS in the settings.py file:

    python
    INSTALLED_APPS = [ # ... 'django.contrib.staticfiles', # ... ]

    Also, ensure that the django.contrib.staticfiles.finders.AppDirectoriesFinder is included in the STATICFILES_FINDERS:

    python
    STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ]
  3. Load static files in templates: In your template, load the static template tag at the top of the file:

    html
    {% load static %}
  4. Use static files in your template: You can use the {% static %} template tag to generate the URL for your static files. For example, if you have a CSS file in your css directory, you can include it in your template like this:

    html
    <link rel="stylesheet" type="text/css" href="{% static 'your_app/css/style.css' %}">

    Similarly, for images:

    html
    <img src="{% static 'your_app/img/logo.png' %}" alt="Logo">

    And for JavaScript:

    html
    <script src="{% static 'your_app/js/script.js' %}"></script>
  5. Run collectstatic command: When you deploy your project to production, or whenever you make changes to your static files, run the following command to collect static files from all your apps into a single directory:

    bash
    python manage.py collectstatic

    This will copy all the static files to the STATIC_ROOT directory, which is specified in your settings. Ensure that the STATIC_ROOT directory is configured correctly.

That's it! Now your Django templates should be able to use static files without any issues.