如何将错误值设置到文本字段中,现在它只显示字段上方的错误,我想在我的文本字段中显示
实际显示:
我的目标:
forms.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')
register.html
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h1>Register</h1>
<form action="/register/" method="post">
{% csrf_token %}
<div>{{form.as_p}}</div>
<input type="submit" value="Register" />
</form>
</body>
我真的不知道如何开始,我一直在寻找django文档,我唯一能找到的是{{form.field.value | default_if_none:&#34;&# 34; }}
答案 0 :(得分:0)
您在寻找Flash消息系统吗?您可以使用视图中的以下内容显示Flash消息:
messages.error(request,"Changes were not saved.")
在模板中:
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }} /li>
{% endfor %}
</ul>
{% endif %}