我尝试将验证放在我的表单中,但在我按照官方文档和教程后,我无法获得解决方案。 这是我的代码: (类的变量是缩进的)
class QuestionForm(forms.Form):
subject = forms.CharField(widget=forms.Select(attrs={'class': 'select'},
choices=SUBJECTS_SELE),
label='Materia')
question = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control', 'rows': 1}),
label='Pregunta',
max_length=5000)
answer = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control', 'rows': 1}),
label='Respuesta correcta',
max_length=1000)
answerOne = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'rows': 1}),
label='Respuesta incorrecta',
max_length=1000,
required=True)
def clean_question(self):
question = self.cleaned_data.get('question')
a = "0"
if not a in question:
raise forms.ValidationError("Es obligatorio llenar este campo")
return question
def clean_answer(self):
answer = self.cleaned_data.get('answer')
a = "0"
if not a in answer:
raise forms.ValidationError("Es obligatorio llenar este campo")
return answer
我也尝试过这种方式:
def clean(self, *args, **kwargs):
question = self.cleaned_data.get('question')
answer = self.cleaned_data.get('answer')
if question != "0":
raise forms.ValidationError("Es obligatorio llenar este campo")
if answer != "0":
raise forms.ValidationError("Es obligatorio llenar este campo")
return super(QuestionForm, self).clean(*args, **kwargs)
在这种情况下,与此表单对应的视图如下:
def ayudanos(request):
form = QuestionForm(request.POST or None)
if form.is_valid():
form_data = form.cleaned_data
subject = form_data.get("subject")
question = form_data.get("question")
answer = form_data.get("answer")
answerOne = form_data.get("answerOne")
answerTwo = form_data.get("answerTwo")
name = form_data.get("name")
obj = QuestionSele.objects.create(subject=subject, question=question, answer=answer, answerOne=answerOne,
answerTwo=answerTwo, name=name)
context = {
"form": form
}
return render(request, "ayudanos.html", context)
传递给对象的变量用于保存在BBDD中。
现实化--------------------
在尝试了人们推荐我的选项之后,我没有看到验证消息,并且在我执行formI后我删除了重载页面的代码部分,我可以看到验证消息。
我的HTML和javascript:
<div class="col-md-6">
{% if form %}
<form action="" method="POST" id="askFortm"> {% csrf_token %}
{{ form.as_p }}
<button class="btn btn-lg btn-primary enviar" id="enviar" type="submit" value="Enviar">Introducir otra
pregunta</button>
</form>
{% endif %}
</div>
<script>
$(function() {
var counter = 94;
$( "#enviar" ).click(function() {
counter = counter + 1;
//alert(counter);
localStorage.setItem("counter",counter);
alert('Su pregunta ha sido enviada correctamente. ' +
'Envía otra y tendras más posibilidades de ganar los Airpods.');
});
$('#askFortm').on('submit', function(e) {
e.preventDefault();
setTimeout(function() {
window.location.reload();
},0);
this.submit();
});
});
</script>
我认为问题可能与重新加载页面有关,有可能我要比较csrf_token或者像这样的想法吗? 你能帮助我吗,谢谢。
答案 0 :(得分:0)
class QuestionForm(forms.Form):
subject = forms.CharField(widget=forms.Select(attrs={'class': 'select'},
choices=SUBJECTS_SELE),
label='Materia')
question = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control', 'rows': 1}),
label='Pregunta',
max_length=5000)
answer = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control', 'rows': 1}),
label='Respuesta correcta',
max_length=1000)
answerOne = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'rows': 1}),
label='Respuesta incorrecta',
max_length=1000,
required=True)
def clean_question(self):
question = self.cleaned_data.get('question')
a = "0"
if a not in question:
raise forms.ValidationError("Es obligatorio llenar este campo")
return question
def clean_answer(self):
answer = self.cleaned_data.get('answer')
a = "0"
if a not in answer:
raise forms.ValidationError("Es obligatorio llenar este campo")
return answer
答案 1 :(得分:0)
我相信当用户没有在必填字段中给出问题或答案时,它会为空,所以下面的代码应该可以工作。
class QuestionForm(forms.Form):
subject = forms.CharField(widget=forms.Select(attrs={'class': 'select'},
choices=SUBJECTS_SELE),
label='Materia')
question = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control', 'rows': 1}),
label='Pregunta',
max_length=5000)
answer = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control', 'rows': 1}),
label='Respuesta correcta',
max_length=1000)
answerOne = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'rows': 1}),
label='Respuesta incorrecta',
max_length=1000,
required=True)
def clean_question(self):
question = self.cleaned_data.get('question')
if not question:
raise forms.ValidationError("Es obligatorio llenar este campo")
return question
def clean_answer(self):
answer = self.cleaned_data.get('answer')
if not answer:
raise forms.ValidationError("Es obligatorio llenar este campo")
return answer
答案 2 :(得分:0)
最后我解决了这个问题,在我的观点中加入了一个HttpResponseRedirect:
def ayudanos(request):
form = QuestionForm(request.POST or None)
if form.is_valid():
form_data = form.cleaned_data
subject = form_data.get("subject")
question = form_data.get("question")
answer = form_data.get("answer")
answerOne = form_data.get("answerOne")
answerTwo = form_data.get("answerTwo")
name = form_data.get("name")
email = form_data.get("email")
obj = QuestionSele.objects.create(subject=subject, question=question, answer=answer, answerOne=answerOne,
answerTwo=answerTwo, name=name, email=email)
return HttpResponseRedirect(reverse('ayudanos'))
context = {
"form": form
}
return render(request, "ayudanos.html", context)