首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Django自定义标签过滤

Django自定义标签过滤
EN

Stack Overflow用户
提问于 2019-09-25 14:23:42
回答 1查看 49关注 0票数 0

需要一点帮助。

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

我的标签:

代码语言:javascript
复制
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]}

我的模型:

代码语言:javascript
复制
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

我的观点是:

代码语言:javascript
复制
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条新闻…我希望我没有更多地迷惑你!

非常感谢!

我的edit2:

代码语言:javascript
复制
{% 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 %}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-09-25 15:23:53

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

代码语言:javascript
复制
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

代码语言:javascript
复制
if category:
    article = article.filter(category=category)

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

代码语言:javascript
复制
if category:
    article = article.filter(article_category__category_title=category)

即通过指向article_category的category_title字段进行过滤。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58092246

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档