Reputation: 115
I'm learning Django framework and I have in the extend templates part, I'm trying to add a new template when I click in the title of the post in my blog to redirect to an page with the post details (date/author/etc),so I create a new view in views.py and a new url to in urls.py,But when I adc the path of the url in the 'href' desirable of the .html file ,as you will see, I receive the follow error when I reload the page:
NoReverseMatch at /
Reverse for 'blog.views.post_detail' with arguments '()' and keyword arguments '{'pk': 2}' not found. 0 pattern(s) tried: []
And
Error during template rendering
In template /home/douglas/Documentos/Django/my-first-blog/blog/templates/blog/post_list.html, error at line 9
So, when I erase the href to back the default value all works well...I am almost sure that something is wrong in the href line but I will post all template related files for you to check, if you need to check anything else let me know:
firs the html file: post_list.html
{% extends 'blog/base.html' %}
{% block content %}
{% for post in posts %}
<div class="post">
<div class="date">
{{ post.published_date }}
</div>
<h1><a href="{% url 'blog.views.post_detail' pk=post.pk %}">{{ post.title }}</a></h1>
<p>{{ post.text|linebreaksbr }}</p>
</div>
{% endfor %}
{% endblock content %}
urls.py:
from django.conf.urls import url
from . import views
from .models import Post
urlpatterns = [
url(r'^$', views.post_list),
url(r'^post/(?P<pk>[0-9]+)/$', views.post_detail),
]
views.py
from django.shortcuts import render
from django.shortcuts import render, get_object_or_404
from .models import Post
from django.utils import timezone
def post_list(request):
#posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
posts = Post.objects.all()
return render(request, 'blog/post_list.html', {'posts': posts})
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
return render(request, 'blog/post_detail.html', {'post': post})
Well guys, I think is that, I hope I have not forgotten any details about my question... Thank you in advance,any help is welcome!!
Upvotes: 0
Views: 8789
Reputation: 1633
You need to define a name for your url. It's better.
urlpatterns = [
url(r'^$', views.post_list, name='post_list'),
url(r'^post/(?P<pk>[0-9]+)/$', views.post_detail, name='post_detail'),
]
Like this, in your template, you can use this name on url
tag
<h1><a href="{% url 'post_detail' pk=post.pk %}">{{ post.title }}</a></h1>
First info (with name define for url)
The first argument is a url() name. It can be a quoted literal or any other context variable.
Second info (In your case, url without name)
If you’d like to retrieve a namespaced URL, specify the fully qualified name:
{% url 'myapp:view-name' %}
Upvotes: 2