Reputation: 1948
It's probably a stupid question but its really late here and my brain died after my 6th coffee.
I'm building (or trying to) a simple blogging application that would display an article index on the homepage - aka. recent articles - and on the main blog page. To do so I've managed to scribble out a following view:
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
}
)
However to display the index within two different URLs I've copied the code changing only few variables, ie. name and template to render.
What could I do to render this view within both URLs yet not duplicate it in my views.py?
Am I right in thinking that I'd have to have 3 views, a main one and two sub ones that would import the code from the main one?
Or should I be using a custom template tag instead?
EDIT
As requested, adding 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)),
)
Upvotes: 0
Views: 1454
Reputation: 12037
It's very simple: map two urls in your conf to the view like this:
urlpatterns = patterns('',
url(r'first_expression', index, name='first'),
url(r'second_expression', index, name='second'),
)
Also, a little advise on your code: try to avoid wildcard imports. They are dangerous... Insead use:
from package import MyClass, my_function, my_etc
Upvotes: 2