-1

我有这个错误:

appname_mymodel.user_id 不能为 NULL

def form_view(request):
    user = request.user
    f_form = FForm(request.POST or None, request.FILES or None)
    if request.method == "POST":
        if f_form.is_valid():
            f_form.user = user
            f_form.save()
            return HttpResponseRedirect('/thanks/')

    return render_to_response('upload.html', {'f_form': f_form}, context_instance=RequestContext(request))

表格.py:

class FForm(ModelForm):
    class Meta:
        model = MyModel
        exclude =['user']

如何保存当前登录用户?

4

2 回答 2

1

表单没有user属性,因此分配给它是没有用的。你应该做的是:

if f_form.is_valid():
    my_model = f_form.save(commit=False)
    my_model.user = user
    my_model.save()

这样,表单将构造一个MyModel实例,但不会尝试将其保存到数据库中。然后您可以填写该user字段并保存它。

于 2013-05-21T10:09:04.927 回答
0

您还可以提供必要的数据作为实例参数:

f_form = FForm(request.POST or None, request.FILES or None, \
        instance = MyModel(user=user))
if request.method == "POST":
    if f_form.is_valid():
        f_form.save()
        return HttpResponseRedirect('/thanks/')
于 2013-05-21T14:51:30.363 回答