How to make generic ListView only show user's

2020-08-07 20:28发布

问题:

I'm new to Django and I'm utilizing class-based views for the first time. I want to use the generic ListView to show a list of "tables" owned by a user. And so far I've gotten it to display ALL the tables in the database. But I only want it to show tables for the logged in user.

this is what my view looks like:

from django.shortcuts import render
from django.http import HttpResponse
from django.views import generic
from vtables.models import Vtable

class TableListView(generic.ListView):

    model = Vtable
    context_object_name = 'table_list'

    def get_context_data(self, **kwargs):
        context = super(TableListView, self).get_context_data(**kwargs)
        return context

And this is what my model looks like:

from django.db import models
from django.contrib.auth.models import User

class Vtable(models.Model):
    user = models.ForeignKey(User)
    table_name = models.CharField(max_length=200)
    added_date = models.DateTimeField('date added')

class Vdata(models.Model):
    table_id = models.ForeignKey(Vtable)
    table_pk = models.IntegerField()
    column_1 = models.CharField(max_length=200)
    column_2 = models.CharField(max_length=200)
    added_date = models.DateTimeField('date added')

I'll admit, I'm not sure what this line is doing:

context = super(TableListView, self).get_context_data(**kwargs)

But I suspect this is what I need to change? Or do I have to go into my template and do an if statement there? Maybe something like: {% if request.user == vtable.user %}?

EDIT: here is my template:

{% extends "base.html" %}
{% load staticfiles %}

{% block content %}
    {% if request.user.is_authenticated %}
        <img src="{{ request.user.profile.profile_image_url }}"/>
        <a href="/accounts/logout/" class="pull-right">Logout</a>

        {% if request.user.first_name or request.user.last_name %}
            {{ request.user.first_name }} {{ request.user.last_name }}
        {% else %}
            {{ request.user.username }}
        {% endif %}

        {% if request.user.profile.account_verified %}
            (verified)
        {% else %}
            (unverified)
        {% endif %}

        <h1>Tables</h1>
        <ul>
            {% for vtable in table_list %}
                <li>{{ vtable.user }}, {{ vtable.table_name }}</li>
            {% endfor %}
        </ul>
    {% else %}
        <a href="/accounts/login/" class="pull-right">Login</a>
    {% endif %}
{% endblock %}

回答1:

perhaps, overriding get_queryset():

def get_queryset(self):
    return self.model.objects.filter(user=self.request.user)