开发者

How to fill model field value from a different ModelForm field with some calculation?

I want to have age fiel开发者_开发百科d 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?


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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜