使用django crispy形式自定义非表单错误

时间:2016-11-05 21:29:26

标签: django django-forms django-templates django-crispy-forms

我想自定义django crispy显示非格式错误的方式。我知道如何更改文本,但我不知道在哪里更改CSS。

这是图片: My login area

forms.py

class LoginForm(forms.Form):
    alphanumeric = RegexValidator(r'^[0-9a-zA-Z]*$', 'Only alphanumeric characters are allowed.')
    username = forms.CharField(label='', required=True, widget=forms.TextInput(attrs={'placeholder': 'Username'}))
    password = forms.CharField(label='', required=True, widget=forms.PasswordInput(attrs={'placeholder': 'Password'}))
    name = forms.CharField(label='', 
                        required=True ,  
                        validators=[alphanumeric], 
                        widget=forms.TextInput(attrs={'placeholder': 'Name'}))


    def clean(self):
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')
        user = authenticate(username=username, password=password)
        if not user or not user.is_active:
            raise forms.ValidationError('Invalid Login : I want to change this CSS')
        return self.cleaned_data

    def login(self, request):
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')
        user = authenticate(username=username, password=password)
        return user

模板 - html

<form method="POST" action="">{% csrf_token %}
    <!--{% if  form.non_field_errors %}
        testing
    {% endif %}-->
    {{form|crispy}}
    <div class="form-info">
        <label class="hvr-sweep-to-right">
            <input class="create btn"  type="submit" value="Submit">
        </label>
    </div>
</form>

1 个答案:

答案 0 :(得分:0)

我假设您使用带有引导程序的酥脆形式(取决于图像中的样式)。

所以你可以覆盖原始的bootstrap类

.alert {
  padding: 0.75rem 1.25rem;
  margin-bottom: 1rem;
  border: 1px solid transparent;
  border-radius: 0.25rem;
}

.alert-danger {
  background-color: #f2dede;
  border-color: #ebcccc;
  color: #a94442;
}

.alert-danger hr {
  border-top-color: #e4b9b9;
}

.alert-danger .alert-link {
  color: #843534;
}

或其他警报类,例如警报的成功。

如果您不想覆盖整个项目的这些类,只需在您的脆弱表单周围设置一个div

<div class"crispyform">
  {{form|crispy}}
</div>

并写入自定义css s.th.像

.crispyform .alert {
  # your new style
}