MiniGunnR MiniGunnR - 29 days ago 11
JSON Question

How can I raise an error in my Django form?

I have a PHP script in a server that returns

{"available":true}
or
{"available":false}
, depending on whether the email address is available or not. Here is the code:

<?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();

?>


On a different server where users are requesting their email address through a form, I am using Django. I have written the following code to check whether the email is available, if not, it should raise an error. Here is the code:

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


Here is my view that is handling the form:

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 })


However, the form is going to the submitted page but it is not raising validation error. What am I doing wrong?

Answer

You are doing nothing on if form is invalid. When ValidationError is raised django sets form.errors dict with data about what went wrong during validation. Read more 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 }) 
Comments