Dan Abramov
Dan Abramov

Reputation: 268235

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

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

Answers (1)

Bernhard Vallant
Bernhard Vallant

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

Related Questions