这与此非常相关: How to access data when form.is_valid() is false
就我而言,如果表单验证失败,我希望用户查看带有错误消息的同一页面,并让它显示新的和修改后的 clean_data 评论。现在,如果它未能通过表单验证,它将显示带有旧用户提交评论的页面。我之所以要显示修改后的评论,是因为我希望新数据与错误消息匹配。例如,如果用户提交
' hey bye '
为了绕过 20 个字符的最小限制,我的清理功能将去除空格并将其修剪为
'hey bye'
然后验证失败。错误消息将显示“评论长度需要至少 20 个字符”。使用旧数据,用户会感到困惑,因为他实际上输入了20多个字符,并且旧数据会显示出来。我希望他们看到被剥离的评论,这样他们就会知道我为什么失败了。
这是我的代码...
视图.py
def question(request, qid):
quest = shortcuts.get_object_or_404(askbox.models.Question, pk=qid)
log.info("Question #{0}: {1}".format(qid, quest))
user = SessionManager.getLoggedInUser(request)
answerForm = AnswerForm()
if request.method == "POST":
if user == None:
return HttpResponseRedirect(reverse('login.views.login'))
answerForm = AnswerForm(request.POST)
if answerForm.is_valid():
# user posted an answer
answerForm.question = quest
answerForm.user = user
answerForm.save()
return HttpResponseRedirect(reverse('question.views.question', args=(quest.id,)))
else:
#answerForm.text = answerForm.saved_data['text'] #doesn't work too
answerForm.text = "foo" # doesn't work...
else: # GET request
# landing page
# probably do nothing
pass
print "AnswerForm: {0}".format(answerForm)
mediaList = askbox.models.Media.objects.filter(question=qid)
return shortcuts.render_to_response('question/question.html', {
'title': 'Groupthink | {0}'.format(quest.question),
'css_list': css_list,
'js_list': js_list,
'question': quest,
'mediaList': mediaList,
'user': user,
'answerForm': answerForm,
}, context_instance=RequestContext(request))
表格.py
# fake abstract class...
class AbstractCommentForm(forms.ModelForm):
text = forms.CharField(min_length=MIN_ANSWER_LEN, max_length=MAX_ANSWER_LEN, widget=forms.Textarea) # the comment text
def clean_text(self):
# we want to avoid user cheating the system. We'll trim extra spaces between characters and then strip spaces at both ends of the string
field = 'text'
self.cleaned_data[field] = (re.sub(r' +', ' ', self.cleaned_data[field])).strip()
self.text = self.cleaned_data[field] # doesn't work
text_len = len(self.cleaned_data[field])
self.saved_data = self.cleaned_data # doesn't work
if text_len < MIN_ANSWER_LEN:
raise forms.ValidationError("The comment length needs to be at least {0} characters long".format(MIN_ANSWER_LEN))
if text_len > MAX_ANSWER_LEN:
raise forms.ValidationError("The comment length exceeds the maximum {0} characters".format(MAX_ANSWER_LEN))
return self.cleaned_data[field]
class CommentForm(AbstractCommentForm):
class Meta:
model = Comment
class AnswerForm(AbstractCommentForm):
class Meta:
model = Answer