如何在Django表单中引发错误?

时间:2016-11-03 05:08:49

标签: php json django forms

我在服务器中有一个返回{"available":true}{"available":false}的PHP脚本,具体取决于电子邮件地址是否可用。这是代码:

<?php

$servername = "localhost";
$username = "root";
$password = "mysqlpass";
$dbname = "testdb";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT username FROM testtable";
$result = $conn->query($sql);

$query = $_GET['query'].'@groupdesignace.com';
$arr = array();

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
    $arr[] = $row['username'];
    }

    if (in_array($query, $arr)) {
    $output = array('available' => false);
    echo json_encode($output);
    } else {
    $output = array('available' => true);
    echo json_encode($output);
    }
} else {
    echo "0 results";
}
$conn->close();

?>

在用户通过表单请求其电子邮件地址的其他服务器上,我正在使用Django。我编写了以下代码来检查电子邮件是否可用,如果没有,则应该引发错误。这是代码:

class RequestEmailAddressForm(forms.Form):
    email = forms.CharField(label='Email', max_length=100)
    password = forms.CharField(widget=forms.PasswordInput)

    def clean_email(self):
        email = self.cleaned_data.get('email')

        if email:
            import requests

            payload = {'query': email}
            r = requests.get('http://172.16.16.172/check_email.php', params=payload)
            result = r.json()
            print r.url

            status = result['available']
            if status == False:
                raise forms.ValidationError('This login name is unavailable!')
        return email

以下是我处理表单的观点:

def request_email_address(request):
    if request.method == "POST":
        form = RequestEmailAddressForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            # do something here
        else:
            pass
        return HttpResponseRedirect('/core/home/')
    else:
        form = RequestEmailAddressForm()
    return render(request, "core/request_email_address.html", { "form": form })

但是,表单将转到提交的页面,但不会引发验证错误。我做错了什么?

1 个答案:

答案 0 :(得分:1)

如果表单无效,您什么都不做。当引发ValidationError时,django会设置form.errors dict,其中包含有关验证过程中出错的数据。阅读更多https://docs.djangoproject.com/en/1.10/ref/forms/validation/

def request_email_address(request):
    if request.method == "POST":
        form = RequestEmailAddressForm(request.POST)
        if form.is_valid():  # <- form validation is called on this line
            data = form.cleaned_data
            # do something here
            # do redirect here
            return HttpResponseRedirect('/core/home/')
        else:
            pass   
    else:
        form = RequestEmailAddressForm()
    return render(request, "core/request_email_address.html", { "form": form })