1

当密码和密码确认不相同时,我对如何在我的注册页面中显示 ValidationError 感到困惑,而不是将我发送到显示 ValueError 和其他东西的页面。但是,当我到管理员那里时,它肯定会显示 ValidationError。有什么帮助吗?这是我的代码

表格.py

from django.core.exceptions import ValidationError
from django.core.validators import RegexValidator

` 从 django.core 导入验证器

class AccountForm(UserCreationForm):
 email = forms.EmailField(required=True)

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

    # def save(self, commit=True):
    #   user = super(AccountForm, self).save(commit=False)
    #   user.email = self.cleaned_data["email"]
    #   if commit:
    #       user.save()
    #   return user



    def clean_password2(self):
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")

        if not password2:
            raise forms.ValidationError(
            self.error_messages['Must   input Password Confirmation'],
                code='Password_Confirmation_empty')
        if password1 != password2:
            raise forms.ValidationError(
              self.error_messages['Passwords do not match.'],
                code='password_mismatch')

      password_validation.validate_password(
     self.cleaned_data.get('password2'), self.instance)
        return password2

    def save(self, commit=True):
        user = super(AccountForm,self).save(commit=False)
        user.email = self.cleaned_data["email"]
        user.set_password(self.cleaned_data["password1"])

        if commit:
            user.save()
        return user

视图.py

      from django.contrib.auth.forms import UserCreationForm
      from django.contrib.auth.models import *
      from django.contrib          import messages
      from django.core import validators

     def signup(request):

if request.method == 'POST':    
    form = AccountForm(request.POST)    
    # form = UserCreationForm(request.POST)
    if form.is_valid:
        username = request.POST.get("username")
        email = request.POST.get("email")
        password1 = request.POST.get("password1")
        password2 = request.POST.get("password2")

        # form.clean_password2()
        form.save()

    return HttpResponseRedirect('/login/')
else:
    form = AccountForm()
    # form = UserCreationForm()

return render(request, 'accounts/signup.html', {'form':form})

注册.html

        {% extends "base_accounts.html" %}
        {% load staticfiles %}

         {% block content %}
         <div class="row">
         <div class="col-md-6 col-md-offset-3 text-center">
             <h2>JCREL INVENTORY</h2>
                      </div>
                         </div>
                  <div class="row">
                       <div class="col-md-6 col-md-offset-3">
                   <div class="panel panel-default">
                   <div class="panel-heading">Register</div>
                      <div class="panel-body">
      <form action="/signup/" class="form" method="POST">
        {% csrf_token %}
        {% if form.errors %}
            {% for field in form %}
              {{field.ValidationError}}
            {% endfor %}
          {% endif %}

          <!-- {{ form.as_p }} -->

        <div class="form-group">
          <label>Username</label>
          <input name="username" type="text" 
               class="form-control" required autofocus>
        </div>
        <div class="form-group">
          <label>Email</label>
          <input name="email" type="text" 
            class="form-control" required autofocus>
        </div>
        <div class="form-group">
          <label>Password</label>
        <!-- {{ form.ValidationError }} -->
          <input name="password1" 
             type="password" id="inputPassword" 
               class="form-control" required>
        </div>
        <div class="form-group">
          <label>Confirm Password</label>
        <!-- {{ form.ValidationError }} -->
          <input name="password2" type="password" 
           id="inputPassword" class="form-control" required>
        </div>
        <!-- {{form}} -->
        <div class="form-group">
          <input type="submit" 
        class="form-control btn btn-primary btn-block" 
             value="Sign Up" />
          <input type="hidden" name="next" value="{{ next }}" />
        </div>
        <div class="form-group">
          <hr>
          <p>Already have an account?</p>
          <a href="/login" class="btn btn-default btn-block">Login</a>
        </div>
      </form>
                </div>
                  </div>

             </div>
         </div>

{% endblock 内容 %}

4

1 回答 1

1

每当表单中有错误时,您都可以通过name_of_the_form.errors(在您的情况下它将是)访问它们的列表(在视图中form.errors)。然后,您可以遍历此列表并打印出message属性(例如error.message

于 2015-11-22T13:38:08.530 回答