I want to have age
field in my ModelForm
and use it to fill birth_year
in the model.
What is the idiomatic way to do this? What method should I provide in my form or model or meta class?
Asked
Active
Viewed 990 times
3

Dan Abramov
- 264,556
- 84
- 409
- 511
-
That depends if you want to fill the `birth_year` field when saving/updating the instance of the model, or do you want it to be a dynamic solution, that wouldn't require saving to update the `birth_year` based on `age`? – WTK Sep 19 '11 at 08:27
1 Answers
3
from datetime import datetime
import forms
from myapp.models import MyModel
class MyAgeForm(forms.ModelForm):
age = forms.IntegerField()
# define other custom fields here
class Meta:
model = MyModel
# probably define what fields from the model to include/exclude here
def save(self, *args, **kwargs):
self.instance.birth_year = datetime.now().year - self.cleaned_data['age']
return super(MyAgeForm, self).save(*args, **kwargs)

Bernhard Vallant
- 49,468
- 20
- 120
- 148