Django引发表单ValidationError不起作用

时间:2019-03-09 10:59:19

标签: python django django-forms django-templates

这可能是一个重复的问题,但是我没有找到解决问题的方法。 我的UserLoginForm验证存在问题。 “提高forms.ValidationError”不起作用,也不抛出错误。其他一切都正常运行。

我的表单验证块

    def clean(self):
        cleanedData= super(UserLoginForm, self).clean()
        username= cleanedData.get('username')
        password = cleanedData.get('password')

        if User.objects.filter(username=username).exists() is False:
            print("User not available Validation should trigger")
            raise forms.ValidationError('User does not exists.')
        else:
            user = authenticate(username=username, password=password)
            if user is None:
                print("Authentication Failed Validation should trigger")
                raise forms.ValidationError('Invalid Credentials.')

Views.py

def signin(request):
    if request.method == 'POST':
        form= UserLoginForm(request.POST)
        if form.is_valid():
            username= str(form.cleaned_data['username']).lower()
            password= form.cleaned_data['password']

            user= authenticate(username= username, password= password)
            if user:
                if user.is_active:
                    login(request, user)
                    return HttpResponseRedirect(reverse_lazy('testapp:index'))
                else:
                    return HttpResponse('User Not Active')
            else:
                return HttpResponse('Login Unsuccessful.')
        else:
            return HttpResponse('Form not valid')
    elif request.method == 'GET':
        if request.user.is_authenticated:
            return HttpResponseRedirect(reverse_lazy('testapp:index'))
        else:
            form= UserLoginForm()
    return render(request, 'signin.html', {'form': form})

HTML Temlplate

{% extends "base.html" %}
{% load static %}
{% block bodyblock %}
    <div class="container">
        <img src="{% static "images/face.png" %}" alt="image no found">
        <div class="heading">
            <h1>Login</h1>
        </div>
        <form action="" method="post" id="signinForm">
            {% csrf_token %}
            <div class="form-input">
                <i class="fas fa-user"></i>
                {{ form.username }}
            </div>
            {% if form.username.errors %}
                <span>{{ form.username.errors }}</span>
            {% endif %}
            <div class="form-input">
                <i class="fas fa-lock"></i>
                {{ form.password }}
            </div>
            {% if form.password.errors %}
                <span>{{ form.password.errors }}</span>
            {% endif %}

            {{ form.non_field_errors }}
            {{ form.source.errors }}
            {{ form.source }}

            <div class="form-submit">
                <input type="submit" value="Sign In">
            </div>
        </form>
    </div>
{% endblock bodyblock %}

要捕获错误,我在HTML模板中使用了全部3个({{form.non_field_errors}},{{form.source.errors}},{{form.source}})。

我能够看到“用户不可用,应该触发验证”和“验证失败,应该触发验证”,但是引发VailidationError不起作用。

2 个答案:

答案 0 :(得分:0)

    # Validation
    def clean(self):
        cleaned_data = super(UserLoginForm, self).clean()
        username = cleaned_data.get("username")
        email = cleaned_data.get("email")
        email_exist = User.objects.filter(email=email).exists()
        username_exist = User.objects.filter(username=username).exists()

        if username_exist:
            raise forms.ValidationError('User Exists')
        else:
            raise forms.ValidationError('User does not exists')

        return super(UserProfileForm, self).clean()

你可以试试吗?

答案 1 :(得分:0)

@Daniel Roseman建议,将“ return HttpResponse('Form notvalid')”替换为“ return render(request,'signin.html',{'form':form}))”,此问题已解决。