解决方案
参考 Writing your first Django app, part 3 文档,以获取在 Django 中使用视图及模板的方法。
在 views.py 中:
进行相关的业务逻辑处理,
并使用 HttpResponse() 来显示页面,或使用 render() 来显示页面;
通过 Http404() 或 get_object_or_404() 进行相关错误处理;
在 template/<app-name>/ 中,添加相关模板文件;
并在模板文件中使用模板语言来显示页面;
通过 url() 的 name 参数定义的名称来引用地址,以防止硬编码;
通过命名空间的方式来定义和引用 URL 防止出现命名冲突的情况;
常见问题
注入变量到所有模板
python – Django – How to make a variable available to all templates? – Stack Overflow
1)Add custom_app to INSTALLED_APPS in settings.py (you've done it already, right?); 2)Create a context_processors.py into custom_app folder; 3)Add the following code to that new file: def categories_processor(request): # request 参数是必须的 categories = Category.objects.all() return {'categories': categories} 4)Add context_processors.py to TEMPLATE_CONTEXT_PROCESSORS in settings.py TEMPLATE_CONTEXT_PROCESSORS += ("custom_app.context_processors.categories_processor", ) 5)And now you can use {{categories}} in all the templates
关闭 HTML 转义
django – Rendering a template variable as HTML – Stack Overflow
// 默认 HTML 转义,我们需要关闭 HTML 转义; {{ myhtml |safe }} {% autoescape off %} {{ myhtml }} {% endautoescape %}
判断字符串是否为空
Python Django Templates and testing if a variable is null or empty string
{% if user.name %} {{user.name}} {% else %} {{user.username}} {% endif %}
修改 HTML 文件,但页面无变化
python – Django HTML Template Cache – Stack Overflow
模板引擎的缓存:默认 HTML 缓存在内存中,需要重启或开启 DEBUG=True 来关闭: