"Best" way to conditionally display values ​​of different model fields in Django templates?

I am creating a website that will provide product information in two languages: English and Chinese.

Each product must have an English name and may also have a Chinese name.

Each time a product page is requested, the request object is checked to determine if the product name should be displayed in English or Chinese. In the latter case, the Chinese name should be displayed, if installed, otherwise the English name should be displayed.

Here's a simplified version of my Product model with remote extraneous information:

 class Product(models.Model): english_name = models.CharField(max_length=100) chinese_name = models.CharField(max_length=100, null=True, blank=True) def name(self, language): if language == 'Chinese' and self.chinese_name: return self.chinese_name else: return self.english_name 

My question is, what is the cleanest way to output the desired name from the template? It is not possible to call the name method, because the language argument must be passed to it, and Django templates only allow method calls with no arguments.

I could do everything using the logic in the template, but this is far from elegant:

 {% ifequal language 'Chinese' %} {% firstof product.chinese_name product.english_name %} {% else %} {{ product.english_name }} {% endifequal %} 

I could alternatively write a template filter to contain the above logic:

 @register.filter def name(product, language): if language == 'Chinese' and product.chinese_name: return product.chinese_name else: return product.english_name 

It would be nice to use:

 {{ product|name:language }} 

Creating a template filter will do the job, but for me, this logic really belongs to the model. Is a template filter suitable, or is there a “better” way to achieve the same result?

I understand that my question is rather vague: I have several working solutions, but I would like to know what is considered the best solution (as in "best practice") to solve this problem.

+4
source share
1 answer

How to make a small filter change?

 @register.filter def name(product, language): return product.name(language) 

Thus, your filter only completes the call; logic is still being processed inside the model. Just a thought.

+4
source

All Articles