I'm trying to make a simple page with Django where posts are being displayed using primary keys. However, the DetailView page with my posts can't be displayed.
This is my model:
class Post(models.Model):
author = models.CharField(max_length=100)
title = models.CharField(max_length=100)
posted_date = timezone.now()
text = models.TextField()
def get_absolute_url(self):
return reverse("postdetail", kwargs={"pk": self.pk})
def __str__(self):
return self.title
and here is my url pattern list:
urlpatterns = [
url(r'^posts/(?P<pk>\d )$', views.PostDetail.as_view(), name="postdetail"),
url(r'^$', views.index, name="index"),
url(r'^thanks/$', views.Thanks.as_view(), name="thanks"),
url(r'^postlist/$', views.PostList.as_view(), name="postlist"),
]
The template is in my templates folder under the name "post_detail.html".
Here is the DetailView:
class PostDetail(DetailView):
context_object_name = 'post_details'
model = Post
I can't see where I might have a mistake. I have a ListView that shows my posts including the primary keys. But when I try to open the URL http://127.0.0.1:8000/posts/1/
I get:
`Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/posts/1/
Using the URLconf defined in myproj.urls, Django tried these URL patterns, in this order:
admin/
^posts/(?P<pk>\d )$ [name='postdetail']
^$ [name='index']
^thanks/$ [name='thanks']
^postlist/$ [name='postlist']
The current path, posts/1/, didn’t match any of these.
Do you have a clue why the URL cannot be found? Thank you very much.`
CodePudding user response:
from django.urls import path
urlpatterns = [
path('', views.index, name = "index"),
path('posts/<int:pk>', views.PostDetail.as_view(), name = "postdetail"),
path('postlist/', views.PostList.as_view(), name="postlist"),
path('thanks', views.Thanks.as_view(), name = "thanks"),
]
NB: url() been deprecated since version 3.1 and removed in 4.0
CodePudding user response:
You are trying to access : http://127.0.0.1:8000/posts/1/ when you define the following http://127.0.0.1:8000/posts/1 without the backlash.
Try : http://127.0.0.1:8000/posts/1
CodePudding user response:
First Things Is Your Views. You can send your database data with return it to the HTML.
views.py
def post(request,id):
post = Post.objects.get(id=id)
return render(request,'blog/index.html',{'post':post})
and before sending data into the HTML you should get the post id in your urls.py
urls.py
path('post/<int:id>', views.post, name='post.blog')
then in your HTML you can handle that data comes from your views.py
index.html
<div >{{ post.body|safe }}</div>