因此,我正在开发一些Django,但对它来说是新的。我有这段代码:
from django.shortcuts import render, render_to_response, get_object_or_404
from .models import Article
from django.views.generic import TemplateView
def view_post(request, slug):
return render_to_response('news/article.html', {'post': get_object_or_404(Article, slug=slug)})
class ArticleView(TemplateView):
template_name = "news/article.html"
def get(self, request):
article = Article.objects.all()
return render(request, self.template_name ,{'article': article })
如何将其写入一个视图,以便可以在urls.py中使用它?
现在这是我的urls.py:
from django.conf.urls import url, include
from .views import view_post
urlpatterns = [
url(r'^blog/view/(?P<slug>[^\.]+)', view_post , name='view_blog_post'),
]
如何将它们添加在一起?因为我也希望变量在模板中可用。
答案 0 :(得分:1)
我想这就是你想要的。
class ArticleView(DetailView):
query_pk_and_slug = 'slug'
template_name = 'news/article.html'
context_object_name = 'post'
model = Article
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['article'] = Article.objects.all()
return context