尽管我努力学习Django模板,但仍然令人费解

时间:2015-04-22 18:26:55

标签: python django python-3.x django-templates

categories.html#这是我想要被CategoryView.as_view()调用的东西,它永远不会起作用。 Howevwer index.html有效但我在index.html中对链接进行了硬编码。虽然index.html扩展了base.html,这是输出url的地方。 编辑:避免混淆这是index.html模板中可用的内容,我认为应该可以使用但现在为索引显示以下错误Page not found (404)

<li><a href="{% url 'all_categories' %}">All</a></li>
当我输入http://127.0.0.1:8000时,从我的根目录

它可以工作,但我想要这样的http://127.0.0.1:8000/cartegories/index.htmlcategories.html)我假设index.html或类别。键入时html不可见,这很好。

我无法相信这是带我12小时所有可能的直观调整仍然无法让它工作。请有人告诉我做错了什么。在essense中,我只是在categories.html中输出hellow world,但后来我会迭代并列出我博客中的所有类别......如果hello world无效,那么什么都不会......

#posts urls.py
from django.conf.urls import include, url
from django.contrib import admin

from .views import IndexView, CategoryView

urlpatterns = [
    url(r'^$', IndexView.as_view(), name='index'),
    url(r'^all_categories$', CategoryView.as_view(), name='all_categories'),

    # stuff i have tried

]

#admin urls.py
from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
    url(r'^/', include('posts.urls', namespace="posts")),
    url(r'^admin/', include(admin.site.urls)),
]

#views.py

from django.shortcuts import render
from .models import Post, Comment, Category, Reply
from django.views import generic

class IndexView(generic.ListView):
    template_name = 'posts/index.html'
    context_object_name = 'posts'
    model = Post

    def get_context_data(self, **kwargs):
        context = super(IndexView, self).get_context_data(**kwargs)
        context['categories'] = Category.objects.all()
        return context

class CategoryView(generic.ListView):
    template_name = 'posts/categories.html'
    context_object_name = 'categories'
    model = Category


#modesl.py

class Category(models.Model):
    category_name = models.CharField(max_length=200)

    class Meta:
        verbose_name_plural = "categories"

    def __str__(self):
        return self.category_name

    def get_absolute_url(self):
        return reverse('all_categories')

class Post(models.Model):

    title = models.CharField(max_length=200)
    …
    category = models.ForeignKey(Category)

    def save(self, *args, **kargs):
        if not self.id:
            self.slug = slugify(self.title)

        super(Post, self).save(*args, **kargs)

    def __str__(self):
        return self.title

1 个答案:

答案 0 :(得分:0)

更改文件中URL的顺序解决了问题。一般来说,主urls.py的顺序对于可读性很重要,但/斜线的功能很重要

#admin urls.py
from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
    url(r'^/', include('posts.urls', namespace="posts")),
    url(r'^admin/', include(admin.site.urls)), 
]

同样在post / url.py文件中,我在正则表达式的末尾添加了/

urlpatterns = [

    url(r'^$', IndexView.as_view(), name='index'),
    url(r'^categories/$', CategoryView.as_view(), name='all_categories'),

]

最后在模板中,html内容如下:

<li><a href="{% url 'posts:all_categories' %}">All</a></li>