how to add static files in django

To add static files in Django, follow these steps:

  1. Create a "static" directory: Inside your Django project directory, create a new directory called "static". This is where you will store all your static files such as CSS, JavaScript, and images.

  2. Configure settings.py: Open your project's settings.py file and locate the STATIC_URL setting. By default, it is set to '/static/'. Ensure that this value matches the URL where you want to serve your static files.

  3. Collect static files: Run the following command in your terminal to collect all your static files into a single directory:

python manage.py collectstatic

This command will gather all the static files from your apps and copy them to the STATIC_ROOT directory, which is specified in the settings.py file.

  1. Load static files in templates: In your templates, you need to load the static files tags to include them in your HTML. Add the following line at the beginning of your template file:

{% load static %}

This tag will load the static files template tags so you can reference your static files.

  1. Reference static files: To reference a static file in your templates, use the static template tag followed by the file's path relative to the static directory. For example, to include a CSS file, use the following code:

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

This will generate the correct URL for the static file.

  1. Serve static files during development: During development, Django's built-in development server automatically serves static files for you. However, you need to add the following code to your project's urls.py file to enable this:

```python from django.conf import settings from django.conf.urls.static import static

urlpatterns = [ # Your URL patterns here ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) ```

This code will serve your static files when you're running the development server.

That's it! By following these steps, you should be able to add static files in Django and serve them correctly.