Django:CBV 方法 form_valid() 未被调用

10

在我的CreateView类中,我按照以下方式重写了form_valid()函数:

class ActionCreateView(CreateView):
    model = Action
    form_class = ActionCreateForm
    success_url = reverse_lazy('profile')

    def get_initial(self):
        initial = super(ActionCreateView, self).get_initial()
        initial['request'] = self.request
        return initial

    def form_valid(self, form):
        form.instance.user = self.request.user
        print 'user: %s'%form.instance.user
        try:
            da = form.cleaned_data['deadline_date']
            ti = datetime.now()
            form.instance.deadline = datetime(da.year, da.month, da.day, ti.hour, ti.minute, ti.second )
        except Exception:
            raise Http404
        return super(ActionCreateView, self).form_valid(form)

但事实证明,form_valid方法从未被调用,因为user从未打印出来。有趣的是,在forms.py中的clean方法被调用了。

没有显示任何错误(因此我没有回溯可显示)。用户只会被重新定向到表单。 这种行为的原因可能是什么? 我在运行Django 1.5和Python 2.7。


3
你是否尝试在form_invalid方法内使用打印语句,并且是否在使用POST - Hedde van der Heide
1
创建 form_invalid 方法揭示了问题。感谢您的建议。如果您将评论写为答案,我将很高兴接受并点赞。谢谢。 - neurix
我遇到了类似的问题,form_invalid也帮助了我。我意识到表单渲染了一个错误,而我在模板中没有为此进行适配,因此它没有显示出来。@neurix,你遇到的是否类似? - Bryce Caine
2个回答

7

很可能表单无效。您可以重写form_invalid()并查看是否调用,或重写post()并查看POST的数据是什么。


2

form.instance.user = self.request.user 是错误的写法。

请尝试使用以下代码:

def form_valid(self, form):
    self.object = form.save(commit=False)  
    if self.request.user.is_authenticated():
        self.object.user = self.request.user
    # Another computing etc
    self.object.save()
    return super(ActionCreateView, self).form_valid(form)

你真的需要更改get_initial吗?在你的代码中我没有看到这个必要。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接