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:
JavaScript
x
20
20
1
models.py
2
3
class Question(models.Model):
4
5
text = models.CharField(max_length=200, null=True)
6
test = models.ForeignKey(Test, on_delete=models.CASCADE)
7
created = models.DateTimeField(auto_now_add = True)
8
9
def get_answer(self):
10
return self.answer_set.all()
11
12
def __str__(self):
13
return self.text
14
15
class Answer(models.Model):
16
text = models.CharField(max_length=200)
17
question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='parent')
18
def __str__(self):
19
return self.text
20
JavaScript
1
8
1
forms.py
2
3
class AnswerEditForm(ModelForm):
4
class Meta:
5
model = Answer
6
exclude = ('question',)
7
8
JavaScript
1
17
17
1
views.py
2
3
def UpdateAnswerView(request, pk):
4
form = AnswerEditForm()
5
6
if request.method == 'POST':
7
form = AnswerEditForm(request.POST)
8
if form.is_valid():
9
obj = form.save(commit=False)
10
obj.question = Question.objects.get(id=pk)
11
12
obj.save()
13
return redirect('home')
14
15
context = {'form':form}
16
return render(request, 'exam/update_answer.html', context)
17
JavaScript
1
7
1
urls.py
2
urlpatterns = [
3
~some other urls~
4
path('answer/edit/<int:pk>/', views.UpdateAnswerView, name='update-answer'),
5
6
]
7
while I’m trying to edit answer i’m getting Question matching query does not exist.
error.
Where did i make mistake ?
Advertisement
Answer
Probably pk
is None
.
it is better you check your pk
JavaScript
1
18
18
1
def UpdateAnswerView(request, pk):
2
form = AnswerEditForm()
3
4
if request.method == 'POST' and pk is not None:
5
form = AnswerEditForm(request.POST)
6
if form.is_valid():
7
obj = form.save(commit=False)
8
try:
9
obj.question = Question.objects.get(id=pk)
10
obj.save()
11
return redirect('home')
12
except Question.DoesNotExist:
13
pass
14
15
16
context = {'form':form}
17
return render(request, 'exam/update_answer.html', context)
18