2015-04-22 64 views
0

categories.html#这就是我想被CategoryView.as_view()调用的那种从不起作用的东西。如何index.html工作,但我已经在index.html中如下硬编码链接。尽管index.html扩展了base.html,它是输出url的地方。 编辑:避免混淆,这是在我的猜测应该工作,但是从我的根目录现在Page not found (404)尽管我努力学习Django模板,但它仍然令人失望

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

显示指数以下错误index.html的模板可当我键入http://127.0.0.1:8000它的工作原理,但我想要的东西像这样http://127.0.0.1:8000/cartegories/index.htmlcategories.html)我认为index.html或categories.html在输入时不可见,这很好。

我不能相信这是带我12小时,所有可能的直观调整仍然无法让它工作。请有人建议做错了什么。在essense我只是outputing hellow世界categories.html但以后我会遍历并列出所有类别在我的博客...如果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 

回答

0

更改的顺序文件中的URL解决了问题。一般而言,主urls.py的顺序是可读性重要,但/斜线在后/ url.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)), 
] 

而且

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> 
相关问题