如何在UI中显示Django ValidationError

时间:2015-11-22 13:32:13

标签: python django validationerror

我很困惑如何在密码和密码确认不一样的情况下在我的注册页面中显示ValidationError,而不是将我发送到一个显示ValueError和stuffs的页面。但是,当我到达管理员时,它肯定会显示ValidationError。有帮助吗?这是我的代码

forms.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

views.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})

signup.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 content%}

1 个答案:

答案 0 :(得分:1)

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