如何通过一些计算从不同的ModelForm字段填充模型字段值?

时间:2011-09-18 18:51:49

标签: django django-models django-forms django-1.3

我想在age中添加ModelForm字段,并使用它填充模型中的birth_year
这样做的惯用方法是什么?我应该在表单,模型或元类中提供什么方法​​?

1 个答案:

答案 0 :(得分:2)

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)