【发布时间】:2021-11-03 17:27:03
【问题描述】:
我正在使用 Django 来显示我的帖子模型。当我尝试显示多个帖子时,它可以工作,但单个帖子对我不起作用。我不太确定为什么。 这是我所做的:
views.py
def post(request, pk):
post = Post.object.get(id=pk)
context = {'post': post}
return render(request, 'base/post.html', context)
urls.py
urlpatterns = [
path('', views.home, name="home"),
path('posts/', views.posts, name='posts'),
path('post/<str:pk>/', views.post, name='post'),]
post.html
<h3>{{post.headline}}</h3>
<h4>{{post.sub_headline}}</h4>
<p>{{post.body|linebreaks}}</p>
编辑:更多信息
后模型
class Post(models.Model):
headline = models.CharField(max_length=200)
sub_headline = models.CharField(max_length=200, null=True, blank=True)
# thumbnail =
body = models.TextField(null=True, blank=True)
created = models.DateTimeField(auto_now_add=True)
active = models.BooleanField(default=False)
featured = models.BooleanField(default=False)
tags = models.ManyToManyField(Tag, null=True)
# slug
def __str__(self):
return self.headline
post.html
{% extends 'base/main.html' %}
{% load static %}
{% block content %}
<div class="main-container">
<img src="{% static 'images/peace.png' %}">
<h3>{{post.headline}}</h3>
<h4>{{post.sub_headline}}</h4>
<p>{{post.body|linebreaks}}</p>
</div>
{% endblock content %}
base/main.html
<!Doctype html>
{% load static %}
<html>
<head>
<title>Peace Cyebukayire</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1" />
<link href="https://fonts.googleapis.com/css2?family=Russo+One&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Roboto+Mono:wght@500&family=Russo+One&display=swap" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="{% static 'css/default.css' %}">
</head>
<body>
{% include 'base/navbar.html' %}
{% block content %}
<!-- Content goes here -->
{% endblock content %}
</body>
</html>
当我设置 Debug=True 时,这是我得到的:
Traceback (most recent call last):
File "/home/peace/.local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/peace/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/peace/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/peace/Desktop/Tutorials/Django/my-portfolio/base/views.py", line 24, in post
post = Post.object.get(id=pk)
Exception Type: AttributeError at /post/1/
Exception Value: type object 'Post' has no attribute 'object'
【问题讨论】:
-
Post模型长什么样? -
你在
post.html中使用了基础模板(模板继承)吗? -
请启用DEBUG mode 以获得完整的堆栈跟踪。这将有助于确定实际错误是什么。
-
在您的
urls.py中,您编写了path('post/<str:pk>/', views.post, name='post'),id 是一个整数,但您指定了一个字符串。试试这个path('post/<int:pk>/', views.post, name='post') -
错字:
Post.object.get(id = pk)这里object应该是objects,即应该是Post.objects.get(id=pk)