I have some background with python, and I’ve been trying to do a few Django tutorials, because while I get the general idea, I’m still a beginner so I thought it good practice to just follow along a few examples.
I’m currently working on the “Django by example” tutorial of how to build a simple blog app (here’s a link: http://lightbird.net/dbe/blog.html), and I’ve reached the part where I’m working on the page for each post.
he’s doing a very weird thing there with the redirecting links so I thought it’d be better to do what the Django documentation does with it’s polls app. And here’s the thing – it doesn’t work at all. And not only that, I don’t get an error so I can’t tell what’s wrong, and what really happens makes absolutely zero sense to me.
so this is my urls.py code:
urlpatterns = patterns('',
url(r'^blog/', 'blog.views.main'),
url(r'^blog/(?P<post_id>\d+)/$', 'blog.views.post'),
)
this is my views.py code:
def main(request):
"""Main listing."""
posts = Post.objects.all().order_by("-created")
paginator = Paginator(posts, 2)
try: page = int(request.GET.get("page", '1'))
except ValueError: page = 1
try:
posts = paginator.page(page)
except (InvalidPage, EmptyPage):
posts = paginator.page(paginator.num_pages)
return render_to_response("list.html", dict(posts=posts, user=request.user))
def post(request, post_id):
post = Post.objects.get(pk=post_id)
d = dict(post=post, user=request.user)
return render_to_response("post.html", d)
and this is (part of my) html code:
{% for post in posts.object_list %}
<div class="title">
<a href="/blog/{{ post.id }}/">{{ post.title }}</a></div>
<ul>
<div class="time">{{ post.created }}</div>
<div class="body">{{ post.body|linebreaks }}</div>
</ul>
{% endfor %}
so my home page looks fine and its development url is 127.0.0.1:8000/blog
now when I click on a post title (say post number 3) it goes to 127.0.0.1:8000/blog/3, like it should.
But instead of getting the new “post.html” template, it just stays on the damn homepage. trying to change the url and find it directly doesn’t work either.
It’s as if the url patterns looked and found the first option, said “yeah good enough” and didn’t bother to run the others. And the freaky thing is, If I change the post view url in urls.py and get rid of the ‘blog’ part, like this:
url(r'^(?P<post_id>\d+)/$', 'blog.views.post')
it freaking works. but I want to keep the ‘blog’ part in my url, and I don’t get what I’m doing wrong anyway, so even If I’ll just ‘go with whatever’ works i still want to try and understand what’s going on here.
I think you should add a
$to the end of the first url:or you could place the second url before the first url. Django is looking for a match from top to down and will select the first match.