Django - 确定传递给模板标签的变量的字段类型

发布于 2024-08-20 04:10:23 字数 543 浏览 5 评论 0原文

我想编写一个可以向其传递变量的 Django 模板标签。

我希望模板标记的行为有所不同,具体取决于变量派生自的模型字段类型(CharField、BooleanField、IntegerField 等)以及字段定义中使用的其他信息(max_length 等)

我可以通过按照此文档,可以轻松地将变量添加到模板标签: 传递模板变量到标签

有没有办法确定变量的原始模型字段的类名和模型参数?

换句话说:我可以制作这样的标签:

{% template_tag model.field %}

并在标签渲染函数中访问来自模型的信息吗?

field = models.CharField(max_length=40)

I would like to write a Django template tag to which I can pass a variable.

I would like the template tag to behave differently depending on what type of model field the variable was derived from (CharField, BooleanField, IntegerField, etc.) as well as other information used in the field's definition (max_length, etc.)

I can pass the variable to the template tag easily, following this documentation:
Passing template variables to the tag

Is there a way to determine the class name and model parameters of the variable's originating model field?

In other words: can I make a tag like this:

{% template_tag model.field %}

and in the tag rendering function access information coming from the model?

field = models.CharField(max_length=40)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

君勿笑 2024-08-27 04:10:23

您可以使用Python的type函数来确定类类型。

if type(field) == models.CharField:
  #CharField specific code
elif type(field) == models.IntegerField:
  #IntegerField specific code

You can use python's type function to determine the class type.

if type(field) == models.CharField:
  #CharField specific code
elif type(field) == models.IntegerField:
  #IntegerField specific code
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文