Fabian
Fabian

Reputation: 11

How to access pk in views (Django)

I'm writing a small chat programm in Django but have problems getting any further.

Here's the code:

models.py

from django.db import models
from datetime import datetime
from django.utils import timezone

class Chat(models.Model):
    chatname = models.CharField(max_length=100)
    description = models.TextField()
    created_at = models.DateTimeField(default=datetime.now, blank=True)
    def __str__(self):
        return self.chatname

class Comment(models.Model):
    chat = models.ForeignKey(Chat, on_delete=models.CASCADE)
    commenter = models.CharField(max_length=30)
    comment = models.TextField()
    created_at = models.DateTimeField(default=datetime.now, blank=True)
    def __str__(self):
        return self.comment

urls.py

from django.conf.urls import url
from . import views
from django.views.generic import ListView
from chat.views import CommentList

app_name = 'chats'
urlpatterns = [
    url(r'^$', views.index, name="index"),
    url(r'^comments/(?P<pk>[0-9]+)/$', views.CommentList.as_view(), name='comments'),
]

views.py

from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib.auth import authenticate, login

from django.views import generic
from .models import Chat, Comment

def index(request):
    username = None 
    if request.user.is_authenticated():
        username = request.user.username

    chats = Chat.objects.all()[:10]

    context = {
        'chats':chats
    }
    return render(request, 'chat/index.html', context)

class CommentList(generic.ListView):
    queryset = Comment.objects.filter(chat_id=1)
    context_object_name = 'comments'

My comment_list.html

{% extends "chat/base.html" %}

{% block content %}
    <a href="/chat/">Go back</a>
    <h3>Comments</h3>
    <h2>{{chat.id}}</h2>
    <ul>
        {% for comment in comments %}
            <li>{{ comment.commenter }}: {{ comment.comment }}</li>
        {% endfor %}
    </ul>
{% endblock %}

My database structure contains these two models: Chat and Comment. Each chat(room) is supposed to have its own comments. I used 'models.ForeignKey' to be able to filter the comments for each chat(room). In my index.html I list all the chats and each of these has a hyperlink to the /comments/ section.

In my views.py I have this line: 'queryset = Comment.objects.filter(chat_id=1)' Chat_id is the column in the comments sql table and as it is now it will only show comments that belong to the chat with pk=1. How can I auto access the chat for the different urls /comments/1/ /comments/2/ and so on..?

Hope the explanation is clear. Sorry beginner here, I can try to explain further if it doesn't make a lot of sense.

Best, Fabian

Upvotes: 1

Views: 6123

Answers (2)

Daniel Roseman
Daniel Roseman

Reputation: 599698

You should define the get_queryset method instead of the standalone queryset attribute.

def get_queryset(self, *args, **kwargs):
    return Comment.objects.filter(chat_id=self.kwargs['pk'])

Upvotes: 2

Make Tips
Make Tips

Reputation: 300

Instead of CommentList you can use plain view:

def comments_index(request, chatid):
    return render(request, 'xxx/comment_list.html', {
        'comments': Comment.objects.filter(chat_id=chatid)
    })

And in urls:

url(r'^comments/(?P<chatid>[0-9]+)/$', views.comments_index, name='comments'),

Upvotes: 0

Related Questions