我正在尝试创建一个页面,用户可以使用ModelForm选择17个足球运动员并保存到他们的个人资料中。
表格
class ProfileForm(ModelForm):
class Meta:
model = Profile
fields = ['GK1', 'GK2', 'DF1', 'DF2', 'DF3', 'DF4', 'DF5', 'MF1', 'MF2', 'MF3', 'MF4', 'MF5', 'FW1', 'FW2', 'FW3']
视图
def selectteam(request):
print('request.post=', request.POST)
print(request.user)
if request.method == "POST":
form = ProfileForm(request.POST, instance=request.user)
if form.is_valid():
print("form confirmed valid") #let me know that the data is valid
form.user = request.user #set the user's data we are changing
form.save() #save the form to db
for x in form.cleaned_data: #check what the data is???
print(x)
return redirect('/accounts/profile/selectteam')
else:
print(form.errors)
form = ProfileForm()
else:
selectedplayers = Player.objects.all()
# if not, you need an empty form for GET request
form = ProfileForm()
context = {'selectedplayers': selectedplayers, 'form': form}
return render(request, 'selectteam.html', context)
对于我的生活,我无法获得实际提交的数据。这是控制台输出:
[28/Apr/2018 10:27:33] "GET /static/images/pitch.png HTTP/1.1" 200 40216
request.post= <QueryDict: {'MF1': ['301'], 'MF2': ['301'], 'GK1': ['301'], 'DF5': ['301'], 'FW1': ['301'], 'DF1': ['301'], 'MF3': ['301'], 'FW2': ['301'], 'GK2': ['301'], 'MF5': ['301'], 'csrfmiddlewaretoken': ['RtvpMLuPVXaupYNzJdt1yvuJsOhfouH51FUQw73IRzUnKqZRLkzcNHWvoMFyVX4N'], 'DF4': ['301'], 'DF3': ['301'], 'DF2': ['301'], 'FW3': ['301'], 'MF4': ['301']}>
request.method= POST
Johnny
form confirmed valid
GK1
GK2
DF1
DF2
DF3
DF4
DF5
MF1
MF2
MF3
MF4
MF5
FW1
FW2
FW3
所以我可以看到form.is_valid()返回TRUE。我可以看到哪些数据正在尝试保存。我还可以看到据说已被更改的字段。
然而,当我进入管理控制台并检查用户“Johnny”时 - 字段仍然是空白/默认!我真的很困惑,因为我所有的检查和验证似乎都很好。
我唯一的猜测是,表单实际发送的数据并不“适合”可用的选择。例如,它可能试图在我的选项列表中选择值['301'],实际值为301.也许我应该做某种形式的data_cleaning?我只是不知道! modelform生成的字段例如是:
GK1 = models.ForeignKey('players.PlayerID', on_delete=models.CASCADE, null=True, related_name='+')
如果我做错了什么,有人能发现吗?感谢
答案 0 :(得分:2)
form.user
对创建的对象没有任何影响。要将当前用户添加到创建的对象,您可以执行以下操作:
if form.is_valid():
obj = form.save(commit=False)
print("form confirmed valid") #let me know that the data is valid
obj.user = request.user #set the user's data we are changing
obj.save()
return redirect('/accounts/profile/selectteam')
您可以找到有关commit
参数和示例here的详细信息。
<强> UPD 强>
同样request.user
是User
模型的实例,但您需要提供给ProfileForm
个人资料实例。因此,如果您未设置AUTH_USER_MODEL=Profile
,则应在视图中执行以下操作:
form = ProfileForm(request.POST, instance=request.user.profile)