10

In my CreateView class I am overriding 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 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.

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.

neurix
  • 4,126
  • 6
  • 46
  • 71
  • 3
    Did you try a print statement within the `form_invalid` method, and are you using `POST`? – Hedde van der Heide May 17 '13 at 14:32
  • 1
    creating the `form_invalid` method revealed the problem. Thank you for the suggestion. If you write your comment as an answer, I am happy to accept and up vote it. Thank you. – neurix May 17 '13 at 16:39
  • I ran into a similar issue, and `form_invalid` helped me as well. I realized that the form was rendering an error that I was not accommodating for in the template, so it didn't display. Is that similar to what you encountered @neurix? – Bryce Caine Mar 19 '15 at 21:50

2 Answers2

7

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.

askvictor
  • 3,621
  • 4
  • 32
  • 45
2

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

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.

nnmware
  • 930
  • 5
  • 15