Basic Django,How to write a URLConf for a blog's DetailView Post?

时间:2015-09-01 22:56:38

标签: python django

I am new to Django , I have a problem writing the right code for URLConf for my blog app in mysite directory.The blog appears at http://127.0.0.1:8000/blog/ but i could not DetailView the Posts within the blog using a hyperlink. The error i am getting is "Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:

  1. ^blog/ ^$
  2. ^blog/ ^(blog/?P\d+)/$
  3. ^admin/ The current URL, blog/3, didn't match any of these."

My mysite\blog\url.py file looks like this:

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

urlpatterns=patterns('',
                     url(r'^$',ListView.as_view(
                         queryset=Post.objects.all().order_by("-date")[:10],
                         template_name="blog.html")),
                     url(r'^(blog/?P<post_id>\d+)/$', DetailView.as_view(
                         model = Post,
                         template_name = "post.html")),                    
)

How can i display a DetailView for the Posts in my blog app?I have the template files of blog, base and post.html. The post.html looks like:

{%extends "base.html"%}
{%block content%}


<h3><a href="/blog/{{post.id}}">{{post.title}}</a></h3>
<div class ="post_meta">
    on {{post.date}}
</div>

<div class = "post_body">
{{post.body|safe}}
</div>

{% endblock %}

1 个答案:

答案 0 :(得分:1)

Your URLConf isn't properly calling the URL in your template.

url(r'^(blog/?P<post_id>\d+)/$',

...is trying to get a url like www.yoursite.com/blog/(blog/post_id/ with the /(blog as part of the url. First, you've already included /blog/ when you include yourapp.urls in the main URLConf. Second, your ( is in the wrong spot.

Try changing it to:

url(r'^(?P<post_id>\d+)/$',....rest of your URLConf....