The previous solution was to convert the time in the front-end interface JS, which was not very good and found that there was an incorrect display in IE. Therefore, we plan to use the Django custom filter method. There are some precautions that may be mistaken if you are not careful, leading to page errors.
1. Add the templatetags directory.
Note that:
- The directory name must be templatetags so that Django can find it.
- Location of the Directory templatetags.
For example, my app directory is ncblog (App. yaml directory). In the ncblog directory, there is also a directory named Nancy. At this time, I created a directory named templatetags under the Nancy directory and put an empty _ init __. py. The directory structure is as follows:
Ncblog
---- Nancy
---- Blog
---- Templatetags
2. Set installed_apps in settings. py
To locate the templatetags, we need to add a path to nstalled_apps in settings. py, for example, add:
Installed_apps = (
' Django. contrib. auth ' ,
' Django. contrib. contenttypes ' ,
' Django. contrib. Sites ' ,
' Nancy ' , # I added this
) 3. compile our filter.
Create a file with any file name in the templatetags directory, such as filters. py. Now we want to convert the time zone into a filter. ThereforeCodeAs follows:
From Django Import Template
From Datetime Import Timedelta
Register = Template. Library ()
Def Timezone (value, offset ):
Return Value + Timedelta (hours = Offset)
Register. Filter (timezone) 4. Add {% load filters %} at the beginning of the template file, and then you can use it like this: {Log. Date | Timezone: 8 | Date: " Y-m-d h: I: S " }}