1

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

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Doh. Thanks for this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.