Django ModelForm not prepopulating fields when updating instance – "This field is required" errors

I'm making a project in Django--UniTest. The idea is to let our university's faculty create and conduct online surprise tests on it. The issue I'm facing is with the update_test.html page which is not prepopulating the data. Here's the view function.

@login_required
def update_test(request, test_id):
    test = get_object_or_404(Test, id=test_id)
    questions = test.questions.all()
    print(test)
    print(test.name, test.course, test.batch, test.total_marks, test.total_questions, test.duration)

    if request.method == 'POST':
        form = testForm(request.POST, instance=test)
        print("Form Data:", request.POST)
        print("Form Errors:", form.errors)
        print(form.initial)

        # Check if the form is valid
        # and if the test ID matches the one in the URL
        if form.is_valid():
            form.save()

            # Update questions and choices
            for question in questions:
                question_text = request.POST.get(f"question_{question.id}")
                question_marks = request.POST.get(f"question_marks_{question.id}")
                question.text = question_text
                question.marks = question_marks
                question.save()

                # Update choices for each question
                for choice in question.choices.all():
                    choice_text = request.POST.get(f"choice_{question.id}_{choice.id}")
                    is_correct = request.POST.get(f"is_correct_{question.id}_{choice.id}") is not None
                    choice.text = choice_text
                    choice.is_correct = is_correct
                    choice.save()

            return redirect('list_tests')

    else:
        form = testForm(instance=test)

    return render(request, 'update_test.html', {'form': form, 'test': test, 'questions': questions})

Output:

Dummy | Computer Networking 2 | BCA | 3 marks | 2 questions
Dummy Computer Networking 2 | CSE309 BCA | 2022-2025 | 4th sem | A 3 2 10:00:00
Form Data: <QueryDict: {'csrfmiddlewaretoken': ['7WtmPpjyY1Ww1cCRuRxEOpwKmESSSjVv8jXToOQ5PSb4MEU5tZXgA93tUwzkGTeU']}>
Form Errors: <ul class="errorlist"><li>name<ul class="errorlist"><li>This field is required.</li></ul></li><li>batch<ul class="errorlist"><li>This field is required.</li></ul></li><li>total_marks<ul class="errorlist"><li>This field is required.</li></ul></li><li>total_questions<ul class="errorlist"><li>This field is required.</li></ul></li><li>duration<ul class="errorlist"><li>This field is required.</li></ul></li></ul>
{'id': 41, 'name': 'Dummy', 'course': 4, 'batch': 11, 'total_marks': 3, 'total_questions': 2, 'duration': datetime.timedelta(seconds=36000)}

And in my update_test.html page, I'm using the form like this:

<form method="post" action="{% url 'update_test' test.id %}">
                        {% csrf_token %}  
                        {{ form.as_p }}
<button type="submit" class="create-button">Update Test</button>
                      
</form>

I'm also loading the questions and they're being filled successfully but the test details gives an 'This field is required error'. Also, here's the forms.py and Test Model

class testForm(forms.ModelForm):
    class Meta:
        model = Test
        exclude = ['user', 'status', 'is_results_visible']
    
class Test(models.Model):
    name               = models.CharField(max_length=255)
    course             = models.ForeignKey(Course, on_delete=models.CASCADE, null=True, blank=True, default=None)
    batch              = models.ForeignKey(Batch, on_delete=models.CASCADE)
    total_marks        = models.IntegerField()
    total_questions    = models.IntegerField()
    duration           = models.DurationField(help_text="Test duration (hh:mm:ss)")
    is_results_visible = models.BooleanField(default=False)
    status             = models.BooleanField(default=False, help_text="False = Upcoming, True = Completed")
    user               = models.ForeignKey('auth.User', on_delete=models.CASCADE, null=True, blank=True, default=None)

so pls help me understand. I've tried ChatGPT and checked everything but can't figure out.

Вернуться на верх