我想在我的 ModelForm
中包含 age
字段,并用它来填充模型中的 birth_year
。
这样做的惯用方法是什么?我应该在我的表单或模型或元类中提供什么方法?
最佳答案
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)
关于django - 如何通过一些计算从不同的 ModelForm 字段中填充模型字段值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7463643/