Issue
[hi i am new to django and i am facing a problem when using primary keys.project name is blog project and app is blog this is my code.] this is the screenshot of the error when i click on a heading:1 please help me
#blog/urls.py
from django.urls import path
from .views import BlogListView,BlogDetailView
urlpatterns = [
path("post/<int:pk>/",BlogDetailView.as_view(),name = "post_detail"),
path('', BlogListView.as_view(), name = "home"),
]
#blog/templates/home.html
{% extends 'base.html' %}
<style>
.post-entry{
color:antiquewhite;
}
</style>
{% block content %}
{% for post in object_list %}
<div class = "post-entry">
<h2><a href = "{% url 'post_detail/' post.pk % }">{{post.title}}</a></h2>
<p>{{post.body}}</p>
</div>
{% endfor %}
{% endblock content %}
#views.py
from django.shortcuts import render
from django.views.generic import ListView,DetailView
from .models import Post
# Create your views here.
class BlogListView(ListView):
model = Post
template_name = "home.html"
class BlogDetailView(DetailView):
model = Post
template_name = "post_detail.html"
Solution
A Solution to try
I agree with gyspark's comment, but I also think post.pk
needs to be changed to post.id
. For example:
blog/templates/home.html
{% extends 'base.html' %}
<style>
.post-entry{
color:antiquewhite;
}
</style>
{% block content %}
{% for post in object_list %}
<div class = "post-entry">
<h2><a href="{% url "post_detail" post.id %}">{{ post.title }}</a></h2>
<p>{{post.body}}</p>
</div>
{% endfor %}
{% endblock content %}
blog/urls.py
from django.urls import path
from .views import BlogListView, BlogDetailView
urlpatterns = [
path('', BlogListView.as_view(), name="home"),
path("post/<int:pk>/", BlogDetailView.as_view(), name="post_detail"),
]
But also, are you importing blog.urls into the main app's urls.py file? Or is the main app called "blog"?
Other tips
Another thing that could be useful is to add a style block to base.html:
<!-- The rest of your code -->
<style>
{% block style %}
{% endblock %}
</style>
</head>
<!-- the rest of your code -->
and then in your templates, like home.html, you would update it like so:
{% extends 'base.html' %}
{% block style %}
.post-entry{
color:antiquewhite;
}
{% endblock %}
{% block content %}
{% for post in object_list %}
<div class = "post-entry">
<h2><a href="{% url "post_detail" post.id % }">{{ post.title }}</a></h2>
<p>{{post.body}}</p>
</div>
{% endfor %}
{% endblock content %}
Answered By - Jordan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.