python - 如何在 Django 中的 HTML 模板上显示表单验证错误
问题描述
我应该如何在 HTML 模板上显示错误消息,例如我在 forms.py 中写了一个条件,如果数据库中已经存在用户名,它应该在 HTML 页面上显示消息,我应该怎么做?以下是我的代码:
视图.py
from django.shortcuts import render,redirect
from django.views.generic import View,TemplateView
from .forms import Registration_Form
from .models import User_Registration
from django.contrib import messages
# Create your views here.
class MainPageView(TemplateView):
template_name='main.html'
class LoginView(TemplateView):
template_name='login.html'
def RegistrationView(request):
form=Registration_Form()
if request.method=='POST':
form=Registration_Form(request.POST)
if form.is_valid():
user_name=form.cleaned_data['username']
print(User_Registration.objects.filter(username=user_name))
form.save()
return redirect('login_view')
else:
# messages.error(request,"Form is Invalid!")
return redirect('registration_view')
else:
return render(request,'registration.html',{'form':form})
# template_name='registration.html'
表格.py
from django import forms
from .models import User_Registration
class Registration_Form(forms.ModelForm):
class Meta:
model=User_Registration
fields=('company_name','username','password','email')
widgets={
'company_name':forms.TextInput(attrs={'class':'form-control input-sm'}),
'username':forms.TextInput(attrs={'class':'form-control'}),
'password':forms.PasswordInput(attrs={'class':'form-control'}),
'email':forms.EmailInput(attrs={'class':'form-control'}),
}
def clean(self):
user_name=self.cleaned_data['username']
if User_Registration.objects.filter(username=user_name).exists():
raise forms.ValidationError("Username Already Exist")
解决方案
推荐阅读
- python - sklearn管道IndexError:标量变量的索引无效
- python - 如何删除在我选择的字符之后开始的行的特定部分?
- python - Python模块安装失败
- angular - 升级 @angular/materials 和 @angular/cli 后出现 Angular 构建错误
- flutter - 从可选数据表中的列表中删除对象
- bash - 从 bash 脚本中的循环调用时,CURL 返回空数据
- shopify - 我们如何阻止 Facebook 像素在添加到购物车时不跟踪产品变体
- python - 可视化多年来的公告牌前 10 名条目
- jquery - 重新计算指数
- .net - Powershell 7:如何从文件中读取并添加 dotnet 包