提交后将用户附加到Django ModelForm / FormView

时间:2014-10-28 16:27:40

标签: python django django-class-based-views

我有一个工作正常的FormView CBV(显示一个ModelForm)。但是,我现在希望在将表单保存到数据库时将“created_by”属性附加到表单。此“created_by”字段应该是已填写表单的当前登录用户。

我尝试延迟form.save(),附加request.user然后保存所有内容......但页面只是重定向到自身,并且未添加模型数据。想法?

相关 models.py

class Event(models.Model):
    title = models.CharField(max_length=255)
    submitted_date = models.DateField(auto_now=True, verbose_name='Date Submitted')
    created_by = models.ForeignKey(User)
    event_date = models.DateField()

相关 views.py

class PostEventView(FormView):
    form_class = EventForm
    template_name = "event-submit.html"

    def form_valid(self, form):
        form = form.save(commit=False)
        form.created_by = self.request.user
        form.save()
        messages.success(self.request, 'Your event was submitted successfully. Thank you for taking the time to add this opportunity!')
        return HttpResponseRedirect(reverse_lazy('single_event', kwargs={'slug': form.slug}))

思想?

1 个答案:

答案 0 :(得分:0)

感谢@Daniel Roseman指出我忘记了exclude = ['created_by'] ModelForm。添加这个字段是一个事后的想法,因此我忘记了它exclude。我的模板也缺少{{ form.non_field_errors }},这解释了为什么我没有看到任何验证错误。