Been stuck on this for ages. Currently learning Django and done some bits on other sites. Starting building my own site and getting stuck with the views / URLS.
I’ve built an app called ‘blog’ where i want to display news posts.
So far I have loaded all the blog items onto a template which is working fine. However when i try and click ‘read more’ the page does not go through to the posts own page. However where it displays the page it’s going to load tells you it’s going to load the correct you URL. So it’s pulling the slug through how I want it but when you click the button it just stays on the same page.
I manage to get it working perfect if i get the blog posts to load on the home page. However I want them to load on /blog/ as obviously I don’t want it to be my homepage.
I’ve read all the documentation and it’s slightly different to the tutorial i’ve been following. Anyhow here is some of my code, really hope someone can help me!
from django.http import HttpResponse
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from blog.models import Blog, NewsPost
def blog_index(request):
blogs = Blog.objects.filter(active=True)
return render_to_response('blog/index.html', {
'blogs':blogs,
}, context_instance=RequestContext(request))
def blog(request, slug):
blog = get_object_or_404(Blog, active=True, slug=slug)
return render_to_response('blog/blog_post.html', {
'blogs': blogs
}, context_instance=RequestContext(request))
url(r'blog/', 'blog.views.blog_index', name="blog_index"),
url(r'blog/(?P<slug>[-\w]+)/$', 'blog.views.blog', name="blog"),
//MODEL
class Blog(TimeStampedActivate):
title = models.CharField(max_length=255, help_text="Can be anything up to 255 character")
slug = models.SlugField()
description = models.TextField(blank=True, help_text="Give a short description of the news post")
content = models.TextField(blank=True, help_text="This is the main content for the news post")
user = models.ForeignKey(User, related_name="blog")
def __unicode__(self):
return self.title
@models.permalink
def get_absolute_url(self):
return ('blog', (), {
'slug': self.slug
})
Thanks,
Josh
Your url
r'blog/'doesn’t have a $ at the end, so I think django will always match this entry rather than ther'blog/(?P<slug>[-\w]+)/$'entry. I’d try reversing the order and see if that helps:I’ve had that problem before and spent many hours trying to figure it out.