Django提升表单ValidationError不起作用

问题描述 投票:0回答:2

这可能是一个重复的问题,但我没有找到解决我的问题的方法。问题在于我的UserLoginForm验证。 “raise 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.朋友

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模板

{% 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无法正常工作。

python django django-forms django-templates
2个回答
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()

你能试试吗?


0
投票

正如@Daniel Roseman所建议的,用“return render(request,'signin.html',{'form':form})”替换“返回HttpResponse('表格无效')”,这解决了这个问题。

© www.soinside.com 2019 - 2024. All rights reserved.