0

I'm following the answer from this question, but the request object isn't actually being passed into it: How do I access the request object or any other variable in a form's clean() method? I'm getting this error when I try to submit the form: 'NoneType' object has no attribute 'user'

Here is my form code:

class MyModelForm(ModelForm):
    class Meta:
        model = MyModel
        fields=['question',]

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        super(MyModelForm, self).__init__(*args, **kwargs)

    def clean(self, *args, **kwargs):
        data = self.cleaned_data['question']
        user = self.request.user
        if user.author.number_of_questions < 1:
             raise ValidationError("You don't have any questions left")
        return data

Here is my CreateView:

class MyModelCreate(generic.CreateView):
    model = MyModel
    fields=['question',]
    def form_valid(self, form):
        # Code
        return super(MyModelCreate, self).form_valid(form)

    def get_success_url(self, **kwargs):
        # obj = form.instance or self.object
        return reverse_lazy('articles:thank-you')

    def get_form_kwargs(self):
        kw = super(MyModelCreate, self).get_form_kwargs()
        kw['request'] = self.request # the trick!
        return kw

    def get_context_data(self, **kwargs):
        #Code
        return context

It's my understanding that the get_form_kwargs method in the CreateView is passing in self.request into the request kwarg of the form, which is then being accessed in the clean method of MyModelForm, but when I run this code, I get the error: 'NoneType' object has no attribute 'user'

I have no idea why the request object isn't getting passed to the form.

1 Answers1

0

Just guessing but dont you need to call form.is_valid() in order to work : return super(MyModelCreate, self).form_valid(form), just guessing...