# Handling Static files in Django

Static files in Django refer to files that do not change and are served directly to the user. These files include things like CSS stylesheets, JavaScript files, images, fonts, and other resources that are used to enhance the look and functionality of a web application. Unlike media files, which are user-uploaded and can vary, static files are usually the same for all users and are served in their original form.

### Scenario: Building a Simple Webpage with Static Files

#### [Link to theme(template)](https://filetransfer.io/data-package/jFAdaZim#link)

[Link to project](https://filetransfer.io/data-package/2J1nga6Z#link)

Step 1: Create a New Django Project and App

Make a folder

```bash
mkdir my_project
```

Go to that folder

```bash
cd my_project
```

Make virtual environment

```bash
python -m venv envname
```

Activate the environment and install django

IN WINDOWS

```bash
.\envname\Scripts\activate
```

In Unix/Linux Systems

```bash
source envname/bin/activate
```

Install django

```bash
pip install django
```

1. **Create a new Django project:**
    
    ```bash
    django-admin startproject my_project .
    ```
    
2. **Create a new app within the project:**
    
    ```bash
    python manage.py startapp my_app
    ```
    
3. **Add the new app to**`INSTALLED_APPS` in [`settings.py`](http://settings.py):
    
    ```python
    # settings.py
    INSTALLED_APPS = [
        ...
        'my_app',
    ]
    ```
    

#### Step 2: Create Static Files Directory and Files

1. **Create a**`static` directory in the project root:
    
    ```bash
    |-- my_project/
    ├── my_app/
    ├── static/
    │   ├── css/
    │   │   └── style.css
    │   ├── js/
    │   │   └── script.js
    │   └── images/
    │       └── logo.png
    ├── manage.py
    └── db.sqlite3
    ```
    
2. **Create CSS file (static/css/style.css):**
    
    ```css
    /* static/css/style.css */
    body {
        background-color: #f0f0f0;
        font-family: Arial, sans-serif;
    }
    
    h1 {
        color: #333;
    }
    ```
    
3. **Create JavaScript file (static/js/script.js):**
    
    ```javascript
    // static/js/script.js
    document.addEventListener('DOMContentLoaded', function() {
        console.log("HELLO DJANGO FORM JS");
    });
    ```
    
4. **Add an image (static/images/logo.png):**
    
    (Add any logo image you have.)
    

#### Step 3: Configure Settings

1. **Configure**[`settings.py`](http://settings.py) for static files:
    
    ```python
    # settings.py
    STATIC_URL = '/static/'
    STATICFILES_DIRS = [
        BASE_DIR / "static",
    ]
    ```
    
2. Configure `settings.py` for template folder
    
    ```bash
    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            #update here
            'DIRS': [BASE_DIR/"templates"],
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',
                    'django.template.context_processors.request',
                    'django.contrib.auth.context_processors.auth',
                    'django.contrib.messages.context_processors.messages',
                ],
            },
        },
    ]
    ```
    

####   
Step 4: Create a Template

1. **Create a template directory in the app:**
    
    ```bash
    my_project/
    ├── templates/
    │   └── index.html
    ```
    
2. **Create the HTML template (templates/index.html):**
    
    ```html
    {% load static %}
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Static Files Example</title>
        <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}">
    </head>
    <body>
        <h1>Hello, Django!</h1>
        <img src="{% static 'images/logo.png' %}" alt="Logo">
        <script type="text/javascript" src="{% static 'js/script.js' %}"></script>
    </body>
    </html>
    ```
    

#### Step 5: Create a View and URL

1. **Create a view in**`my_app/`[`views.py`](http://views.py):
    
    ```python
    from django.shortcuts import render
    
    def index(request):
        return render(request, 'index.html')
    ```
    
2. **Create a URL pattern in**`my_app/`[`urls.py`](http://urls.py):
    
    ```python
    from django.urls import path
    from .views import index
    
    urlpatterns = [
        path('', index, name='index'),
    ]
    ```
    
3. **Include the app's URLs in the project's**[`urls.py`](http://urls.py):
    
    ```python
    # my_project/urls.py
    from django.contrib import admin
    from django.urls import path, include
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('', include('my_app.urls')),
    ]
    ```
    

#### Step 6: Run the Development Server

1. **Run the development server:**
    
    ```bash
    python manage.py runserver
    ```
    
2. **Open a web browser and navigate to**[`http://127.0.0.1:8000/`](http://127.0.0.1:8000/).
    

You should see a styled page with an Console message saying "Hello, Django from JS" and an image displayed. The CSS file is applied for styling, the JavaScript file for the alert, and the image file is displayed from the static directory.

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">Open Inspect and Console to see JS output message</div>
</div>
