I'm making django app which allow me to study. It has multiple tests with multiple question each. Every question has one correct answer. I'm trying to make form which allow me to edit answer If I made mistake in passing correct answer during making question.
That's what I have already made:
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'),
]
while I'm trying to edit answer i'm getting Question matching query does not exist.
error.
Where did i make mistake ?
CodePudding user response:
Probably pk
is None
.
it is better you check your 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)
CodePudding user response:
You should confirm that pk
is actually getting passed to UpdateAnswerView
. Also confirm that you're actually passing a Question
ID and not an Answer
ID.