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

2024-09-26 18:03:33 发布

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

我有一个表单来输入用户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})

Tags: theinfrompyformidyourdata
1条回答
网友
1楼 · 发布于 2024-09-26 18:03:33

假设您尝试匹配的用户id确实存在(记录该id并手动查询数据库以确保)。您的代码应更改如下:

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

这段代码更短,效率更高(不像当前版本那样获取所有用户对象)

相关问题 更多 >

    热门问题