Skip to content
Advertisement

Show all articles from specific category [django]

I want show all Articles from specific category in my template ‘category_articles.list.html’ at the link: path(‘category/<name_of_category_SLUG>/’

I have:

URLS

urlpatterns = [
    path('show/<int:pk>/<slug:slug>', ArticleDetailView.as_view(), name='article_detail'),
    path('all/', AllArticlesListView.as_view(), name='all_articles_list'),
    path('category/<slug:slug>/', CategoryArticlesList.as_view(), name='category_articles_list'),
]

MODELS

class Created(models.Model):
    created_on = models.DateTimeField(auto_now_add=True, null=True)  

    class Meta:
        abstract = True


class ArticleCategory(Created):
    category_name = models.CharField(max_length=128)
    slug = models.SlugField(null=False, unique=False)

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.category_name)
        return super().save(*args, **kwargs)

    def __str__(self):
        return self.category_name

    class Meta:
        verbose_name_plural = 'Article categories'


class Article(Created):
    title = models.CharField(max_length=120)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    snippet = models.TextField(null=False)  # ustawić max_lenght
    body = RichTextField(null=False)
    category = models.ManyToManyField(ArticleCategory, related_name='articles')  # TODO: ustawić on_delete
    image = models.ImageField(blank=True, null=True, upload_to='article_image/')
    slug = models.SlugField(null=False, unique=False)

    def save(self, *args, **kwargs):  # opisać tą funckję
        if not self.slug:
            self.slug = slugify(self.title)
        return super().save(*args, **kwargs)

    def get_absolute_url(self):
        return reverse('news:article_detail', kwargs={'pk': self.pk, 'slug': self.slug})

    def article_categories(self):
        # zwraca nam wszystkie kategorię artykułu w stringu
        return ", n".join([x.category_name for x in self.category.all()])

    def __str__(self):
        return f"{self.title}"

    class Meta:
        verbose_name_plural = 'Articles'

VIEWS

class CategoryArticlesList(DetailView):
    template_name = 'news/category_articles_list.html'
    model = ArticleCategory




class AllArticlesListView(ListView):
    template_name = 'news/articles_list.html'
    model = Article
    paginate_by = 2

    def get_queryset(self):
        return self.model.objects.all().order_by('-created_on')


class ArticleDetailView(DetailView):
    template_name = 'news/article_detail.html'
    model = Article

ARTICLES_LIST.HTML template

ALL NEWS


{% if object_list  %}
    {% for article in object_list %}      

        TITLE: <a href="{{ article.get_absolute_url  }}"> {{ article.title }} </a> 

        CATEGORY_iterator:
        {% for category in article.category.iterator %}
            <a href="{% url 'news:category_articles_list' category.slug %}">    {{ category | upper}} </a>
        {% endfor %}<br>

ARTICLE_DETAIL.HTML template

ONE SPECIFIC NEWS

<h3>TITLE: {{ article.title }}</h3>
<a href="{% url 'news:article_detail' pk=article.pk slug=article.slug  %}">
    {% url 'news:article_detail' pk=article.pk slug=article.slug  %}</a> <br>
ID:
{{ article.id }} <br>

AUTHOR:
{{ article.author.username }} <br>

CATEGORY_iterator:
{% for category in article.category.iterator %}
    <a href="{% url 'news:category_articles_list' category.slug %}">    {{ category | upper}} </a>
{% endfor %}<br>

finally….

CATEGORY_ARTICLES_LIST.HTMLtemplate

ALL ARTICLES FROM CATEGORY: {{ articlecategory.category_name | upper }}

I don’t know how put all articles to ARTICLE_DETAIL.HTML template…

Advertisement

Answer

You can iterate all articles from the reverse relation:

articlecategory.articles.all

I am not sure if you can use that in django templates and if it needs to be used with or without the “()”.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement