错误列表此字段是必需的

时间:2018-01-03 16:23:43

标签: django django-models django-views

form = AuthorForm(self.request.POST, self.request.FILES, self.request.user)

class AuthorForm(forms.ModelForm):
    class Meta:
        model = Author
        fields = ['file','user']`


class Author(models.Model):
    user = models.ForeignKey(User)
    file = models.FileField(upload_to='authors/')

通过上述配置,我收到错误

<tr><th><label for="user">User:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><select id="user" name="user" required
<option value="" selected="selected">---------</option>
<option value="2">admin</option>
<option value="3">user2</option>

我不想在用户字段中设置blank = True。我已经将request.user传递给了ModelForm,我希望将它存储在db中,但是它没有按预期工作。

我是否知道如何将request.user传递给ModelForm。

1 个答案:

答案 0 :(得分:1)

form = AuthorForm(self.request.POST, self.request.FILES, self.request.user)

除非您覆盖了表单的self.request.user方法,否则无法将__init__传递给此类表单。

您应该从表单

中删除user字段
class AuthorForm(forms.ModelForm):
    class Meta:
        model = Author
        fields = ['file',]

然后在视图的form_valid方法中设置用户。

def form_valid(self, form):
    form.instance.user = self.request.user
    return super(MyView, self).form_valid(form)

如果您的观点未调用form_valid,请更改保存表单的代码以使用commit=False,并在此处设置用户。

author = form.save(commit=False)
author.user = self.request.user  # request.user in a function-based view
author.save()