Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

object data editting form

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading