Reputation: 175
I am creating a book app where users can sign up and start reading.
This is the model.py for the book:
from django.db import models
from django.urls import reverse
from django.conf import settings
class Chapter(models.Model):
title = models.CharField(max_length=200, unique=True)
slug = models.SlugField(unique=True)
date_completed = models.DateTimeField(blank=True, null=True)
completed = models.BooleanField(default=False)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("course:subchapter_list", kwargs={"pk": self.pk})
class SubChapter(models.Model):
chapter = models.ForeignKey(Chapter, on_delete=models.CASCADE)
title = models.CharField(max_length=200, unique=True)
slug = models.SlugField(unique=True)
completed = models.BooleanField(default=False)
def __str__(self):
return self.title
class SubSection(models.Model):
sub_chapter = models.ForeignKey(SubChapter, on_delete=models.CASCADE)
title = models.CharField(max_length=200, unique=True)
slug = models.SlugField(unique=True)
text = models.TextField(null=True, blank=False)
completed = models.BooleanField(default=False)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("course:detail",
kwargs={"slug": self.sub_chapter.slug,
"slug2": self.slug,
"pk": self.sub_chapter.chapter.pk,
}
)
How can I monitor each user's progress such that when a subsection/subchapter/chapter is viewed/read, that model instance's completed attribute is set to True just for that user? My current implementation sets completed to True for everyone.
I would appreciate code snippets demonstrating how you might implement it.
Upvotes: 4
Views: 997
Reputation: 378
If you want to monitor the reading progress for every user, you can't have the completed fields on the Chapter
, SubChapter
and SubSection
models, you need a new one related to the user. I would do something like this:
class ReadingProgress(models.Model):
user = models.ForeignKey(User)
completed_chapter = models.ForeignKey(Chapter)
completed_subchapter = models.ForeignKey(SubChapter)
completed_subsection = models.ForeignKey(SubSection)
If you have different books, you should add foreign keys to the book model as well.
Then in the views that fetch the chapters, sections and so on, you can get the ReadingProgress
object for the specific user (and book?) and set the corresponding values.
Upvotes: 2