我正在制作django应用程序,它可以让我学习。它有多个测试,每个测试有多个问题。每个问题都有一个正确答案。我正在试着制作一个表格,让我可以编辑答案。如果我在做题的时候把正确答案传错了。
这就是我已经做的:
models.py
class Question(models.Model):
text = models.CharField(max_length=200, null=True)
test = models.ForeignKey(Test, on_delete=models.CASCADE)
created = models.DateTimeField(auto_now_add = True)
def get_answer(self):
return self.answer_set.all()
def __str__(self):
return self.text
class Answer(models.Model):
text = models.CharField(max_length=200)
question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='parent')
def __str__(self):
return self.text
forms.py
class AnswerEditForm(ModelForm):
class Meta:
model = Answer
exclude = ('question',)
views.py
def UpdateAnswerView(request, pk):
form = AnswerEditForm()
if request.method == 'POST':
form = AnswerEditForm(request.POST)
if form.is_valid():
obj = form.save(commit=False)
obj.question = Question.objects.get(id=pk)
obj.save()
return redirect('home')
context = {'form':form}
return render(request, 'exam/update_answer.html', context)
urls.py
urlpatterns = [
~some other urls~
path('answer/edit/<int:pk>/', views.UpdateAnswerView, name='update-answer'),
]
当我试图编辑答案时,我得到了Question matching query does not exist.
错误。我哪里搞错了?
可能pk
就是None
最好检查您的pk
def UpdateAnswerView(request, pk):
form = AnswerEditForm()
if request.method == 'POST' and pk is not None:
form = AnswerEditForm(request.POST)
if form.is_valid():
obj = form.save(commit=False)
try:
obj.question = Question.objects.get(id=pk)
obj.save()
return redirect('home')
except Question.DoesNotExist:
pass
context = {'form':form}
return render(request, 'exam/update_answer.html', context)
您应该确认pk
实际上正在传递给UpdateAnswerView
。还要确认您实际传递的是Question
ID,而不是Answer
ID。