在 django 1.8 中使用 CBV 插入 url

Slug in url with CBV in django 1.8

我使用 Django 1.8,我想在 urls 中使用 slugs 构建博客。但是我的代码不起作用。

这是我的模板,包含 link 到 post 的详细信息:

{% extends "base.html" %}
{% block head_title %}<title>Blog</title>{% endblock %}

{% block content %}
    <div class="container">
        <h2>Blog</h2>
        {% for i in blog %}
            <p><b>{{ i.date|date:"D, d M Y" }}</b></p>

            <h4><a href="{% url 'projde:blogdetail' slug=i.slug %}">{{ i.title }}</a></h4>
            <p>{{ i.text|truncatewords:100 }}</p>
            {% if not forloop.last %}
                <hr>
            {% endif %}
        {% endfor %}
    </div>
{% endblock %}

这是我的模型:

class BlogPost(models.Model):
    title = models.CharField(max_length=100)
    slug = models.SlugField(max_length=200, unique=True)
    text = models.TextField()
    date = models.DateTimeField()
    is_online = models.BooleanField(default=False)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse("blogdetail", kwargs={"slug": self.slug})

这是我在申请中的所有观点,但在这种情况下,最重要的是最后一个。

class Home(TemplateView):
    template_name = "projde/index.html"


class Projects(ListView):
    template_name = "projde/projects.html"
    context_object_name = "all_projects"
    model = ProjectItem

    def get_queryset(self):
        return ProjectItem.objects.filter(is_online=True)


class Resume(ListView):
    template_name = 'projde/resume.html'
    context_object_name = 'resume'
    model = ResumeItem

    def get_queryset(self):
        return ResumeItem.objects.filter(is_online=True)


class Blog(ListView):
    template_name = "projde/blog.html"
    context_object_name = "blog"
    model = BlogPost

    def get_queryset(self):
        s = BlogPost.objects.all().order_by("-date")
        return s

class BlogDetail(DetailView):
    model = BlogPost
    template_name = "projde/blogdetail.html"

和我的 url:

    urlpatterns = [
    url(r'^$', Home.as_view(), name="home"),
    url(r'^projects/$', Projects.as_view(), name="projects"),
    url(r'^resume/$', Resume.as_view(), name="resume"),
    url(r'^blog/$', Blog.as_view(), name="blog"),
    url(r'^blog/(?P<slug>\S+)$', BlogDetail.as_view(), name="blogdetail"),
]

ListView 模板中,如果您不设置 context_object_name,博客列表 post 将作为 blogpost_list 提供。

{% for blogpost in blogpost_list %}
<p><b>{{ blogpost.date|date:"D, d M Y" }}</b></p>
<h4><a href="{% url 'projde:blogdetail' slug=blogpost.slug %}">{{ blogpost.title }}</a></h4>
{% endfor %}

既然你已经为你的列表视图设置了context_object_name = 'blog',你应该将上面的for循环更改为{% for blogpost in blogs %}

如果您仍然收到错误 '{'slug': ''}',这表明您的数据库中有一个博客 post slug=''。通过 shell 或 Django 管理员修复此问题,然后刷新页面。

DetailView模板中,不需要for循环,可以用{{ blogpost }}访问博客post。