gpt4 book ai didi

python - 如何在 Django 中比较表单输入和数据库值?

转载 作者:行者123 更新时间:2023-12-01 04:29:07 24 4
gpt4 key购买 nike

我有一个表单来输入用户 ID,我想将此 ID 与数据库值 (usrId) 进行比较。

forms.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 exit.

models.py

class UserInfo(models.Model):
name = models.CharField(max_length=200)
usrId = models.CharField(max_length=200)
age = models.CharField(max_length=200)
poste = models.CharField(max_length=200)
date1 = models.DateTimeField('date of recruitment')
def __str__(self): # __unicode__ on Python 2
return self.name

views.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 并手动查询数据库以确保)。您的代码应更改如下:

try:
p = UserInfo.objects.get(id=your_id)
except UserInfo.DoesNotExist:
raise forms.ValidationError("User not exist.")

此代码更短且更高效(您不会像当前版本那样获取所有用户对象)

关于python - 如何在 Django 中比较表单输入和数据库值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32642061/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com