Django templates and static images

Akhila
1 min readFeb 15, 2021

Import Django template and static folders in settings.py file .

How to create a django template.?

  1. Create a templates folder in your directory.
  2. Create a file index.html (optional name) and create text for demo purpose.
  3. Go to views.py in django-app and render the html file ex: return render(request,’index.html’)
  4. Make sure about the mapping in the urls to views.
  5. Go to your django project settings file( django project folder = django-admin startproject <django-project-folder>)
  6. Create a variable TEMPLATE_DIR = <path-of-the-templates-folder>
  7. Add the variable TEMPLATE_DIR to DIRS array in TEMPLATES array in settings.py file. (TEMPLATES array is already created in settings.py by django)
  8. Runserver to see the text mentioned in the index.html

How to create a static images.?

  1. Create a folder static
  2. Create a folder images in static folder
  3. Save image file(jpg, png) in images folder
  4. Go to settings.py and create a new variable with static folder path ex: STATIC_DIR = <path-to-static-folder>
  5. Got to end of the setting.py file and under the STATIC_URL create an array and add STATIC variable (STATIC_URL is already created by django)
  6. Example STATICFILES_DIRS = [ STATIC_DIR,]
  7. Now run the server and you can see the image in the url
  8. http://127.0.0.1:8080/static/images/<image-file-name>
  9. Insert in html file, insert {% load staticfiles %} at the top of html page under <!DOCTYPE html> tag
  10. The use this code {% static ‘images/ss.png’ %} where you need the image
  11. Example: <img src=”{% static ‘images/ss.png’ %}” alt=””>
  12. You can see the image in the html file when server is up.

--

--