我有一个模型
class someModel(models.Model):
.....
.....
user = models.OneToOneField(User, on_delete=models.CASCADE)
#User is the field that I need from the form
.....
.....
在这里,我有一些必须填写的字段以及连接到用户表的用户字段
在我的表单中
class someForm(forms.ModelForm):
class Meta:
model = someModel
fields = [....., 'user']
widgets = { .... }
我想从用户的角度传递用户,但我不知道该怎么做,因此无法在线找到它。表单失败,因为未通过用户。
@login_required
def someView(request):
organisator= request.user
if request.method == "POST":
cl_form = SomeModel(data=request.POST, initial={'user': organisator})
if cl_form.is_valid():
cl_form.save(commit=True)
else:
print(cl_form.errors)
return HttpResponseRedirect(reverse('someviewfromurls'))
else:
cl_form = someForm(initial={'user':organisator})
return render(request, 'somefile.html', context=
{"cl_form": cl_form})
答案 0 :(得分:0)
您可以尝试这样:
if cl_form.is_valid():
instance = cl_form.save(commit=False)
instance.user = request.user
instance.save()