In my CreateView
class I am overriding the form_valid()
function as follows:
在我的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)
But as it turns out, the form_valid
method is never called because the user
is never printed. Interestingly, the clean
method in the forms.py is called.
但事实证明,从不调用form_valid方法,因为永远不会打印用户。有趣的是,调用forms.py中的clean方法。
No error is displayed (therefore I do not have a traceback to display). The user is just redirected to the form again. What could be the reason for this behaviour? I'm running on Django 1.5 and Python 2.7.
没有显示错误(因此我没有要显示的回溯)。用户只是重新定向到表单。这种行为可能是什么原因?我正在使用Django 1.5和Python 2.7。
2 个解决方案
#1
2
form.instance.user = self.request.user is wrong
form.instance.user = self.request.user是错误的
Please try this variant:
请尝试以下变体:
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)
P.S. You really need change get_initial? On you code i don't see that this need.
附:你真的需要改变get_initial吗?在你的代码我不认为这需要。
#2
1
It is likely that the form is not valid. You could override form_invalid() and see if that is called, or override post() and see what data is being POSTed.
表格可能无效。您可以覆盖form_invalid()并查看是否已调用,或覆盖post()并查看正在发布的数据。
#1
2
form.instance.user = self.request.user is wrong
form.instance.user = self.request.user是错误的
Please try this variant:
请尝试以下变体:
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)
P.S. You really need change get_initial? On you code i don't see that this need.
附:你真的需要改变get_initial吗?在你的代码我不认为这需要。
#2
1
It is likely that the form is not valid. You could override form_invalid() and see if that is called, or override post() and see what data is being POSTed.
表格可能无效。您可以覆盖form_invalid()并查看是否已调用,或覆盖post()并查看正在发布的数据。