Experiment 20: Configuring Django to
Handle Static Files
1. Project Setup
Open your terminal and run the following commands:
django-admin startproject loyolaproject
cd loyolaproject
python manage.py startapp loyolaapp
2. Folder Structure
Inside the `loyolaapp` directory, create the following folder structure:
- static/
- css/
- images/
- javascript/
- templates/
- home.html
3. Configure settings.py
In `loyolaproject/settings.py`, add:
import os
STATIC_DIR = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = [STATIC_DIR,]
In the TEMPLATES section:
'DIRS': [os.path.join(BASE_DIR, 'templates')]
Also ensure 'loyolaapp' is added to INSTALLED_APPS.
4. Create HTML Template
Create `home.html` inside the templates folder with:
{% load static %}
<link href="{% static 'css/sample.css' %}" rel="stylesheet">
<script src="{% static 'javascript/sample.js' %}"></script>
<img src="{% static 'images/india.jpg' %}" ...>
5. Create CSS and JavaScript Files
In `static/css/sample.css`:
h1 { color: orange; font-size: 60px; }
In `static/javascript/sample.js`:
alert("welcome to loyola college");
6. Configure Views
In `loyolaapp/views.py`:
from django.shortcuts import render
def index(request):
context = {'eid': '101', 'ename': 'John Doe', 'eaddress': 'Chennai', 'salary': '50000'}
return render(request, 'home.html', context)
7. Setup URLs
In `loyolaapp/urls.py`:
from django.urls import path
from . import views
urlpatterns = [path('', views.index, name='index')]
In `loyolaproject/urls.py`:
from django.urls import path, include
urlpatterns = [
path('', include('loyolaapp.urls')),
path('admin/', admin.site.urls),
]
8. Run the Server
In your terminal, run:
python manage.py runserver
Open http://127.0.0.1:8000/ in your browser to view the project.