我在Django有一个problam。我是一个不成熟的Django开发人员。我无法在模板中显示我的“类别”数据。这是我的代码:
models.py
from django.db import models
from taggit.managers import TaggableManager
class Category(models.Model):
title = models.CharField(max_length=40)
def __unicode__(self):
return self.title
class Post (models.Model):
title = models.CharField(max_length=150)
body = models.TextField()
date = models.DateTimeField()
tags = TaggableManager ()
cats = models.ManyToManyField(Category)
def __unicode__ (self):
return self.title
views.py
from django.shortcuts import render
from django.template.loader import get_template
from django.template import Context
from django.http import HttpResponse
from blog.models import Category
render(request, 'index.html', args)
def cats(request):
t = get_template('category.html')
for i in Category.object.get :
html = t.render(Context({'cat': i}))
return HttpResponse(html)
urls.py
from django.conf.urls import include, url, patterns
from django.views.generic import ListView, DetailView
from blog.models import Post, Category
urlpatterns = patterns('blog.views',
url(r'^$',ListView.as_view(
queryset = Post.objects.all().order_by("-date")[:2],
template_name="index.html")),
url(r'^(?P<pk>\d+)$',DetailView.as_view(
model = Post,
template_name="post.html")),
url(r'^(?P<pk>\d+)$','cats'),
)
模板“post.html”的一部分
#some html code here
{% include "category.html" %}
#another some html code here
这是我的category.html
<li><a href="#">{{cat}}</a></li>
谢谢。
答案 0 :(得分:2)
您编写代码的方式并不完全正确。视图适用于后端代码,urls.py仅适用于不用于编写查询的URL规范。
views.py
from blog.models import Category
from blog.models import Post
def cats(request):
queryset = Post.objects.all().order_by("-date")[:2]
return render_to_response('category.html',{'queryset': queryset},
context_instance=RequestContext(request))
在urls.py中添加此内容
url(r'^cats', 'blog.views.cats', name='cats')
在category.html
中,您可以访问从views.py传递的对象的任何字段(此处为queryset
)
<li><a href="#">{{querset.title}}</a></li>