django form is valid() fails

前端 未结 2 431
有刺的猬
有刺的猬 2021-01-15 06:04

I am trying to create a registration form using django, when I submit my form the is valid() function fails and I am not sure why. I have my registration and login page all

相关标签:
2条回答
  • 2021-01-15 06:14

    Right now your form is always empty and therefore invalid. You forgot to add the request POST content to the form.

    def SignUp(request):
        # ...
        if request.method == 'POST':
            regForm = SignupForm(request.POST)  # form needs content
            if regForm.is_valid():
                # ...
    

    If you get stuck when calling .is_valid(), you can print(regForm.errors) to see what's up.

    0 讨论(0)
  • 2021-01-15 06:35

    You have two main problems. Firstly, you are never passing the POST data to the form, so it can never be valid.

    Secondly, for some reason you are ignoring everything that the form could tell you about why it is not valid, and always returning "usernames didn't match". What's more, you're not even doing anything to compare usernames, so that error message will never be accurate.

    You should rework your view to follow the pattern as described in the documentation:

    def SignUp(request):
        if request.method == 'POST':
            regForm = SignUpForm(request.POST)
            if regForm.is_valid():
                 ...
                 return redirect(somewhere)
        else:
            regForm = SignUpForm()
        return render(request, 'index.html', {'regForm':regForm})
    

    and in your template make sure you include {{ form.errors }} to show what the validation failures are.

    0 讨论(0)
提交回复
热议问题