Django: CBV method form_valid () not called

In my CreateView class CreateView I override the form_valid() function as follows:

 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 turned out, the form_valid method form_valid never called because user never printed. Interestingly, the clean method in form.py is called.

No error is displayed (therefore, I do not have backtracking). The user is redirected to the form again. What could be causing this behavior? I am running Django 1.5 and Python 2.7.

+7
source share
2 answers

form.instance.user = self.request.user is invalid

Try this option:

 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) 

PS Do you really need to change get_initial? On your code, I do not see what this need is.

+2
source

The form is probably invalid. You can override form_invalid () and see if this is called, or override post () and see what data is POSTED.

+1
source

All Articles