我在forms.py中为我的表单编写了一个自定义验证,但它无效。它没有显示任何内容("电子邮件不存在"),当我按下提交按钮时,它看起来像刷新页面。 我将不胜感激任何帮助。
这是我的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,})
这是模板:
<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>
这里是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
答案 0 :(得分:1)
您根本不会将经过验证的表单返回给模板。每次在视图中,您都会返回一个新的LoginPageDelete()实例,并丢弃带有验证信息的实例。
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 or in your case "DeleteButton" not in request.POST
form = LoginPageDelete()
return render(request,'delete.html',{"FormDelete":form})