Python 从URL获取ID并从数据库中选择它
我有Python 从URL获取ID并从数据库中选择它,python,django,view,Python,Django,View,我有帖子。在索引页面中,我显示了所有这些内容,按创建的顺序排列,如下所示: class IndexView(TemplateView): template_name = 'blog/index.html' def get(self, request): return render (request, self.template_name, { 'posts': Post.objects.order_by('-created_at') }) 我已
帖子
。在索引页面中,我显示了所有这些内容,按创建的顺序排列,如下所示:
class IndexView(TemplateView):
template_name = 'blog/index.html'
def get(self, request):
return render (request, self.template_name, {
'posts': Post.objects.order_by('-created_at')
})
我已经创建了一个视图,我打算重定向到另一个页面,显示整个帖子。这是url.py:
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name = 'index'),
url(r'^categories/$', views.CategoriesView.as_view(), name = 'categories'),
url(r'^post/(?P<id>[0-9]+)/$', views.Post.as_view(), name = 'post')
]
但是我得到了一个错误:
属性错误在/
类型对象“Post”没有属性“objects”
不要同时命名视图和模型!例如,将其称为PostView
,问题将得到解决:
class PostView(TemplateView):
...
及
然后直接使用id
变量。太好了,错误已经改变了。现在,它说get()得到了一个意外的关键字参数“id”
。可能只是从URL检索参数的方法。@GabrielMFernandes是的,这是一个无关的错误,但请查看我的更新答案。错误已经消失,现在我只需要弄清楚如何显示帖子,它没有显示。谢谢你,原因是愚蠢的。我将块
名称与base.html
放在不同的位置。您应该为此使用DetailView。
class PostView(TemplateView):
...
url(r'^post/(?P<id>[0-9]+)/$', views.PostView.as_view(), name = 'post')
def get(self, request, id):