简体   繁体   中英

Django custom registration form errors

Hope you have wonderful day.

I've build custom register form, but when form is not valid, the form returns without error on it.

Example:

Im inserting incorrect password to "confirm password" input, and after sending the form, no error could be found on the form it self.

It might because im not returning the form correctly?

This is my form.py file:


class SignUpForm(UserCreationForm):

    email = forms.EmailField(max_length=50, help_text='Required. Inform a valid email address.',
                             widget=(forms.TextInput(attrs={'class': 'form-control'})))
    password1 = forms.CharField(label=('Password'),
                                widget=(forms.PasswordInput(
                                    attrs={'class': 'form-control'})),
                                help_text=password_validation.password_validators_help_text_html())
    password2 = forms.CharField(label=('Password Confirmation'), widget=forms.PasswordInput(attrs={'class': 'form-control'}),
                                help_text=('Just Enter the same password, for confirmation'))
    username = forms.CharField(
        label=('Username'),
        max_length=150,
        help_text=(
            'Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.'),

        error_messages={'unique': (
            "A user with that username already exists.")},
        widget=forms.TextInput(attrs={'class': 'form-control'})
    )

    class Meta:
        model = User
        fields = ('username', 'email', 'password1', 'password2',)


the signup function using the Signup form:

csrf_exempt
def signup1(request):
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid() is False:
            form = SignUpForm()
            return render(request, 'accounts/register.html', {'form': form})

        if form.is_valid():
            print(str(form.cleaned_data["email"]))
            email = str(form.cleaned_data["email"])
            username = str(form.cleaned_data["username"])
            p1 = str(form.cleaned_data["password1"])
            p2 = str(form.cleaned_data["password2"])

            try:

                user1 = User.objects.get(email__exact=email)
            except:
                form = SignUpForm()
                return render(request, 'accounts/register.html', {'form': form})

            if p1 != p2:
                form = SignUpForm()
                return render(request, 'accounts/register.html', {'form': form})

            user = User.objects.create_user(
                email=email, username=username, password=p1)

            print("EMAIL? " + str(user.email))

            user.refresh_from_db()
            # load the profile instance created by the signal
            user.save()

            pro = Profile(user_id=user.id, isVerified=False)

            pro.save()

            sender = 'xilplatform@gmail.com'

            receiver = [str(user.email)]

            message = "Welcome to XIL Platform "+receiver[0] + \
                " Please Verify you account by clicking \n the link in the email  we sent you! \n" \
                "If you registerd in heroku use this link to verify - https://django.herokuapp.com//verifyAccount?email="+receiver[0] + \
                "\n If you are using localhost use this link to verify - http://localhost:8000/verifyAccount?email=" + \
                receiver[0]

        try:
            # send your message with credentials specified above
            with smtplib.SMTP(smtp_server, port) as server:
                server.starttls()
                server.login(loginAddr, password)
                server.sendmail(sender, receiver, message)

            return redirect('/')

            # tell the script to report if your message was sent or which errors need to be fixed
            print('Sent')
            return redirect('/')

        except (gaierror, ConnectionRefusedError):
            print('Failed to connect to the server. Bad connection settings?')
        except smtplib.SMTPServerDisconnected:
            print('Failed to connect to the server. Wrong user/password?')
        except smtplib.SMTPException as e:
            print('SMTP error occurred: ' + str(e))

            return redirect('/')
    else:
        return render(request, 'accounts/register.html', {'form': form})
    return render(request, 'accounts/register.html', {'form': form})

and of course the HTML file.

        <form action="/signup" method="post">
          {% csrf_token %}



          <form method="post">
            {% csrf_token %}
            {% for field in form %}
            <p>
              {{ field.label_tag }}<br>
              {{ field }}
              {% if field.help_text %}
              <small style="color: grey">{{ field.help_text | safe }}</small>
              {% endif %}
              {% for error in field.errors %}
            <p style="color: red">{{ error | safe }}</p>
            {% endfor %}
            </p>
            {% endfor %}







      </div>
      <div class="card-footer">
        <button type="submit" onclick="" class="btn btn-primary">Register</button>
        &nbsp; &nbsp;
        Have an account? <a href="{% url 'login' %}" class="text-primary">Login</a>
      </div>
      </form>

You're clearing the form when it is not valid

    form = SignUpForm(request.POST)
    if form.is_valid() is False:
        form = SignUpForm()   # <== e.g. here (remove this line)
        return render(request, 'accounts/register.html', {'form': form})

there are many other places where you do the same (the form with the request.POST data contains the errors.

Additionally the bare except: will hide errors, and I would seriously consider refactoring this view. A lot of the code should be in the form's clean/is_valid functions (for an example look at the django.contrib.auth user creation form: https://github.com/django/django/blob/main/django/contrib/auth/forms.py#L109 )

I would also urge you to to spell the is-not-valid check:

if not form.is_valid():

and instead of:

  pro = Profile(user_id=user.id, isVerified=False)
  pro.save()

do:

pro = Profile.objects.create(user=user, isVerified=False)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM