Question

Building a blog in Django and I suspect something is wrong with matching my main urls.py

from django.conf import settings
from django.conf.urls import patterns, include, url

urlpatterns = patterns('',
    url(r'$', 'posts.views.home'),
    url(r'^(?P<slug>[\w-]+)/$', 'posts.views.single'),
)

Here's my views.py

from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response, RequestContext, Http404, get_object_or_404

from .models import Post

def home(request):
    posts = Post.objects.filter(private=False)
    return render_to_response('all.html', locals(), context_instance=RequestContext(request))

def single(request, slug):
    post = Post.objects.filter(slug=slug)
    return render_to_response('single.html', locals(), context_instance=RequestContext(request))

The function-based view home works perfectly and returns all non-private posts. However, the single view alters the URL to make the correct slug (ie: 127.0.0.1/this-correct-slug) but just goes to the top of the page and does nothing to filter the content (shows a 200 GET request in terminal). Using post = get_object_or_404(Post, slug=slug) yields same result.

I'm unsure of the post = Post.objects.filter(slug=slug) part but I also know it's not getting that far - trying to add print statements to see if the function is being called shows nothing.

I'm also a little unsure of the argument locals(). I've been using it but, frankly, only because I'm still not sure how to use the data dictionary.

Assume that the templates all.html and single.html are correct.

Thanks!

Was it helpful?

Solution

The problem is that your first regex is not rooted. It matches '$' which basically means "any string that ends" - which is everything. So all URLs end up being matched by that pattern.

It should be ^$, ie the empty string.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top