'def get_absolute_urls(self): not working ,Django
when I click the post title it is supposed to go to the post detail(detail.html) but it's not working, how do i fix this?
Here is Model.py class Post(models.Model): .......
def get_absolute_urls(self):
return reverse('blog:post_detail',
args=[self.publish.year,
self.publish.month,
self.publish.day, self.slug])
Urls.py
urlpatterns= [
path('',views.post_list,name='post_list'),
path('<int:year>/<int:month>/<int:day>/<slug:post>/',views.post_detail,name='post_detail'),
]
Views.py
def post_detail(request,year,month,day,post):
post= get_object_or_404(Post,slug=post,status='published',publish_year= year,publish_month= month, publish_day= day)
return render(request,'blog/detail.html',{'post':post})
list.html
{% extends "blog/base.html" %}
{% block title %} My Blog {% endblock title %}
{% block content %}
<h1>My Blog</h1>
<p>this is working in list.html</p>
{% for post in posts %}
<h2>
<a href="{{ post.get_absolute_url }}">
{{ post.title }}
</a>
</h2>
<p class="date">
Published{{ post.publish }} by {{ post.author }}
</p>
{{ post.body| truncatewords:30|linebreaks }}
{% endfor %}
{% endblock content %}
detail.html
{% extends "blog/base.html" %}
{% block content %}
<h1>{{ post.title }}</h1>
<p class="date">
Published {{ post.publish }} by {{ post.author }}
</p>
{{ post.body|linebreaks }}
{% endblock content %}
Solution 1:[1]
You need to use {% url 'get_absolute_urls' %}
or
change your function name above your model get_absolute_url instead of get_absolute_urls
Solution:
in models.py
def get_absolute_url(self): # removed the letter s
return reverse('blog:post_detail',
args=[self.publish.year,
self.publish.month,
self.publish.day, self.slug])
in .html
{% extends "blog/base.html" %}
{% block title %} My Blog {% endblock title %}
{% block content %}
<h1>My Blog</h1>
<p>this is working in list.html</p>
{% for post in posts %}
<h2>
<a href="{{ post.get_absolute_url }}">
{{ post.title }}
</a>
</h2>
<p class="date">
Published{{ post.publish }} by {{ post.author }}
</p>
{{ post.body| truncatewords:30|linebreaks }}
{% endfor %}
{% endblock content %}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | enes islam |
