Search code examples
pythonhtmldjangoweburl-routing

django a href tag not routing properly


How can properly route pages using a href tag in templates in django? my urls.py

urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', views.home_page, name='home_page'),
url(r'^post/', include('blog.urls')),
url(r'^post/(?P<slug>[-\w]+)/$', views.single_post, name='post'),
url(r'^about/', views.about_page, name='about_page'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

views.py

 def home_page(request):
posts = Post.objects.filter(publish_date__lte=timezone.now()).order_by('publish_date').reverse()
paginator = Paginator(posts, 6)
page = request.GET.get('page')
try:
    posts = paginator.page(page)
except PageNotAnInteger:
    posts = paginator.page(1)
except EmptyPage:
    posts = paginator.page(paginator.num_pages)

return render_to_response('home.html', locals(), context_instance=RequestContext(request))

 def single_post(request, slug):
     post = get_object_or_404(Post, slug=slug)
     return render_to_response('post/post_detail.html', locals(), context_instance=RequestContext(request))

def about_page(request):
     return render_to_response(
    'about.html'
)

base.html

 <div class="head-nav">
                <span class="menu"> </span>
                    <ul class="cl-effect-1">
                        <li class="active"><a href="/">Home</a></li>
                        <li><a href="about/">About</a></li>
                        <li><a href="gaming/">Gaming</a></li>
                        <li><a href="tech/">Tech</a></li>
                        <li><a href="404.html">Shortcodes</a></li>

                        <li><a href="contact.html">Contact</a></li>
                                    <div class="clearfix"></div>
                    </ul>
            </div>

The problem is that when I'm at url http://127.0.0.1:8000/post/post_title and then I want to go to the about page, then when I hit the link from the navbar it goes to http://127.0.0.1:8000/post/post_title/about, this gives me a 404 but the about page is at url http://127.0.0.1:8000/about.

It may be a problem with href or urls so correct me.


Solution

  • Replace your code with the line below.

    <li><a href="{% url 'about_page' %}">About</a></li>
    

    You have defined named url's in your urls.py, so make good use of it. For more information read this article this will help you making the best use of named urls. Django URL's Dispatcher