django 自定义过滤器
-
创建模型
from django.db import models class User(models.Model): # 用户名 username = models.CharField(max_length=32,unique=True) # 密码 password = models.CharField(max_length=255) # 添加时间 addtime = models.DateTimeField(auto_now_add=True) class Meta: # 指定表名 db_table = 'user'
-
创建视图函数
from django.shortcuts import render from django.views import View from . import models class UserView(View): def get(self,request): user = models.User.objects.all() return render(request,'index.html',{"user":user})
-
路由文件
from django.urls import path from . import views urlpatterns = [ path('user/',views.UserView.as_view()) ]
-
创建模版文件
{% load mytags %} <body> <table> <tr> <td>id</td> <td>name</td> <td>password</td> <td>addtime</td> </tr> {% for i in user %} <tr> <td>{{ i.id }}</td> <td>{{ i.username }}</td> <td>{{ i.password }}</td> <td>{{ i.addtime | myTime }}</td> </tr> {% endfor %} </table> </body>
-
创建
templatetags
目录 并 创建自定义过滤器文件mytags.py
from django import template register = template.Library() @register.filter def myTime(val): return val.strftime('%Y-%m-%d %H:%M:%S')