2011-09-18 1 views
2

ModelFormage 필드를 갖고 싶습니다. 모델에 birth_year을 채우기 위해 사용합니다.
이렇게하는 관용적 인 방법은 무엇입니까? 내 양식이나 모델 또는 메타 클래스에서 제공해야하는 메소드는 무엇입니까? 당신이 모델의 인스턴스를 갱신/저장할 때`birth_year` 필드를 채우려는, 또는 당신이 동적 솔루션하고자하는 경우에 따라몇 가지 계산을 사용하여 다른 ModelForm 필드의 모델 필드 값을 채우는 방법은 무엇입니까?

+0

, 즉'birth_year를 업데이트 절약 필요하지 않습니다 ''나이 '에 따라? – WTK

답변

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) 
관련 문제