Reputation: 3791
I don't understand my problem here is my code:
urls.py
urlpatterns = patterns('blog.views',
...
url(r'^(?P<slug>.+)$', 'blog', name='blog'),
url(r'^membres$', 'membres', name='membres'),
)
views:
def blog(request, slug):
posts = Post.objects.filter(blog__slug=slug)
return render(request, 'blog/blog.html', locals())
def membres(request):
membres = User.objects.all()
return render(request, 'blog/membres.html', {'membres': membres})
Here is my link in my base.html template
<li><a href="{% url "membres" %}">List</a></li>
When I click the link it redirect me to the blog view and then render blog.html instead of using membres view.
I got no error in console or in my template.
All my code is in my app called 'blog'
Upvotes: 0
Views: 433
Reputation: 2548
Django uses the first pattern that matches. Your first URL regex matches any string, including /membres
, so Django never tries the second one. I suggest something like this:
urlpatterns = patterns('blog.views',
url(r'^/blog/(?P<slug>[-\w]+)/$', 'blog', name='blog'),
url(r'^membres/$', 'membres', name='membres'),
)
If you must have a catch-all pattern, it should be the last one in the list, so the other patterns have a chance to match before:
urlpatterns = patterns('blog.views',
url(r'^membres/$', 'membres', name='membres'),
# other patterns...
url(r'^(?P<slug>[-\w]+)/$', 'blog', name='blog'),
)
It's also a good habit to always include the trailing slash (Django will append it to requests by default). To match a slug, I suggest [-\w]+
, which will match any sequence of alphanumeric characters, _
and -
.
Upvotes: 3
Reputation: 15798
Django stops at the first URL pattern that matches. This means that your
blog
view -- which simply looks for one or more characters -- will interpret your mysite.com/membres
URL to be a blog post with the slug membres
.
To fix it, try swapping the order of your URL patterns:
urlpatterns = patterns('blog.views',
...
url(r'^membres$', 'membres', name='membres'),
url(r'^(?P<slug>.+)$', 'blog', name='blog'),
)
In general, you want your most general patterns at the bottom for exactly this reason.
Upvotes: 1
Reputation: 3710
It's because urlresolver takes patterns from top to bottom and 'membres' matches (?P<slug>.+)
so urlresolver returns blog
view. Put more concrete urlpatterns higher. Also I suggest using more specific characters in slug regexp, i.e. (?P<slug>[A-Za-z0-9_\-]+)
.
Upvotes: 1