#views.py class AddQuestion(View):
def post(self, request):
forms = QuestionForm(request.POST)
if forms.is_valid:
forms.save()
print("If statement")
return redirect(reverse('home'))
else:
print("else statement")
return render(request,'file/addQuestion.html')
def get(self, request):
forms = QuestionForm()
context = {'forms': forms}
return render(request,'file/addQuestion.html',context)
#forms.py from django.forms import ModelForm from .models import Question from django.core.exceptions import ValidationError
class QuestionForm(ModelForm):
class Meta:
model = Question
fields = "__all__"
def clean_answer(self):
answer = self.cleaned_data['answer']
option1 = self.cleaned_data['option1']
option2 = self.cleaned_data['option2']
option3 = self.cleaned_data['option3']
option4 = self.cleaned_data['option4']
if answer == option1 or answer == option2 or answer == option3 or answer == option4:
return answer
else:
raise ValidationError("Select an answer from the options.")
CodePudding user response:
use forms.is_valid():
instead of forms.is_valid:
def post(self, request):
forms = QuestionForm(request.POST)
if forms.is_valid():
forms.save()
print("If statement")
return redirect(reverse('home'))
else:
print("else statement")
return render(request,'file/addQuestion.html')