[Answered ]-Django not committing form to database

1πŸ‘

βœ…

I’m surprised this doesn’t give an error.

When you instantiate the form on a GET, you correctly pass the UserProfile object as the instance parameter – this is correct because the form has that as its model. But when you instantiate on POST, you incorrectly pass the User object – request.user. You should pass the profile, as you do in the other branch.

Note, in both cases you can get the profile more simply by just doing request.user.userprofile.

1πŸ‘

Well the form being invalid situation isn’t being handled here at all. Your code should look like this

def edit_profile(request):
    if request.method == 'POST':
        form = ProfileForm(request.POST, instance=request.user)
        if form.is_valid():
            save_data = form.save(commit=False)
            save_data.user = request.user
            save_data.save()
            return redirect(reverse('core:profile'))
    else:
        udata = UserProfile.objects.get(user=request.user)
        form = ProfileForm(instance=udata)
        args = {'form': form}
    return render(request, 'core/test.html', args)

Note the change in indentation.

πŸ‘€e4c5

Leave a comment