显示由经过身份验证的用户使用模型管理器创建

时间:2016-05-12 20:03:11

标签: python django django-models django-views

我需要能够在模板上显示经过身份验证的用户进行的所有预订。我正在使用模型管理器来覆盖get_queryset方法以返回我需要的属性。

然后在将其传递给模板之前将其用作视图中的查询集。当我跟着documentation on managers时,我不知道自己可能做错了什么。

models.py

class ReservationManager(models.Manager):

  use_for_related_fields = True

  def get_queryset(self):
    return super(ReservationManager, self).get_queryset().filter(customer_name=User)

class Reservation(models.Model):

"""
this class will contain all information that concerns a car reservation
"""

customer_name = models.ForeignKey(User)
vehicle = models.ForeignKey(Car)
pickup_location = models.ForeignKey(Location)
drop_location = models.ForeignKey(Location, related_name='drop_location')
pickup_time = models.DateTimeField(blank=False)
drop_time = models.DateTimeField(blank=False)
reserved_on = models.DateTimeField(auto_now_add=True)
edited_on = models.DateTimeField(auto_now=True)
completed = models.BooleanField(default=False)

reservations = ReservationManager()

views.py

class ReservationsList( ListView):

model = Reservation
queryset = Reservation.reservations.all()
template_name = 'reservation_list.html'
context_object_name = 'reservations'

`

模板

模板应显示经过身份验证的用户进行的所有预订。



<tbody>

{% if user.is_authenticated  %}
            {% for reservation in reservations %}


<tr class="row1"><td class="action-checkbox"><input class="action-select" name="_selected_action" type="checkbox" value="2" /></td>
    <th class="field-code white-text grey center">{{reservation.code}}</th>
    <td class="field-customer_name nowrap">{{reservation.customer_name}}</td>
   
    <td class="field-vehicle nowrap">{{reservation.vehicle}}</td>
    <td class="field-pickup_location nowrap white-text grey center">{{reservation.pickup_location}}</td>
    <td class="field-drop_location nowrap">{{reservation.drop_location}}</td>
    <td class="field-pickup_time nowrap white-text grey center">{{reservation.pickup_time}}</td>
    <td class="field-drop_time nowrap ">{{reservation.drop_time}}</td>
    <td class="field-reserved_on white-text grey center nowrap">{{reservation.reserved_on}}</td>
</tr>


{% endfor %}

{% else %}
nothing
{% endif %}
</tbody>
&#13;
&#13;
&#13;

我做错了什么?

1 个答案:

答案 0 :(得分:1)

您正在尝试选择请求的属性(即当前用户),但管理员的存在与请求无关。

您是否尝试过使用内置类视图?在那里,等效的get_queryset方法位于具有self.request的类实例上,因此self.request.user

略微重写Django文档示例(https://docs.djangoproject.com/en/1.9/topics/class-based-views/generic-display/):

class ReservationList(ListView):

    template_name = 'reservation_list.html'

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

我刚刚复制粘贴然后攻击了这个例子,但希望它足够接近你的工作进展。