Jeremy Collier
Jeremy Collier

Reputation: 23

Manipulating data passing from database to template (Django)

I'm still pretty new to Django, so I really hope I can explain what I need to do.

I have a form where users input information about a character and then it's stored in the database and displayed for them on a page.

I know it's easy to recall and display this data with template variable call (i.e. {{character.gender}}), however, I am trying to use the inputted data to create other variables based on the data BEFORE it goes into the template.

I've done this in visual basic before and essentially used an if statement to create a new variable to store the information before passing it back out, but I can't figure out how to do this with django/python.

For example, if the user provided the following information:

Name = "Jill"
Age = 23
Gender = "Female"

I'd want to be able to do something like:

if gender = "female":
    gender_identifier = 'she'

if age < 30:
    youth = "is still very young"

and then be able to do something like this in a template:

{{character.name}} is {{character.age}} years old and {{gender_identifier}} {{youth}}!

to output "Jill is 23 years old and she is still very young!"

What I"m struggling with is where those if statements need to go and how to recall them in the template.

I've tried adding them to the character model, creating it's own model, putting it in the models.py, and creating a different .py and just can't get it to work.

Also, I know it's possible to do through if/then template tags, but I really want to avoid that if at all possible. However, if that is the solution, I can live with it.

Thank you for any and all help and putting up with reading through the whole question while I fumble through and try to explain!

Upvotes: 0

Views: 1140

Answers (1)

xssChauhan
xssChauhan

Reputation: 2838

This can be achieved using Python's property decorator.

class Character(models.Model):
   #All the fields declarations 
   .
   .
   .
   @property
   def gender_identifier(self):
       if self.gender == "Female":
           return "she"
   @property
   def youth(self):
       if age < 30:
           return "is still very young"

What property does is that it will allow you to call a function as an object attribute. So, whenever you access Character.gender_identifier the method gender_identifier will be called and the value returned.

Now in your template you can simply do {{Character.gender_identifier}}

Upvotes: 2

Related Questions