Django在表单的texfield中显示错误(ValidationError)

2024-06-28 16:08:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我如何在textfield中设置错误值,现在它只显示字段上方的错误,我想在我的textfield中显示它

实际显示:

What it show now

我的目标:

What I want

表单.py

from django import forms            
from django.contrib.auth.models import User   
#from models import StudentRegistration
from django.forms import ModelForm
from promSpace.models import Space
from StudentUsers.models import StudentRegistration
from django.contrib.auth.forms import UserCreationForm  



class MyRegistrationForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput)
    password2 = forms.CharField(widget=forms.PasswordInput)
    prom_code = forms.CharField(max_length = 8)
    email = forms.EmailField(max_length=50)


    def clean_email(self):
        email = self.cleaned_data['email']
        if StudentRegistration.objects.filter(email = email).exists():
            raise forms.ValidationError("Email already exists")
        return email


    def clean_password2(self):
        password = self.cleaned_data.get('password')
        password2 = self.cleaned_data.get('password2')
        if password and password2:
            if password != password2:
                raise forms.ValidationError(("The two password fields didn't match."))
            elif password == '' or password2 == '':
                raise forms.ValidationError(("The password cannot be blank"))
        return password2


    def clean_prom_code(self):
        prom_code = self.cleaned_data['prom_code']
        prom_code_ver = Space.objects.filter(prom_code = prom_code)
        if prom_code_ver.exists():
            return prom_code
            StudentRegistration.prom_name = prom_code_ver.prom_name
        else:
            raise forms.ValidationError(("The Prom Code Does not exist"))


    class Meta:
       model = StudentRegistration
       fields = ('email', 'first_name', 'last_name','gender','prom_code','password')

注册.html

^{pr2}$

我真的不知道该怎么开始,我一直在查看django文档,唯一能找到的就是{窗体字段值|默认值为“如果没有”:“}”


Tags: djangofromimportselfdataifmodelsemail