如果使用form.instance设置值,Django表单验证将失败

时间:2016-02-15 14:28:01

标签: python django validation django-forms django-generic-views

我正在尝试使用通用视图将当前登录的用户作为属性分配给modelform实例的字段。我已经提到了this SO帖子并且覆盖了post方法,但它给了我一个错误,即CreatedBy字段是必需的。我也多次ccbv mro class PostCreate(LoginRequiredMixin, CreateView): model = Post form_class = PostForm success_message = "Post Updated" success_url = '/home/' def get_form(self, form_class=None): """ Returns an instance of the form to be used in this view. """ form = super(PostCreate, self).get_form(form_class) form.instance.CreatedBy=User.objects.get(id=self.request.user.id) return form def get_initial(self): """ Returns the initial data to use for forms on this view. """ self.initial = {'CreatedBy': User.objects.get(id=self.request.user.id)} return self.initial.copy() def get_form_kwargs(self): """ Returns the keyword arguments for instantiating the form. """ kwargs = { 'initial': self.get_initial(), 'prefix': self.get_prefix(), } if self.request.method in ('POST', 'PUT'): kwargs.update({ 'data': self.request.POST, 'files': self.request.FILES, }) return kwargs 。如下所示。

get_initial(self)

我覆盖所有这些方法的原因是检查每种方法中初始dict的可用性。它在每种方法中都可用,但仍然表单验证失败。但我认为最好不要在update a field of an initialized form with User object of logged in user中设置值,因为我没有使用任何已保存对象的现有数据预填充表单字段,而是希望ipdb。我已经在ipdb> form.initial={'CreatedBy':User.objects.get(id=request.user.id)} ipdb> form.fields['CreatedBy']=User.objects.get(id=request.user.id) ipdb> form.instance.CreatedBy=User.objects.get(id=request.user.id) ipdb> form.is_valid() False ipdb> form.instance.CreatedBy <User: userone> ipdb> form.fields['CreatedBy'] <User: userone> ipdb> form.initial {'CreatedBy': <User: userone>} 中完成了控制流程,但是却遇到了同样的错误。

form_valid(self)

请注意,我不是在寻找被操纵的Public Sub test() 'Imports data into M&R spreadsheet Dim wbMnR As Workbook Dim wbMatch As Workbook Set wbMnR = Workbooks("MnRs.xlsx") Set wbMatch = Workbooks("Match.xlsm") Dim myRow As Integer For i = 1 To 10 myRow = WorksheetFunction.Match(wbMatch.Worksheets(1).Range("a" & CStr(i)), wbMnR.Worksheets(1).Range("A:A"), 0) Debug.Print myRow Next i End Sub 方法。 我被困了几个小时。非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

仍然需要created_by的原因是因为您没有从表单本身中排除它;你需要在PostForm中做到这一点。

class PostForm(forms.ModelForm):
    class Meta:
        exclude = ['created_by']

对于自动分配,编辑视图上的文档有一个specific section,用于描述如何执行此操作;你重写form_valid()

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