Django ModelForm not saving data to database

倖福魔咒の 提交于 2019-12-03 16:49:29

I'm not sure exactly what the problem is here, but one issue certainly is that you are passing instance=request.user when instantiating the form. That's definitely wrong: request.user is an instance of User, whereas the form is based on UserProfile.

Instead, you want to do something like this:

f = UserDetailsForm(request.POST)
if f.is_valid():
    profile = f.save(commit=False)
    profile.user = request.user
    profile.save()

As regards ForeignKey vs OneToOne, you should absolutely be using OneToOne. The advice on using ForeignKeys was given for a while in the run-up to the release of Django 1 - almost five years ago now - because the original implementation of OneToOne was poor and it was due to be rewritten. You certainly won't find any up-to-date documentation advising the use of FK here.

Edit after comments The problem now is that you're instantiating the form with the first parameter, data, even when the request is not a POST and therefore request.POST is an empty dictionary. But the data parameter, even if it's empty, takes precedence over whatever is passed as initial data.

You should go back to the original pattern of instantiating the form within the if statement - but be sure not to pass request.POST when doing it in the else clause.

This is kind of old thread, but I hope this will help someone. I've been struggling with similar issue, I initiated object from db, updated field, called save() function and nothing happened.

user = User.objects.get(username = example_string)
user.userprofile.accepted_terms = True
user.userprofile.save()

The field accepted_terms have been added lately and that was the issue. First try python manage.py makemigrations and python manage.py migrate, if this does not help you need to flush the database.

Solution in my case was flushing the database.

UserDetailsForm(request.POST, instance = db_obj_form)

db_obj should be an object of table UserProfile that you want to save.

Sourabh Sinha

Remember to register your model form to admin.py file. This is a common mistake

Register your models here.

from . models import advancedUserForm
admin.site.register(advancedUserForm)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!