Jay
Jay

Reputation: 770

Django ModelForm - Create instance with foreign key

I'm wondering what the correct way to create a model instance with a django model form is when it contains a required FK? I think it may have to do with the exclude class property, but in the view I am trying override this before save.

Model:

 class Profile(models.Model):
    client = models.OneToOneField('auth.User')
    first_name = models.TextField(blank=True,)
...

Form:

class ProfileForm(floppyforms.ModelForm):
    class Meta:
        exclude = ('client',)
        model = Profile

        widgets = {
            'first_name': floppyforms.TextInput(attrs={'placeholder': 'First Name'}),
...

View:

def post(self, request):
    form = ProfileForm(request.POST)
    if form.is_valid():
        form.save(commit=False)
        form.client = User.objects.create(username=request.POST['email'],)
        form.save()
        return redirect('/success')
    return redirect('/error')

The error:

django.db.models.fields.related.RelatedObjectDoesNotExist: Profile has no client.

Looking at the Admin, I can see that the user has been created however. enter image description here

Cheers

Upvotes: 1

Views: 1835

Answers (1)

Shang Wang
Shang Wang

Reputation: 25539

You have an error in your views.py. It should be:

def post(self, request):
    form = ProfileForm(request.POST)
    if form.is_valid():
        new_profile = form.save(commit=False)
        new_profile.client = User.objects.create(username=request.POST['email'],)
        new_profile.save()
        return redirect('/success')
    return redirect('/error')

You shouldn't assign the client to your form, but to the in-memory instance new_profile, then call new_profile.save() to save the new_profile to the database.

Upvotes: 6

Related Questions