Django按用户过滤ListView

时间:2016-03-17 05:29:31

标签: django django-models django-forms django-templates django-views

我的视图中有@required_login装饰器,但我需要ListView只显示与当前登录用户相关的对象。

我在尝试:

class NdaList(ListView):
    form_class = NonDisclosureForm
    template_name = 'nda/nda_list.html'

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

但它给了我一个Cannot query "charles": Must be "Profile" instance.

我的模特:

class Profile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="profile", verbose_name="user")
...

class NonDisclosure(Timestamp):
    user = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name="nda", verbose_name="user")
...

我尽我所能,但由于我对Django的了解仍然有限,我的想法不足。谢谢你的时间。

1 个答案:

答案 0 :(得分:2)

快速解决方案:

user

附加:

我认为最好更改NonDisclosure中的Profile字段名称,因为实际上该字段指向的是User个实例,而不是class NonDisclosure(Timestamp): profile = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name="nda", verbose_name="user")

return NonDisclosure.objects.filter(profile__user=self.request.user)

并且您的查询语句也会更改为:

<button id="createDropdown" class="btn-create" tabindex="7">
    <ul id="createDropdownUl" class="dropdown-create" style="display: block">
    <li tabindex="8">
    <button>MASTER SERVICE BLOCK</button>
    </li>
    <li tabindex="9">
    <button id="MasterS">MASTER SCHEDULE</button>
    </li>
    </ul>
    </div>