Django之tag的使用

settings.py:

#安装

pip install django-taggit

INSTALLED_APPS = [
    'myblog',
    'taggit',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

实体类中进行定义:

from taggit.managers import TaggableManager
class Post(models.Model):
    '''
    实体-文章类
    发布的文章
    '''
    STATUS_CHOICES={
        ('draft', '草稿'),
           ('published', '发布'),
    }
    title=models.CharField(max_length=300,verbose_name='文章标题')
    zhaiyao=models.TextField(verbose_name='摘要')
    content=models.TextField(verbose_name='文章内容')
    author = models.ForeignKey(User,related_name='blog_posts')
    publish = models.DateTimeField(default=timezone.now,verbose_name='发布时间')
    created = models.DateTimeField(auto_now_add=True,verbose_name='提交时间')
    updated = models.DateTimeField(auto_now=True,verbose_name='更新时间')
    status=models.CharField(max_length=10,choices=STATUS_CHOICES)
    tags=TaggableManager
    published=PublishedManager()
    # #分类标签
    tags = TaggableManager()

    class Meta:
        ordering = ('-publish',)

    def __str__(self):
        return self.title

    def __unicode__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('myblog:post_detail',args=[self.publish.year,
                                self.publish.strftime('%m'),
                                self.publish.strftime('%d'),
                                self.title.encode('utf-8')])

 

html:

{% extends "myblog/base.html" %}
{% block content %}
    {% if tag %}
         <h2>Posts tagged with "{{ tag.name }}"</h2>
    {% endif %}
    {% for post in posts %}
        <h2>
            <a href="{{ post.get_absolute_url }}">{{ post.title }}</a>
        </h2>
        <p class="tags">
{#            {{ post.tags.all|join:", " }}#}
            标签:
            {% for tag in post.tags.all %}
                <a href="{% url "myblog:post_list_by_tag" tag.slug %}">
                    {{ tag.name }}
                </a>
                {% if not forloop.last %}
                    ,
                {% endif %}
            {% endfor %}
        </p>
{#        posted @ 2016-04-18 16:16 similarface#}
        <p class="date">
            posted@{{ post.publish }} {{ post.author }}
        </p>
        {{ post.body|truncatewords:30|linebreaks }}
    {% endfor %}
    {% include "pagination.html" with page=posts %}
{#    {% include "pagination.html" with page=page_obj %}#}
{% endblock %}

 urls.py:

    url(r'^tag/(?P<tag_slug>[-\w]+)/$', views.post_list,name='post_list_by_tag'),

 views.py:

def post_list(request,tag_slug=None):
    '''
    文章的列表
    :param request:
    :return:所有文章的列表
    '''
    #获取所有的published的文章
    object_list=Post.published.all()
    tag=None
    if tag_slug:
        tag=get_object_or_404(Tag,slug=tag_slug)
        object_list=object_list.filter(tags__in=[tag])
    paginator=Paginator(object_list,3)
    #rquest没有就返回None
    page=request.GET.get('page')
    try:
        posts=paginator.page(page)
    except PageNotAnInteger:
        posts=paginator.page(1)
    except EmptyPage:
        posts=paginator.page(paginator.num_pages)
    return render(request,'myblog/post/list.html',{'page':page,'posts':posts,'tag':tag})

 

http://127.0.0.1:8000/myblog/?page=3

http://127.0.0.1:8000/myblog/tag/python/

 

 

posted @ 2016-04-20 09:43  similarface  阅读(2016)  评论(2编辑  收藏  举报