1

I am looking to apply this behavior (extracted from a template):

object.my_date|date:"F Y"

but in a model. Is it possible to use a predefined templatetags directly in a model ? Or should I rely on python functions ?

Thanks.

2 Answers 2

1

I would expose a property on the model that does what you require. Template tags are not really designed to be used outside of templates (though of course they can as they are just functions after all), and furthermore using them means your model code depends on view specific code, which is not ideal (typically view code will depend on model code, not the other way round).

@property
def my_date_formatted(self):
    return self.my_date.strftime('%B %Y')

Note that when using strftime instead of the template tag, the syntax for specifying the date format is different, there is a good reference at http://strftime.org/.

Sign up to request clarification or add additional context in comments.

Comments

1

You can call this filter right in your python code:

from django.template.defaultfilters import date as date_filter

date = date_filter(object.my_date, "F Y")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.