How to show validation error messages while using TemplateView and crispy forms

2.2k views Asked by At

How to return the form with error messages using Crispy Forms. I can't use FormView because I am trying to add multiple model forms to the same tag.

class Test(TemplateView):
    template_name = 'login.html'

    def get(self, request, *args, **kwargs):
        form = RegistrationForm()
        return render(request, self.template_name, {'form': form})

    def post(self, request, *args, **kwargs):
        form = RegistrationForm(request.POST)

        if form.is_valid():
            print 'valid'
        else:
            form = RegistrationForm()
            print self.get_context_data()

            for x in self.get_context_data():
                print type(x)
            print form.errors

            return render(request, self.template_name,{'form': form})
1

There are 1 answers

0
Alasdair On BEST ANSWER

Don't create a new form when the form is invalid. It overwrites the bound form which contains the errors.

If you remove that line, then the form will be rendered with its errors, whether you use {{ form }} or crispy forms in your template.

def post(self, request, *args, **kwargs):
    form = RegistrationForm(request.POST)
    if form.is_valid():
        # do something with form, then redirect
    else:
        form = RegistrationForm() # remove this line
        return render(request, self.template_name, {'form':form})