top of page
Writer's pictureCodersarts AI

How to add static files in django projects | How to add 'html' files and static(js,css,imag


To add static files(css, js files, images) some basic changes are made in django files as per given below code files:


First we create html file by creation directory 'templates' in our in app folder like this:


And then after create html files(index.html). Go to the setting.py file and make changes in this file like this:

TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', ], }, }, ]

After adding this code

TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(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', ], }, }, ]

Create another directory static in Appfolder(helloworld) in create any static files(like css, js, image) inside it:

Add css file:

To insert CSS file in project first create a directory in main project folder whose name is static. After that some changes are made to run the code.

First add this load code at the top of of index.html page:

<!DOCTYPE html> {% load static %} <html lang="en"> <head>

After this go to the setting.py and changes in the static part which is located at the last in the setting.py file:

# Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.2/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR,'static') ]

And run the project.

Project 1:

Print Hello world:

url.py:

First set path in url.py

from django.contrib import admin from django.urls import path from helloworld.views import Hello urlpatterns = [ path('admin/', admin.site.urls), path('helloworld/',Hello) //set path ‘helloword/’and pass Hello

method

]

Views.py:

After set path in url.py make changes in views.py file.

from django.http import HttpResponse def Hello(request): //add method hello return HttpResponse("Hello")

# Create your views here.

Setting.py:

Add app name to the setting.py file:

INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'helloworld', //app name ]


If you like Codersarts blog and looking for Assignment help, Project help, Programming tutors help and suggestion you can send mail at contact@codersarts.com.


27 views0 comments
bottom of page