Django永久链接不起作用

时间:2013-03-20 08:19:22

标签: django permalinks

models.py

    from django.db import models

    class Blog(models.Model):
        time = models.DateTimeField(auto_now_add = True)
        title = models.CharField(max_length = 100)
        slug = models.SlugField()
        perex = models.TextField()
        content = models.TextField()
        @models.permalink
        def get_absolute_url(self):
            return ('blog', [self.slug])

        def __unicode__(self):
            return self.title

        class Meta:
            ordering = ['-time']

views.py

    from django.shortcuts import render_to_response, get_object_or_404
    from blog.models import Blog

    def blog_entries(request):
        blogs = Blog.objects.all()[0:3]
        title = "Blogs"
        return render_to_response('blog/blog.djhtml', {'blogs': blogs, 'title': title,})

    def blog_single_entry(request, slug):
        blog = get_object_or_404(Blog, slug=slug)
        title = blog.title
        return render_to_response('blog/single.djhtml', {'blog': blog, 'title': title,})

url.py

    from django.conf.urls import patterns, include, url

    # Uncomment the next two lines to enable the admin:
    from django.contrib import admin
    admin.autodiscover()

    urlpatterns = patterns('',
        # Examples:
        # url(r'^$', 'kablog.views.home', name='home'),
        # url(r'^kablog/', include('kablog.foo.urls')),

        # Uncomment the admin/doc line below to enable admin documentation:
        # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

        # Uncomment the next line to enable the admin:
         url(r'^admin/', include(admin.site.urls)),
         url(r'^blog/', 'blog.views.blog_entries', name='blog'),
         url(r'^blog/(?P<slug>[-\w]+)/', 'blog.views.blog_single_entry', name='single_blog'),
    )

模板

    {% extends 'base.djhtml' %}
    {% block title %}| {{title}}{% endblock %}
    {% block content %}
    <div class="hero-unit">
      <h1>Welcome to my Blog</h1>
      <p>Where knowledge is always free</p>
      <p>
        <a class="btn btn-primary btn-large">
          Read More
        </a>
      </p>
    </div>
    <div class="row">
        {% for blog in blogs %}
            <div class="span4">
                <h2>{{blog}}<small>{{blog.time|date:"M D d Y"}}</small></h2>
                <p>{{blog.perex|safe}}</p>
                <a class="btn" href="{{ blog.get_absolute_url }}">
                  Read More
                </a>
            </div>
        {% endfor %}
    </div>
    {% endblock %}

blog.get_absolute_url没有返回slug,即使我已经尝试浏览“blog / my-first-blog”,浏览器只显示主页博客而不是single_blog,如果没有,则不会返回404错误你浏览“blog / dgdsghdsfhdsfhds”

2 个答案:

答案 0 :(得分:0)

我也试过了,但是我无法让它发挥作用,所以我尝试其他方法

class Blog(models.Model):
    [......]

    @property
    def get_blog_url(self):
        return reverse('blog', args=[self.slug])

<a class="btn" href="{{ blog.get_blog_url }}">
    Read More
</a>

答案 1 :(得分:0)

您需要@models.permalink而不是@permalink