[Fixed]-Saving django OneToOneField current user with modelform

1๐Ÿ‘

โœ…

i found the answer.

i changed my model.py to

class HostRegistration(models.Model):
    # user is the changed variable
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)  
    address = models.CharField(max_length=200)
    city = models.CharField(max_length=100)
    state = models.CharField(max_length=30)
    zipcode = models.CharField(max_length=15)
    country = models.CharField(max_length=30)
    # Override the __unicode__() method to return out something meaningful!
    def __unicode__(self):
        return self.user

and i updated my views.py to:

def host_register(request):
    user = request.user
    if user.is_authenticated:
        if request.method == 'POST':
            host_form = HostForm(data=request.POST)
            if host_form.is_valid():
                instance = host_form.save(commit=False)  # this is the trick.
                instance.user = request.user  # and this to get the currently logged in user
                instance.save()  # to commit the new info
                return HttpResponseRedirect('/edit_userpage/')
            else:
                print host_form.errors
    else:
        return HttpResponseRedirect('/')
    guide_form = HostForm()
    context = {'guide_form': guide_form}
    return render(request, 'users/host.html', context)
๐Ÿ‘คcastaway2000

0๐Ÿ‘

Does it work if you do host_form.cleaned_data.get("user") instead of host_form.fields['user'].instance?

๐Ÿ‘คNS0

Leave a comment