简体   繁体   English

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

[英]Django - Determine field type of a variable passed to a template tag

I would like to write a Django template tag to which I can pass a variable. 我想编写一个Django模板标签,可以向其中传递变量。

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.) 我希望模板标记的行为有所不同,具体取决于变量从哪种类型的模型字段(CharField,BooleanField,IntegerField等)以及字段定义中使用的其他信息(max_length等)得出。

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)

You can use python's type function to determine the class type. 您可以使用python的type函数来确定类的类型。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM