我所拥有的是一个基本论坛。现在,我尝试做的是从董事会内的主题中检索帖子。每当我点击localhost:8000/boards/1/topics/1
时,我都会得到以下信息:
没有主题与给定的查询匹配
我怀疑get参数可能是罪魁祸首,但我不确定我必须指定哪些参数才能检索所需的对象。以下是完整的代码流程,请指教。
urls.py:
path('boards/<board_id>/topics/<topic_id>', views.topic_posts, name = 'topic_posts')
views.py:
def topic_posts(request, board_id, topic_id):
topic = get_object_or_404(Topic, board_id = board_id, topic_id = topic_id)
return render(request, 'topic_posts.html', {'topic': topic})
模型:
from django.db import models
from django.contrib.auth.models import User
from datetime import datetime
# Create your models here.
class Board(models.Model):
'''
id auto generated
'''
name = models.CharField(max_length = 30, unique = True)
description = models.CharField(max_length = 100)
def __str__(self):
return self.name
class Topic(models.Model):
subject = models.CharField(max_length = 255, default = '')
last_updated = models.DateTimeField(default = datetime.now(), blank = True)
board = models.ForeignKey(Board, related_name = 'topics', on_delete = models.CASCADE)
starter = models.ForeignKey(User, related_name = 'topics', on_delete = models.CASCADE)
class Post(models.Model):
message = models.TextField(max_length = 4000, default = '')
topic = models.ForeignKey(Topic, related_name = 'posts', on_delete = models.CASCADE)
created_at = models.DateTimeField(default = datetime.now(), blank = True)
updated_at = models.DateTimeField(null = True, default = datetime.now(), blank = True)
created_by = models.ForeignKey(User, related_name = 'posts', on_delete = models.CASCADE)
updated_by = models.ForeignKey(User, null = True, related_name = '+', on_delete = models.CASCADE)
祝福,谢谢您的阅读!
答案 0 :(得分:1)
url(r'^boards/(?P<pk>\d+)/topics/(?P<topic_pk>\d+)/$', views.topic_posts, name='topic_posts'),
http://127.0.0.1:8000/boards/1/topics/84/
id
中的从84(在我的数据库中)开始,而不是1。 因此,请从头开始检查数据库ID。