我有一个表单来输入用户id,我想将这个id与数据库值(usrId)进行比较。在
表单.py
from django import forms
from .models import UserInfo
class NameForm(forms.Form):
your_id = forms.CharField(label='Your id', max_length=100)
def clean(self):
cleaned_data = super(NameForm, self).clean()
your_id = cleaned_data.get("your_id")
p = UserInfo.objects.all()
if your_id:
for i in p:
if i.usrId not in your_id:
raise forms.ValidationError(
"User not exist."
)
当我这样做时,什么都不会发生,我得到任何值的User not exist.
。在
模型.py
^{pr2}$视图.py
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = NameForm(request.POST)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
# ...
# redirect to a new URL:
return generate_pdf(request, Type_id)
# if a GET (or any other method) we'll create a blank form
else:
form = NameForm()
return render(request, 'rh/detail.html', {'form': form, 'type_id': Type_id})
假设您尝试匹配的用户id确实存在(记录该id并手动查询数据库以确保)。您的代码应更改如下:
这段代码更短,效率更高(不像当前版本那样获取所有用户对象)
相关问题 更多 >
编程相关推荐