RedTears
RedTears

Reputation: 31

Django get() model query not returning object

What I have is a basic forum. Now, what I'm trying to do is retrieve the post from a topic within the board. Everytime I hit localhost:8000/boards/1/topics/1 I get the following:

No Topic matches the given query`

I'm suspicious of the get parameters may be the culprit but I'm unsure of what parameters I must specify in order to retrieve the desired object. Below is the full flow of code, please advise.

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})

models:

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)

Best wishes, and thank you for reading!

Upvotes: 0

Views: 222

Answers (1)

nazeer
nazeer

Reputation: 11

urls.py

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/

in DB id starts from 84(in my db) not from 1. so check in your database id where from starts.

Upvotes: 1

Related Questions