Bootstrap表单以不同的样式显示错误消息

时间:2017-02-12 15:37:05

标签: python django twitter-bootstrap django-forms

我的django应用程序中有两个表单,我正在使用bootstrap3来自定义它们,但是表单中的错误消息并不相同。

一切都是葡萄牙语

enter image description here

我的模板使用相同的结构,我不知道为什么会有差异。

的login.html

    {% extends 'base.html' %}
{% load crispy_forms_tags %}
{% load bootstrap3 %}

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{% block content %}
    <div class="row">
    <div class="col-sm-4">
         <form method="POST" action="">
                {% csrf_token %}
                {% bootstrap_form form %}
                <input class='btn btn-primary' type="submit" value="Logar">
            </form></br></br>


    </div>

    </div>

{% endblock %}
</body>
</html>

signup.html

{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% load bootstrap3 %}


<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{% block content %}
    <div class="row">
    <div class="col-sm-4">
 <form method="POST" action="">
        {% csrf_token %}
        {% bootstrap_form form %}
        <input class='btn btn-primary' type="submit" value="Cadastrar">
    </form>
     </div>

    </div>
{% endblock %}

</body>
</html>

forms.py

from django.contrib.auth import get_user_model, authenticate
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.forms import AuthenticationForm
from .models import User
from django import forms


class UserCreateForm(UserCreationForm):
    class Meta:
        fields = ("username","email", "password1","password2")
        model = get_user_model()

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields["username"].label = "Usuário"
        self.fields["email"].label = "Email"
        self.fields["password2"].help_text = None
        #self.fields["email"].widget.attrs['readonly']=True

    def clean_email(self):

        email = self.cleaned_data['email'].lower()
        try:
            u = User.objects.get(email=email)
        except User.DoesNotExist:
            return email
        raise forms.ValidationError('Email já em uso')
    # return self.cleaned_data['email'].lower()


class UserLogin(AuthenticationForm):

    def clean(self):
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')

        if username and password:
            self.user_cache = authenticate(username=username, password=password)
            if self.user_cache is None:
                raise forms.ValidationError(
                    ("Email ou Senha errados"))
            elif not self.user_cache.is_active:
                raise forms.ValidationError(("This account is inactive."))
        return self.cleaned_data

base.html文件

{% load staticfiles %}

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" href="../../favicon.ico">

    <title>Static Top Navbar Example for Bootstrap</title>

    {% include 'header_css.html' %}



  </head>

  <body>
  {% include 'navbar.html' %}

    {% block jumbotron %}
    <div class="container">

        <!-- Main component for a primary marketing message or call to action -->
      <div class="jumbotron">
        {% block jumbotron_content %}
        {% endblock %}
      </div>

    {% block content %}
    {% endblock %}


    </div> <!-- /container -->
     {% endblock jumbotron %}

    <!-- Bootstrap core JavaScript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script>window.jQuery || document.write('<script src="../../assets/js/vendor/jquery.min.js"><\/script>')</script>
    <script src="{% static 'js/bootstrap.min.js' %}"></script>
    <!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
    <script src="{% static 'js/ie10-viewport-bug-workaround.js' %}"></script>
  </body>
</html>

2 个答案:

答案 0 :(得分:0)

看起来像signup.html和login.html页面使用不同的引导样式(可能一个文件仍在缓存中)。

您是否在浏览器中尝试过“硬刷新”(CTRL +点击Chrome中的刷新按钮,点击Firefox中的CTRL + F5)?

答案 1 :(得分:0)

第一个屏幕截图是将错误消息应用于整个表单(NON_FIELD_ERRORS),第二个屏幕截图看起来正在将错误应用于各个字段本身。在左侧的屏幕截图中,错误文本正在顶部打印,因为错误已应用于整个表单,而不是特定字段。

UserCreateForm中,您通过email方法验证,将错误应用于clean_email字段。在UserLogin中,它是一般clean

请参阅https://docs.djangoproject.com/en/1.10/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other

您可以使用add_error方法指定要错误的字段,复制右侧屏幕截图,或add_error(None,...复制左侧的格式(或使用{{1而不是clean)。

另请参阅:https://docs.djangoproject.com/en/1.10/ref/forms/api/#django.forms.Form.add_error