Django模型验证失败

时间:2011-03-27 20:15:02

标签: django django-forms

我无法弄清楚这里的错误。我的模型上有一个IntegerField(薪水),其字段类型在相应的模型上被覆盖。对于表单,我已将薪水作为RegexField并添加了自定义验证以消除任何逗号。我还尝试将modelform字段设为CharField,但没有成功。

 class Background_Check(models.Model):      
    user=models.ForeignKey(User, unique=True)
    salary=models.IntegerField(blank=True,max_length=10)

 class Background_CheckForm(forms.ModelForm):
    salary=forms.RegexField(label=_("Salary"), max_length=10, regex=r'^[\d\s,]+',
    #help_text = _("Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only."), 
    error_messages = {'invalid': _("Please enter a valid salary")})

    class Meta:
    model=Background_Check
    exclude=('user')



def clean_salary(self):
    salary=str(self.cleaned_data["salary"])
    re.sub(r'[,]','',salary)
    return salary

以下是我的观点:

@login_required 
def profile_settings(request):  
   page="account background"
   user=User.objects.get(pk=request.user.id)
   save_success=request.GET.get('save','')
try:
    profile=user.background_check_set.all()[0]
    profileform=Background_CheckForm(instance=profile)
  except IndexError:
    profile=''
    profileform=Background_CheckForm()
  if request.method=='POST':
    #might be able to work get_or_create_object method here
      if profile:
          profileform=Background_CheckForm(request.POST,instance=profile)
      else:
          profileform=Background_CheckForm(request.POST)
      if profileform.is_valid():
          salary=profileform.cleaned_data['salary']
          profile=profileform.save(commit=False)
          profile.user=user
          profile.save()
          return HttpResponseRedirect("/account/profile/settings/?save=1")
      else:
          return render_to_response('website/profile_settings.html', {'page':page, 'profileform':profileform}, context_instance=RequestContext(request))
  else:
      return render_to_response("website/profile_settings.html", {'page':page,'profile':profile,'profileform':profileform,'save_success':save_success}, context_instance=RequestContext(request))   

当我尝试验证模型时,我得到无效IntegerField的标准错误消息(此值必须是整数)。这里发生了什么?

1 个答案:

答案 0 :(得分:1)

在您的帖子中,clean_salary()方法未正确缩进。它应该是Background_CheckForm类的一部分。

如果您的代码以与帖子相同的方式缩进,则永远不会调用clean_salary()方法,然后您显然会收到标准错误消息。