【问题标题】:Django modelform validation is failingDjango 模型验证失败
【发布时间】:2011-03-27 20:15:02
【问题描述】:

我无法找出这里的错误。我的模型上有一个 IntegerField(工资),其字段类型在相应的模型表单上被覆盖。对于表单,我将薪水设为 RegexField 并添加了自定义验证以消除任何逗号。我还尝试将模型表单字段设置为 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 的标准错误消息(此值必须是整数)。这里发生了什么?

【问题讨论】:

  • 我在模板中将表单字段显示为 {{background_checkform.field}},然后在我的视图中使用 .is_valid() 对其进行处理
  • 我的意思是,请显示视图。您似乎根本没有使用此表单。

标签: django django-forms


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-08
    • 2015-06-02
    • 1970-01-01
    • 1970-01-01
    • 2015-01-13
    相关资源
    最近更新 更多