這可能是一個愚蠢的問題,但它真的很晚,我的大腦在我的第6次咖啡後死亡。Django - 重複使用不同模板中的視圖
我正在構建(或試圖)一個簡單的博客應用程序,該應用程序會在主頁上顯示文章索引 - 又名。最近的文章 - 和主博客頁面上。要做到這一點我已經成功地塗抹了以下觀點:
def index(request):
'''Article index'''
archive_dates = Article.objects.datetimes('date_publish','month', order='DESC')
categories = Category.objects.all()
page = request.GET.get('page')
article_queryset = Article.objects.all()
paginator = Paginator(article_queryset, 5)
try:
articles = paginator.page(page)
except PageNotAnInteger:
#If page requested is not an integer, return first page.
articles = paginator.page(1)
except EmptyPage:
#If page requested is out of range, deliver last page of results.
articles = paginator.page(paginator.num_pages)
return render(
request,
'blog/article/index.html',
{
'articles': articles,
'archive_dates': archive_dates,
'categories': categories
}
)
但是兩個不同的URL中顯示的指標,我複製的代碼只改變幾個變量,即。名稱和模板來呈現。
我該怎麼做才能在這兩個網址中呈現此視圖,但不會在我的views.py中複製它?
我是否認爲我必須有3個視圖,主要的一個和兩個子視圖才能從主視圖導入代碼?
或者我應該使用自定義模板標籤嗎?
編輯
按照要求,將urls.py
from django.conf.urls import *
from django.contrib import admin
from settings import MEDIA_ROOT
from django.views.generic import TemplateView
from blog.views import *
admin.autodiscover()
urlpatterns = patterns('',
#Blog URLs
url('^$', home_index, name='blog-preview'),
url('^blog/archive/(?P<year>[\d]+)/(?P<month>[\d]+)/$', date_archive, name='blog-date-archive'),
url('^blog/archive/(?P<slug>[-\w]+)/$', category_archive, name='blog-category-archive'),
url('^blog/categories/', category_list, name='blog-category-list'),
url('^blog/(?P<slug>[-\w]+)/$', single, name='blog-article-single'),
url('^blog/$', index, name='blog-article-index'),
url(r'^contact/', include("contact_form.urls", namespace="contact_form")),
url(r'^admin/', include(admin.site.urls)),
)
你應該能夠只添加一行到你的urls.py.你可以編輯你的文章,包括你的嗎? – schillingt
添加我的urls.py,感謝您的幫助! – Hevlastka