【问题标题】:Django Custom Tag FilteringDjango 自定义标签过滤
【发布时间】:2019-09-25 06:23:42
【问题描述】:

需要一点帮助。

我有一个新闻网站,我想做的是制作一个自定义标签(它必须是一个自定义标签,这是我的任务的一部分),它将显示一个类别中的最新 3 条新闻。因此,假设我单击“健康”文章,文章打开,我的自定义标签在文章旁边呈现来自健康类别的最新 3 条新闻。希望没有把你弄糊涂,我还在学习中。

我的标签:

from django import template
from news.models import Article

register = template.Library()

@register.inclusion_tag("news/categories.html")
def show_results(category=None):
    article = Article.objects.all()
    if category:
        article = article.filter(category=category)
    return {'article': article[:3]}

我的模型:

class Category(models.Model):
    category_title = models.CharField(max_length=200, default="")

    def __str__(self):
        return self.category_title


class Article(models.Model):
    title = models.CharField('title', max_length=200, blank=True)
    slug = AutoSlugField(populate_from='title', default="",
                         always_update=True, unique=True)
    author = models.CharField('Author', max_length=200, default="")
    description = models.TextField('Description', default="")
    is_published = models.BooleanField(default=False)
    article_text = models.TextField('Article text', default="")
    pub_date = models.DateTimeField(default=datetime.now, blank=True)
    article_image = models.ImageField('Article Image')
    article_category = models.ForeignKey(Category, on_delete="models.CASCADE", default="")
    img2 = models.ImageField('Article Image 2', default="", blank=True)
    img3 = models.ImageField('Article Image 3', default="", blank=True)
    img4 = models.ImageField('Article Image 4', default="", blank=True)
    img5 = models.ImageField('Article Image 5', default="", blank=True)
    img6 = models.ImageField('Article Image 6', default="", blank=True)

    def __str__(self):
        return self.title

我的看法:

from django.shortcuts import render, reverse, get_object_or_404
from django.views import generic
from news.models import Article, Category
from .forms import CommentForm
from django.http import HttpResponseRedirect


class IndexView(generic.ListView):

    template_name = 'news/index.html'
    context_object_name = 'latest_article_list'

    def get_queryset(self):
        return Article.objects.order_by("-pub_date").filter(is_published=True)[:6]


class CategoryView(generic.ListView):

    template_name = 'news/categories.html'
    context_object_name = 'category'

    def get_queryset(self):
        return Article.objects.filter(article_category__category_title="Politics")


class ArticlesView(generic.ListView):
    context_object_name = 'latest_article_list'
    template_name = 'news/articles.html'
    paginate_by = 5

    def get_context_data(self, **kwargs):
        context = super(ArticlesView, self).get_context_data(**kwargs)
        context['categories'] = Category.objects.all()
        return context

    def get_queryset(self):
        category_pk = self.request.GET.get('pk', None)
        if category_pk:
            return Article.objects.filter(article_category__pk=category_pk).order_by("-pub_date")
        return Article.objects.order_by("-pub_date")


def article(request, article_id):

    article = get_object_or_404(Article, pk=article_id)
    context = {'article': article}

    return render(request, 'news/article.html', context)

编辑:所以,为了进一步澄清,我的问题是:当我点击一篇“健康”文章并打开它时,我如何让我的自定义标签只过滤来自该特定类别的文章,抱歉,如果它令人困惑! 所以如果我点击健康,我需要标签来呈现最新的 3 篇健康文章,如果我点击“音乐”文章,我需要标签来呈现来自“音乐”类别的最新 3 条新闻……我希望我没有让你更困惑!

非常感谢你!!!

编辑2: 我的html:

{% extends "news-base.html" %}

{% load static %}
{% load article_extras %}


{% block article %}

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>



{% show_results article_category %}

<div class="preloader d-flex align-items-center justify-content-center">
  <div class="spinner">
    <div class="double-bounce1"></div>
    <div class="double-bounce2"></div>
  </div>
</div>
<!-- {% show_results article.category %} -->

<!-- ##### Post Details Area Start ##### -->
<section class="container post-details-area">
  <div class="container single-article-div">
    <hr class="hr-single">
    <h2 class="single-article-titles">{{ article.title }}</h2>
    <hr class="hr-single">
    <img class="single-article-img" src="{{ article.article_image.url }}" alt="">
    <!-- *********************************** -->
    <hr class="hr-single">
    <p>Category: {{ article.article_category }}</p>
    <hr class="hr-single">
    <div class="row justify-content-center">
      <!-- Post Details Content Area -->
      <div class="col-12 col-xl-8">
        <div class="post-details-content bg-white box-shadow">
          <div class="blog-thumb">

          </div>
          <div class="blog-content">
            <div class="post-meta">
              <a href="#">{{ article.pub_date }}</a>
            </div>
            <h3 class="single-article-titles post-title"> {{ article.description }}</h3>
            <hr>

            <!-- Post Meta -->
            <div class="post-meta-2">
              <a href="#"><i class="fa fa-eye" aria-hidden="true"></i> 1034</a>
              <a href="#"><i class="fa fa-thumbs-o-up" aria-hidden="true"></i> 834</a>
              <a href="#"><i class="fa fa-comments-o" aria-hidden="true"></i> 234</a>
            </div>
            <p>{{ article.article_text }}</p>
            <hr />

            {% include "partials/_thumbnails.html" %}

            <hr>
            <p>Author: {{ article.author }}</p>

            <hr>

            {% for comment in article.comments.all %}
            <div class="comment">
              <div class="date">{{ comment.created_date }}</div>
              <strong>{{ comment.author }}</strong>
              <p>{{ comment.text|linebreaks }}</p>
            </div>
            {% empty %}
            <p>No comments here yet :(</p>
            {% endfor %}
          </div>
          <!-- Post A Comment Area -->
          <div class="post-a-comment-area bg-white mb-30 p-30 box-shadow clearfix">
            <!-- Section Title -->
            <div class="section-heading">
              <h5>LEAVE A REPLY</h5>
            </div>
            <!-- Reply Form -->
            <div class="contact-form-area">
              <form action="#" method="post">
                <div class="row">
                  <div class="col-12 col-lg-6">
                    <input type="text" class="form-control comment-section" id="name" placeholder="Your Name*"
                      required />
                  </div>
                  <div class="col-12 col-lg-6">
                    <input type="email" class="form-control comment-section" id="email" placeholder="Your Email*"
                      required />
                  </div>
                  <div class="col-12">
                    <textarea name="message" class="form-control" id="message" cols="30" rows="10"
                      placeholder="Message*" required></textarea>
                  </div>
                  <div class="col-12">
                    <button class="btn mag-btn comment-section" type="submit">
                      Submit Comment
                    </button>
                  </div>
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</section>
<script>
  jQuery(document).ready(function ($) {
    //set here the speed to change the slides in the carousel
    $('#myCarousel').carousel({
      interval: 5000
    });
    //Loads the html to each slider. Write in the "div id="slide-content-x" what you want to show in each slide
    $('#carousel-text').html($('#slide-content-0').html());
    //Handles the carousel thumbnails
    $('[id^=carousel-selector-]').click(function () {
      var id = this.id.substr(this.id.lastIndexOf("-") + 1);
      var id = parseInt(id);
      $('#myCarousel').carousel(id);
    });
    // When the carousel slides, auto update the text
    $('#myCarousel').on('slid.bs.carousel', function (e) {
      var id = $('.item.active').data('slide-number');
      $('#carousel-text').html($('#slide-content-' + id).html());
    });
  });

</script>

{% endblock %}

【问题讨论】:

  • 这篇文章,毫无疑问...
  • 什么意思?我的问题是:当我单击“健康”文章并打开它时,如何使我的自定义标签仅过滤该特定类别的文章,我在原始帖子中对此进行了解释,如果令人困惑,请见谅!所以如果我点击健康,我需要标签来呈现最新的 3 篇健康文章,如果我点击“音乐”文章,我需要标签来呈现来自“音乐”类别的最新 3 条新闻……我希望我没有让你更困惑!
  • 您的自定义标签似乎已经完成了您想要的操作......有什么问题?
  • 它实际上没有,这就是我问的原因:/它总是呈现所有文章,不按类别过滤它们......我搞砸了一些东西,不知道是什么或在哪里......
  • 您提供的代码没有显示模板标签不起作用。也许你忘了在你使用它的地方包含模板文件..?

标签: python django model categories custom-tag


【解决方案1】:

您的模板{% show_results article_category %} 使用变量article_category 但您的视图并未在上下文中公开此变量。将它包含在您的上下文中应该可以解决您的问题,即:

def article(request, article_id):
    article = get_object_or_404(Article, pk=article_id)
    context = {
        'article': article,
        'article_category': article.article_category.category_title
    }
    return render(request, 'news/article.html', context)

哦,刚刚注意到...,您的模板标签试图过滤category

if category:
    article = article.filter(category=category)

但是模型中的字段名称是article_category。此外,由于它是外键,因此您需要:

if category:
    article = article.filter(article_category__category_title=category)

即按指向 article_category 的 category_title 字段过滤。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-06
    • 2021-11-24
    • 1970-01-01
    • 1970-01-01
    • 2012-07-07
    • 2020-11-07
    • 2021-12-31
    相关资源
    最近更新 更多