我想在我的 Django 模型中验证问题字段不接受我尝试的整数,但它不起作用..我该怎么做?
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?
这是我的代码
#models.py
来自 django.db 导入模型
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
从 django.shortcuts 导入渲染,重定向
从 .models 导入 *
从 .forms 导入 QuestionForm
来自 django.views 导入视图
从 django.urls 导入反向
class 添加问题(查看):
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)
只需检查 request.POST.get('question') 是否为带有 .isdigit()
的数字
这是我的代码
#models.py
来自 django.db 导入模型
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 从 django.shortcuts 导入渲染,重定向 从 .models 导入 * 从 .forms 导入 QuestionForm 来自 django.views 导入视图 从 django.urls 导入反向
class 添加问题(查看):
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)
只需检查 request.POST.get('question') 是否为带有 .isdigit()
的数字