社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Django

django:从表中获取数据并使用listview一起显示

Frendom • 7 年前 • 1801 次点击  

**imports**
def home(request):
    context = {'users': Person.object.all(),
               'emails': Email.object.all()
              }
    return render(request,'app/home.html',context)

class PersonListView(ListView):
    model = Person
    template_name = 'app/home.html'
    context_object_name = 'users'

{% extends "app/base.html" %}
{% block content %}
    {% for user in users %}
    Displaying user attributes works fine
    {% endfor %}

Here should be emails
{% for email in emails %}
    This displaying doesnt work
{% endfor %}
{% endbock content %}

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/34360
文章 [ 1 ]  |  最新文章 7 年前
Willem Van Onsem
Reply   •   1 楼
Willem Van Onsem    7 年前

一 ListView [Django-doc] 仅用于显示 一 一次查询集。如果需要传递额外的查询集,可以重写 get_context_data(..) method [Django-doc] :

class PersonListView(ListView):
    model = Person
    template_name = 'app/home.html'
    context_object_name = 'users'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context.update(emails=Email.objects.all())
        return context

在这里我们传递一个额外的变量 emails 到模板呈现引擎。但是请注意,此查询集不会 分页 (或者至少在不添加分页的情况下)。

我的 models.py :

注意那些是 意见 ,你需要把这些写进去 views.py 。