[Answered ]-Model Form wont validate with OneToOneField(User)

2👍

Your form is posting the value request.user.username, which is not an instance of a User object. To make your code work as-is, you would have to first retrieve the user by username, then assign the property as such:

def profile_creation(request):
    student_form = StudentForm(request.POST or None)
    if request.method == 'POST':
        username = request.POST.get('username')
        try:
            user = User.objects.get(username=username)
            student = StudentForm.save(commit=False)
            student.user = user
            student.save()
        except User.DoesNotExist:
            # handle the exception
        ...

You have to populate user_id, which btw I would simply name user, because “user_id” is misleading imo, with a user instance. Instead of doing that in the view, which in the above sample is getting messy, you’d be better off assigning that value in your form class to keep your view clean.

# classes ALWAYS start with a capital letter in Python
class Student(models.Model):
    user_id =  models.OneToOneField(User,unique=True)
    ...

class StudentForm(ModelForm):
    class Meta:
        model = student

    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user')
        super(StudentForm, self).__init__(*args, **kwargs)
        self.fields['user'] = user

# views.py
from django.core.urlresolvers import reverse

def profile_creation(request):
    # Assumes the user is authenticated, otherwise request.user
    # will be an AnonymousUser instance...
    student_form = StudentForm(request.POST or None, user=request.user)
    if request.method == 'POST':
        if student_form.is_valid():
            student_form.save()
            # don't hard-code urls - use reverse lookups
            return HttpResponseRedirect(reverse('about'))

    return render(request, 'profile_registration.html',
        {'student_form': student_form}) 

0👍

Yes, You need to get User object by username.

user = request.POST.get(username=username)

And then you can save user object into OneToOneField.

👤Nilesh

Leave a comment