python - Creating one Django Form to save two models -
i have regular django user
model , userdetails
model (onetoonefield
user
), serves extension user
model. (i tried django 1.5's feature , headache strangely horrible documentation, stuck onetoonefield
option)
so, in quest build custom registration page have registration form comprised of user
fields , userdetails
fields, wondered if there way generate form automatically (with of validations) out of these 2 related models. know works form made of 1 model:
class meta: model = mymodel
but there anyway similar functionality form comprised of 2 related models?
from django.forms.models import model_to_dict, fields_for_model class userdetailsform(modelform): def __init__(self, instance=none, *args, **kwargs): _fields = ('first_name', 'last_name', 'email',) _initial = model_to_dict(instance.user, _fields) if instance not none else {} super(userdetailsform, self).__init__(initial=_initial, instance=instance, *args, **kwargs) self.fields.update(fields_for_model(user, _fields)) class meta: model = userdetails exclude = ('user',) def save(self, *args, **kwargs): u = self.instance.user u.first_name = self.cleaned_data['first_name'] u.last_name = self.cleaned_data['last_name'] u.email = self.cleaned_data['email'] u.save() profile = super(userdetailsform, self).save(*args,**kwargs) return profile
Comments
Post a Comment