我正试图为forms.py 中的输入字段引发验证错误
我的models.py
class StudBackground(models.Model):
stud_name=models.CharField(max_length=200)
class Student(models.Model):
name=models.CharField(max_length=200)
我的forms.py
class StudentForm(forms.ModelForm):
name = forms.CharField(max_length=150, label='',widget= forms.TextInput)
class Meta:
model = Student
fields = ['name',]
在那里我尝试应用干净的方法:
def clean_student(self,*args,**kwargs):
name=self.cleaned_data.get("name")
if not studBackground.stud_name in name:
raise forms.ValidationError ( "It is a not valid student")
else: return name
我试图将StudBackground
模型中的stud_name
合并到表单中,但它不起作用——当我尝试键入不在DB中的学生名称时,会引发以下错误:
Profiles matching query does not exist
然而,它应该在名称字段"It is a not valid student"
附近返回
如何使其发挥作用?代码出了什么问题?
您可以这样尝试:
def clean_student(self):
name=self.cleaned_data.get("name")
if not StudBackground.objects.filter(stud_name=name).exists():
raise forms.ValidationError("It is a not valid student")
return name
我使用queryset中的filter(...)
函数来检查StudBackground
中是否存在名称。我还运行exists()
来检查DB中是否存在条目。
更新
我认为你的压痕不适合这种观点。但是,你可以这样尝试:
def home(request):
form = StudentForm(request.POST or None)
if request.method == "POST":
if form.is_valid():
instance = form.save()
name = instance.name
class_background=StudBackground.objects.get(stud_name=name)
context={'back':class_background}
return render(request, 'class10/background.html', context)
# Now let us handle if request type is GET or the form is not validated for some reason
# Sending the form instance to template where student form is rendered. If form is not validated, then form.errors should render the errors.
# How to show form error: https://docs.djangoproject.com/en/3.0/topics/forms/#rendering-form-error-messages
return render(request, 'your_student_form_template.html', context={'form':form})