我是Django的新手,我第一次使用基于类的视图。我想使用通用ListView来显示"表"由用户拥有。到目前为止,我已经让它显示数据库中的所有表。但我只希望它为登录用户显示表格。
这就是我的观点:
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
这就是我的模型:
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')
我承认,我不确定这条线在做什么:
context = super(TableListView, self).get_context_data(**kwargs)
但我怀疑这是我需要改变的?或者我是否必须进入我的模板并在那里做一个if语句?可能是这样的:{% if request.user == vtable.user %}
?
编辑:这是我的模板:
{% 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 %}
答案 0 :(得分:4)
也许,重写get_queryset():
def get_queryset(self):
return self.model.objects.filter(user=self.request.user)