Django查看文章内容

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chengqiuming/article/details/85377685

一 修改ArticlePost类

class ArticlePost(models.Model):
    author = models.ForeignKey(User, related_name="article")
    title = models.CharField(max_length=200)
    slug = models.SlugField(max_length=500)
    column = models.ForeignKey(ArticleColumn, related_name="article_column")
    body = models.TextField()
    # 得到文章发布时的日期和时间
    created = models.DateTimeField(default=timezone.now)
    updated = models.DateTimeField(auto_now=True)


    class Meta:
        ordering = ("title",)
        # 对数据库中的这两个字段建立索引,会通过每篇文章的id和slug获取该文章对象
        # 这样建立索引后,能提高文章对象的速度
        index_together = (('id', 'slug'),)

    def __str__(self):
        return self.title

    # 对save方法进行重写,主要实现slugify操作
    def save(self, *args, **kargs):
        self.slug = slugify(self.title)
        super(ArticlePost, self).save(*args, **kargs)

    # 获取某篇文章对象的URL,并传递参数,从name到path,reverse起到逆向颠倒的作用
    def get_absolute_url(self):
        return reverse("article:article_detail", args=[self.id, self.slug])

二 在页面中增加到文章详情的链接

{% extends "article/base.html" %}
{% load staticfiles %}
{% block title %}文章列表{% endblock %}
{% block content %}
<div>
    <table class="table table-hover">
        <tr>
            <td>序号</td>
            <td>标题</td>
            <td>栏目</td>
            <td>操作</td>
        </tr>
        {% for article in articles %}
        <tr id={{ article.id }}>
            <td>{{ forloop.counter }}</td>
            <td><a href="{{ article.get_absolute_url }}">{{ article.title }}</a></td>
            <td>{{ article.column }}</td>
            <td>
            </td>
        </tr>
        {% endfor %}
    </table>
</div>
{% endblock %}

三 配置URL

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^article-column/$', views.article_column, name="article_column"),
    url(r'^rename-column/$', views.rename_article_column, name="rename_article_column"),
    url(r'^del-column/$', views.del_article_column, name="del_article_column"),
    url(r'^article-post/$', views.article_post, name="article_post"),
    url(r'^article-list/$', views.article_list, name="article_list"),
    url(r'^article-detail/(?P<id>\d+)/(?P<slug>[-\w]+)/$', views.article_detail, name="article_detail"),
]

四 新增视图函数

@login_required(login_url='/account/login')
def article_detail(request, id, slug):
    article = get_object_or_404(ArticlePost, id=id, slug=slug)
    return render(request, "article/column/article_detail.html", {"article":article})

五 编写一个模板显示文章详情

{% extends "article/base.html" %}
{% load staticfiles %}
{% block title %}文章详情{% endblock %}
{% block content %}
<div>
    <h1>{{ article.title }}</h1>
    <p>{{ user.username }}</p>
    <div>
        {{ article.body }}

    </div>
</div>
{% endblock %}

六 查看效果

 

展开阅读全文

没有更多推荐了,返回首页