Django过滤基于标签的博客

时间:2015-07-26 02:04:51

标签: django

我正在尝试根据标签过滤我的博客。我已经设法找出如何显示所有标签,但是现在我希望用户能够点击标签并根据该标签显示博客帖子的过滤列表。

我收到了一个错误:

ValueError invalid literal for int() with base 10: 'testtag'

url.py

urlpatterns = [
    # Examples: /blogs
    url(r'^tags$', 'blog.views.tags', name='tags'),
    url(r'^tags/(?P<blog_tagslug>[\w-]+)$', 'blog.views.tagslist', name='tagslist'), 

views.py

def tags(request):
    blog_obj = Tag.objects.all()
    paginator = Paginator(blog_obj, 5)

    page = request.GET.get('page')

    try:
        blog_list = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        blog_list = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        blog_list = paginator.page(paginator.num_pages)

    template_hash = {'blog_list':blog_list}
    return render(request,'blog/tags.html', template_hash)

def tagslist(request, blog_tagslug):
    #blog = Blog.objects.get(pk=blog_id)
    #blog = Tag.objects.all().filter(tagslug=blog_tagslug)
    blog = Blog.objects.all().filter(tags=blog_tagslug)

    paginator = Paginator(blog, 2)

    page = request.GET.get('page')

    try:
        blog_list = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        blog_list = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        blog_list = paginator.page(paginator.num_pages)

    template_hash = {'blog_list':blog_list}
    return render(request,'blog/index.html', template_hash)

tags.html(工作正常)

<h1>All Tags</h1>
{% if blog_list %}
    <ul>
    {% for blog in blog_list %}
        {{ blog.image.thumbnail.url }}

        <li><a href="{% url "tagslist" blog.tagslug %}">{{ blog.tagslug }}</a></li>
        {{ blog.tags.all|join:", " }} <br>
    {% endfor %}
    </ul>
{% else %}
    <p>No blogs are available.</p>
{% endif %}

<div class="pagination">
    <span class="step-links">
        {% if blog_list.has_previous %}
            <a href="?page={{ blog_list.previous_page_number }}">previous</a>
        {% endif %}

        <span class="current">
            Page {{ blog_list.number }} of {{ blog_list.paginator.num_pages }}.
        </span>

        {% if blog_list.has_next %}
            <a href="?page={{ blog_list.next_page_number }}">next</a>
        {% endif %}
    </span>
</div>   

tagslist.html(不起作用会收到错误)

<h1>Blog Index</h1>
{% if blog_list %}
    <ul>
    {% for blog in blog_list %}
        {{ blog.image.thumbnail.url }}

        <li><a href="{% url "show" blog.id blog.slug %}">{{ blog.blog_title }}</a></li>
        {{ blog.tags.all|join:", " }} <br>
    {% endfor %}
    </ul>
{% else %}
    <p>No blogs are available.</p>
{% endif %}

<div class="pagination">
    <span class="step-links">
        {% if blog_list.has_previous %}
            <a href="?page={{ blog_list.previous_page_number }}">previous</a>
        {% endif %}

        <span class="current">
            Page {{ blog_list.number }} of {{ blog_list.paginator.num_pages }}.
        </span>

        {% if blog_list.has_next %}
            <a href="?page={{ blog_list.next_page_number }}">next</a>
        {% endif %}
    </span>
</div>

models.py

from django.db import models
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.conf import settings

# Create your models here.

class Image(models.Model):
     name = models.CharField(max_length = 255)
     image = models.ImageField(upload_to="%Y/%m/%d",max_length=500,blank=True,null=True)
     thumbnail = models.ImageField(upload_to="%Y/%m/%d",max_length=500,blank=True,null=True)

     def __str__(self):
        return self.name


class Tag(models.Model):
    tagslug = models.SlugField(max_length=200, unique=True)

    def __str__(self):
        return self.tagslug

class Author(models.Model):
    authorname = models.CharField(max_length=200, null=True)

    def __str__(self):
        return self.authorname


class Blog(models.Model):
    blog_title = models.CharField(max_length = 200)
    author = models.ForeignKey(Author)
    image = models.ForeignKey(Image)    
    blog_content = models.TextField()
    slug = models.SlugField(max_length=200, unique=True)
    publish = models.BooleanField(default=True)
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)
    tags = models.ManyToManyField(Tag)
    user_id = models.ForeignKey(User)

    def __str__(self):
        return self.blog_title

class Comment(models.Model):
    comment_content = models.TextField()
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)  
    blog_id = models.ForeignKey(Blog)
    user_id = models.ForeignKey(User)

    def __str__(self):
        return '{0}, {1}'.format(self.comment_content, self.created)

1 个答案:

答案 0 :(得分:2)

问题是tags期望Tag个对象的列表,而你传递一个字符串。您应该按标签的slug过滤博客,如下所示:

blog = Blog.objects.all().filter(tags__tagslug=blog_tagslug)