views:

246

answers:

1

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)
+1  A: 

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
mountainswhim
True, but generally a very bad idea. While this answer is literally correct, it's pretty-poor polymorphism, and shouldn't be used.
S.Lott