djangodjango-modelsdjango-viewsdjango-validationmodel-validation

i want a validation in my Django model that question field would not accept an integer i try but it's not working..How can i do that?


Here this is my Code
#models.py from django.db import models

class Question(models.Model):
    question = models.CharField(max_length=200, null= True)
    option1 = models.CharField(max_length= 200, null= True)
    option2 = models.CharField(max_length= 200, null= True)
    option3 = models.CharField(max_length= 200, null= True)
    option4 = models.CharField(max_length= 200, null= True)
    answer = models.CharField(max_length=200, null=True)
    
    def __str__(self):
        return self.question

#views.py from django.shortcuts import render,redirect from .models import * from .forms import QuestionForm from django.views import View from django.urls import reverse

class AddQuestion(View):

def post(self, request):
    forms = QuestionForm(request.POST)
    if forms.is_valid():
        forms.save()
        print("i was in If ")
        return redirect(reverse('home'))
    else:
        print("i was in else ")
        context = {'forms': forms}
        return render(request, 'file/addQuestion.html', context)
    
def get(self, request):
    forms = QuestionForm()
    context = {'forms': forms}
    return render(request,'file/addQuestion.html',context)
   

Solution

  • Just check if request.POST.get('question') is a number with .isdigit()