2017-08-30 30 views
-1

对于以下URL路由为blog应用,查询上通用的显示视图 - Django的

from django.conf.urls import url, include 
from django.views.generic import ListView, DetailView 
from blog.models import Post 

urlpatterns=[ 
    url(r'^$', ListView.as_view(
        queryset=Post.objects.all().order_by("-date")[:25], 
        template_name="blog/blog.html", 
        ) 
      ) 
] 

模板blog.html是,

{% extends "personal/header.html" %} 

{% block content %} 
    {% for post in object_list %} 
     <h5>{{post.date|date:"Y-m-d"}}<a href="/blog/{{post.id}}"> {{post.title}} </a></h5> 
    {% endfor %} 
{% endblock %} 

其中模型blog应用被定义为,

class Post(models.Model): 
    title = models.CharField(max_length=140) 
    body = models.TextField() 
    date = models.DateTimeField() 

    def __str__(self): 
     return self.title 

MTV的blog应用程序是结构S作为,

../blog 
    admin.py 
    apps.py 
    __init__.py 
    migrations 
    models.py 
    templates 
    tests.py 
    urls.py 
    views.p 

问:

{{post.id}}内部作为主键生成,为表中的每一行,但是,

是什么/blog/{{post.id}}意味着在模板( blog.html)?

+0

网址的帖子的细节 –

回答

1

当您想要访问特定的博客时,您需要链接到该博客。这就是/blog/{{post.id}}作为链接所做的事情。

so/blog/1给你第一个博客。只有你必须定义url模式,视图和模板。

url(r'^(?P<id>[^/]+)/$', views.get_blog, name='one_blog'), 

然后在访问量:

def get_blog(request, id): 
    blog = Blogs.objects.get(id=id) 
    return render(request, 'blogs/one_blog.html', locals()) 

然后在模板文件夹中,创建一个 '博客/ one_blog.html' 文件。最简单的例子是:

{% extends "personal/header.html" %} 

{% block content %} 
    <h5>{{blog.title}}</h5> 
    {{blog.body}} 
{% endblock %} 

只要确保你了解模板的文件夹结构。

1

它只是一个前缀/前缀/ ID /。也可以/条/ 1 ...没关系

urls.py

urlPatterns=[ 
     url(r'^$', ListView.as_view(
        model=Post, 
        template_name="blog/blog_list.html", 
        ) 
      ) 
     url(r'blog/(?P<pk>[\w-]+)/$', DetailView.as_view(
        model=Post, 
        template_name="blog/blog_detail.html", 
       ) 
      ) 

]