如何在Django中将表单输入与数据库值进行比较?

时间:2015-09-18 00:31:48

标签: python django

我有一个输入用户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 exist.任何值。

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})

1 个答案:

答案 0 :(得分:2)

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

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

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