【问题标题】:Get All Users in django在 django 中获取所有用户
【发布时间】:2020-07-15 22:09:00
【问题描述】:

我想在我的模板中显示所有用户,但我收到了这个错误。 /list/ 处的类型错误 init() 接受 1 个位置参数,但给出了 2 个

views.py

class UsersView(TemplateView):
template_name = 'list.html'
 context = super(UsersView, self).get_context_data(**kwargs)
 context['object_list'] = User.objects.values()

list.html

           <tbody>            
           <tr>
              
           <th scope="col">Id</th>
           <th scope="col">username</th>
            <th scope="col">email Adress</th>
            <th scope="col">First Name </th>
            <th scope="col">Last Name</th>
                
               </tr>
        </thead>
        <tbody>
                {% for user in users %}
                <tr> 
            <td>{{ user.id }} </td>
            <td>{{ user.username}}</td>
            <td>{{ user.email }}</td>
            <td>{{ user.first_name}}</td>
            <td>{{ user.last_name }}</td>

如何拉动所有用户?

【问题讨论】:

    标签: django django-views


    【解决方案1】:

    一个类中没有selfcontext 等。你应该覆盖.get_context_data(…) method [Django-doc]:

    class UsersView(TemplateView):
        template_name = 'list.html'
    
        def get_context_data(self, *args, **kwargs):
            context = super(UsersView, self).get_context_data(*args, **kwargs)
            context['object_list'] = User.objects.all()
            return context

    您将模板变量命名为ojbect_list,因此您应该迭代object_list,而不是users

    {% for user in object_list %}
        <tr> 
            <td>{{ user.id }} </td>
            <td>{{ user.username}}</td>
            <td>{{ user.email }}</td>
            <td>{{ user.first_name}}</td>
            <td>{{ user.last_name }}</td>
        </tr>
    {% endfor %}

    不过,改用ListView [Django-doc] 可能更有意义:

    from django.views.generic.list import ListView
    
    class UsersView(ListView):
        template_name = 'list.html'
        model = User

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-08
      • 2017-01-27
      • 2015-02-09
      • 2015-10-08
      • 1970-01-01
      • 2022-10-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多