I am working on a learning platform. I want to be able to track user progress of the chapters completed. I cerated a new model and inserted it into the html using a form. However when I submit, I keep getting a TypeError with the specifics that “Field ‘id’ expected a number but got <QueryDict: {‘csrfmiddlewaretoken’: [‘YMvOO6ZYGWVVfxfgoFLVEanZ9zK70CrqlRIx5Y2LOkbzH8Mx3UHPlQYczqLbq1Qt’], ‘chapter’: [‘2’], ‘completed’: [‘on’], ‘student’: [‘1’]}>“
I tried converting all the variables I was using to identify the user, student and chapter to their primary keys but I got even more complicated error. If there is an easier way to track the progress or a tutorial on a way to do it, please share.
Here’s what I tried
This is he StudemtProgress Model
class StudentProgress(models.Model):
student = models.ForeignKey(
Student, on_delete=models.CASCADE, related_name="student_progress"
)
chapter = models.ForeignKey(
Chapter, on_delete=models.CASCADE, related_name="student_progress"
)
completed = models.BooleanField(default=False)
This is the form. Some of the code is to pick only the current logged in user and the chapter of th page that it is being displayed.
class StudentProgressForm(forms.ModelForm):
class Meta:
model = StudentProgress
fields = ("chapter", "completed", "student")
# widgets = {
# "student": forms.HiddenInput(),
# }
def __init__(self, user, student_slug, chapter_slug, *args, **kwargs):
super(StudentProgressForm, self).__init__(*args, **kwargs)
student_queryset = Student.objects.filter(user=user, student_slug=student_slug)
if student_queryset.exists():
self.instance.student = student_queryset.first()
else:
self.instance.student = None
if student_queryset.exists():
self.fields["student"].initial = student_queryset.first()
current_chapter = Chapter.objects.filter(chapter_slug=chapter_slug).first()
self.fields["chapter"].initial = current_chapter
def get_current_chapter(self, current_chapter_slug):
return Chapter.objects.filter(chapter_slug=current_chapter_slug).first()
This is the logic I used in the views.py file
if request.method == "POST":
form = StudentProgressForm(
request.POST,
instance=single_chapter,
student_slug=student_slug,
chapter_slug=chapter_slug,
)
if form.is_valid():
form.save()
return redirect("user_dashboard")
else:
form = StudentProgressForm(
user=request.user,
instance=single_chapter,
student_slug=student_slug,
chapter_slug=chapter_slug,
)
And lastly the html file has this form
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>