Im trying to rewrite my whole app from function views to class views. Right now Im struggle with Tag.
This how its looks before views.py
def tagged(request, slug):
tag = get_object_or_404(Tag, slug=slug)
articles = Article.objects.filter(tag=tag)
paginator = Paginator(articles, 5)
page_number = request.GET.get("page")
page_obj = paginator.get_page(page_number)
context = {
"tag": tag,
"page_obj": page_obj,
}
return render(request, "web/home.html", context)
And right now Im trying rewrite it to Class View but I dont know how to use get_object_or_404 in class and then filter my model Article by tag
class Tagged(ListView):
model = Article
paginate_by = 5
model.py
class Article(models.Model):
headline = models.CharField(max_length=100)
article_content = models.CharField(max_length=10000)
article_author = models.ForeignKey(User, on_delete=models.CASCADE)
article_photos = models.URLField(blank=True, max_length=300)
yt_links = models.URLField(blank=True, max_length=300)
article_image_upload = models.ImageField(blank=True, upload_to="images/")
slug = models.SlugField(null=True, unique=True, max_length=100)
tag = TaggableManager(blank=True)
likes = models.ManyToManyField(User, related_name="article_likes")
timestamp = models.DateTimeField(auto_now_add=True)
def serialize(self):
return {
"id": self.id,
"headline": self.headline,
"article_content": self.article_content,
"article_author": self.article_author,
"article_image_upload": self.article_image_upload,
"tag": self.tag,
"yt_links": self.yt_links,
"likes": self.likes,
"timestamp": self.timestamp.strftime("%b %d %Y, %I:%M %p"),
}
CodePudding user response:
You can override get_queryset
method to filter Article
. For example:
class Tagged(ListView):
model = Article
paginate_by = 5
def get_queryset(self):
tag = get_object_or_404(Tag, slug = self.kwargs['slug'])
return super().get_queryset().filter(tag=tag)