Nima Hakimi
Nima Hakimi

Reputation: 1392

add foreign key fields to form

I'm trying to create a form from this model:

class A(models.Model):
    u = models.OneToOneField(User)

and then create this form:

class AForm(ModelForm):
    class Meta:
        model = A
        fields = ['u']

then i create an instance of that form in my view and send it to my template as a context I'll get a drop down list to choose from existing users but what i want to do is to have a text field to change my current user's first name or last name. I'll be grateful if you could help me to change my form class to get the right result. Thank you

Upvotes: 0

Views: 112

Answers (2)

OrenD
OrenD

Reputation: 1741

You can add the first and last name fields to the AForm ModelForm in the following way:

class AForm(ModelForm):
  first_name = forms.CharField(max_length=30, blank=True)
  last_name = forms.CharField(max_length=30, blank=True)

  class Meta:
    Model = A

  def __init__(self, *args, **kwargs):
    super(AForm, self).__init__(*args, **kwargs)
    self.fields['first_name'].initial = self.instance.u.first_name
    self.fields['last_name'].initial = self.instance.u.last_name

  def save(self, commit=True):
    self.instance.u.first_name = self.cleaned_data['first_name']
    self.instance.u.last_name = self.cleaned_data['last_name']
    self.instance.u.save()
    return super(AForm, self).save(commit=commit)

Upvotes: 2

Wtower
Wtower

Reputation: 19902

In this case you do not need a modelform of A but a modelform of User. You would need to set the form's instance appropriately in the view. For example,

a_record = A.objects.get_object_or_404(A, id=1)
form = self.UserForm(instance=a.u)  # UserForm is a modelform of User

Upvotes: 0

Related Questions