首页 > 解决方案 > 如何在 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")


标签: pythondjango

解决方案


推荐阅读