开发者

Django modelform validation is failing

I can't figure out the bug here. I have an IntegerField (salary) on my model, whose field type is overridden on the respective modelform. For the form, I've made salary a RegexField and added custom validation to eliminate any commas. I also tried making the modelform field a CharField, without success.

 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

Here is my view:

@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)
      els开发者_如何学Pythone:
          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))   

When I try to validate the modelform, I get the standard error message for an invalid IntegerField (This value must be an integer). What's going on here?


In your post, the clean_salary() method is not correctly indented. It should be part of your Background_CheckForm class.

If your code is indented in the same way as your post, the clean_salary() method is never invoked, and then you obviously get the standard error message.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜