始终将用户包含在 django 模板上下文中

编程入门 行业动态 更新时间:2024-10-27 15:22:24
本文介绍了始终将用户包含在 django 模板上下文中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在为一家小公司开发一个小型 Intranet 站点,用户应该可以在该站点上发帖.我设想了一种非常简单的身份验证机制,人们只需输入他们的电子邮件地址,然后就会收到一个唯一的登录 URL,该 URL 会设置一个 cookie,以便在以后的请求中始终识别他们.

I am working on a small intranet site for a small company, where user should be able to post. I have imagined a very simple authentication mechanism where people just enter their email address, and gets sent a unique login url, that sets a cookie that will always identify them for future requests.

在我的模板设置中,我有 base.html,其他页面对此进行了扩展.我想在 base.html 中显示登录或注册按钮,但如何确保必要的变量始终是上下文的一部分?似乎每个视图只是随心所欲地设置上下文,并没有全局上下文人口.有没有办法在每个上下文创建中不包括用户?

In my template setup, I have base.html, and the other pages extend this. I want to show logged in or register button in the base.html, but how can I ensure that the necessary variables are always a part of the context? It seems that each view just sets up the context as they like, and there is no global context population. Is there a way of doing this without including the user in each context creation?

或者我是否必须制作自己的自定义快捷方式才能正确设置上下文?

Or will I have to make my own custom shortcuts to setup the context properly?

推荐答案

从更一般的意义上说,不必在每个视图中显式设置变量,听起来您想考虑编写自己的 上下文处理器.

In a more general sense of not having to explicitly set variables in each view, it sounds like you want to look at writing your own context processor.

来自文档:

上下文处理器有一个非常简单的接口:它只是一个 Python 函数,它接受一个参数,一个 HttpRequest 对象,并返回一个添加到模板上下文的字典.每个上下文处理器必须返回一个字典.

A context processor has a very simple interface: It's just a Python function that takes one argument, an HttpRequest object, and returns a dictionary that gets added to the template context. Each context processor must return a dictionary.

更多推荐

始终将用户包含在 django 模板上下文中

本文发布于:2023-11-11 04:56:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1577434.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文中   模板   用户   django

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!