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。
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()