これはこれにかなり関連しています: form.is_valid() が false の場合にデータにアクセスする方法
私の場合、フォームの検証が失敗した場合、ユーザーに同じページをエラーメッセージとともに表示させ、新しいおよび変更されたcleaned_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