Determine variable type within django template

前端 未结 5 1111
执念已碎
执念已碎 2020-12-03 21:02

I have a variable that I\'m pulling into a table that sometimes is a date and sometimes is a string. If the variable is a date, I want to change the formatting:

<         


        
5条回答
  •  误落风尘
    2020-12-03 21:45

    I know I'm way behind on this (by three years) but I just got here looking to do something similar and came up with what I think is a decent solution.

    Just add a function to your models like get_model_type and have it return something you'd expect from each model like so:

    class MyModelOne(models.Model):
      date_created = models.DateTimeField(auto_now_add=True)
      first_name = models.CharField(max_length=255)
      def get_model_type(self):
        return "my_model_one"
    
    class MyModelTwo(models.Model):
      date_created = models.DateTimeField(auto_now_add=True)
      other_field = models.CharField(max_length=255)
      def get_model_type(self):
        return "my_model_two"
    

    Then in your template you can easily just call that function:

    {% if model.get_model_type == 'my_model_one' %}
      

    Model One

    {% elif model.get_model_type == 'my_model_two' %}

    Model Two

    {% endif %}

提交回复
热议问题