Reputation: 268235
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?
Upvotes: 3
Views: 1011
Reputation: 50786
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)
Upvotes: 3