ali ali - 4 months ago 10
Python Question

django custom validation not showing up on button click

I wrote a custom validation for my form in forms.py but it's not working. It doesn't show anything ("email not exist"), when I press the submit button it looks like refreshing the page.
I would appreciate any help.

here is my view.py:

def delete(request):
if request.method == 'POST' and "DeleteButton" in request.POST:
form = LoginPageDelete(request.POST)
if form.is_valid():
DeleteData = form.cleaned_data
q = DeleteData["emailD"]
query = Users.objects.get(email = q )
query.delete()
fetch = Users.objects.all()
return render(request,'Result.html',{'QueryDelete':fetch.values(),})

FormDelete = LoginPageDelete()
return render(request,'delete.html',{"FormDelete":FormDelete,})


here is template:

<html>
<head>
<title>Delete</title>
</head>
<body>
{% if FormDelete.errors %}
<p style="color:red">Please correct the problems</p>
123
{%endif%}

<form action="" method="POST">
<table>
{{FormDelete.as_table}}
</table>
{%csrf_token%}
<input type="submit" value="Delete" name="DeleteButton">
</form>
</body>




here is forms.py:

from django import forms
from login.models import Users

class LoginPageDelete(forms.Form):
emailD = forms.EmailField(required=True)

def clean_emailD(self):
email = self.cleaned_data['emailD']
if not Users.objects.filter(email = email).exists():
raise forms.ValidationError("email not exist")
return email

Answer

You are simply not returning the validated form to the template. Everytime in your view, you return a new instance of LoginPageDelete() instead and discard the one with validation information.

def delete(request):
    if request.method == 'POST' and "DeleteButton" in request.POST:
        form = LoginPageDelete(request.POST)
        if form.is_valid():
            DeleteData = form.cleaned_data
            q = DeleteData["emailD"]
            query = Users.objects.get(email = q )
            query.delete()
            fetch = Users.objects.all()
            return render(request,'Result.html',{'QueryDelete':fetch.values(),})
    else:# here request.method is get
        form = LoginPageDelete()

    return render(request,'delete.html',{"FormDelete":form})
Comments