PART-5

Static Files and Filters In Django

This chapter will teach you the following:

  • Using humanize filter to render posted on
  • Create our pages responsive

Let’s add the bootstrap’s starter template to our base.html file to make all our templates responsive and be able to use the bootstrap classes.

You can notice that all the pages will be responsive now,design your base.html file as you want.

Here’s my design for the website..

base.html
home.html

for now, the about.html is like this,

about.html
about.html

Static files

Static files include stuff like CSS, JavaScript and images that you may want to serve alongside your site.

{% load static %}, uses Django's special template tag syntax to tell the template engine to use the files in the static folder in this template.

The static folder can be created anywhere in the project i.e., either in your root directory(blog_project) or in app directory(blogapp), if you choose the former one, in the settings.py you’ll need to add a tuple STATICFILES_DIR and a variable STATIC_ROOT, where you specify django to look for the static files in the BASE_DIR rather than looking for it in a particular app.For now I have choosen the later one,and have put the static folder in he blogapp just like templates folder..

You can put your css, js and images understatic/blogapp/filename.ext or under static/blogapp/foldername/filename.ext I have used the former one.

Filters

filters take data piped to them and output it in a formatted way. Django templates have access to the humanize collection of filters, which make data more human readable.

To use Django’s humanize filters, you first need to edit some settings. Open up blog_project/settings.py and edit the INSTALLED_APPS list to this:

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.humanize', #Add this line.Don't forget the trailing comma
...
]

We can now use a filter in our templates. I’ve used the naturaltime filter to make the date published easier to read.

There are many more filters included in the humanize package. Read about them here.

Posting Django Tutorials with Beginner to Advanced Projects

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store