0
我找不到這裏的錯誤。我在我的模型上有一個IntegerField(工資),其字段類型在相應的模型表單上被覆蓋。對於表單,我已將薪水設置爲RegexField並添加了自定義驗證以消除任何逗號。我也嘗試將模型表單字段設置爲CharField,但沒有成功。Django模型驗證失敗
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))
當我嘗試驗證的ModelForm,我得到一個無效IntegerField標準錯誤信息(該值必須爲整數)。這裏發生了什麼?
你是如何使用這種形式? – 2011-03-27 20:30:42
我在我的模板中顯示錶單域爲{{background_checkform.field}},然後在我的視圖中用.is_valid()處理。 – Ben 2011-03-27 21:13:30
我的意思是,請顯示視圖。它似乎並不像你使用這種形式。 – 2011-03-27 21:20:31