简体   繁体   中英

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. 在此处输入图片说明

Cheers

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM