/ notify / notify /'UserNotifications'对象中的AttributeError没有属性'user'

时间:2017-10-16 00:41:54

标签: python django

我正在尝试制作通知应用。我有一个中间收集有关应该通知用户的操作的信息,并且在处理该操作的视图中,它自动在UserNotification模型中创建实例。这一切都有效。现在,如果用户的帖子被其他用户喜欢,则需要在通知页面上显示该操作。但是,我显然不希望任何一个用户能够看到在网站上创建的每个通知,而只能看到他们的帖子创建的通知。

我遇到了视图问题并根据当前用户过滤了通知。更具体地说,我收到了这个错误:

AttributeError at /notify/notify/
'UserNotifications' object has no attribute 'user'

使用追溯:

Traceback (most recent call last):
  File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner
    response = get_response(request)
  File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/views/generic/base.py", line 68, in view
    return self.dispatch(request, *args, **kwargs)
  File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/contrib/auth/mixins.py", line 56, in dispatch
    return super(LoginRequiredMixin, self).dispatch(request, *args, **kwargs)
  File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/views/generic/base.py", line 88, in dispatch
    return handler(request, *args, **kwargs)
  File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/views/generic/list.py", line 160, in get
    self.object_list = self.get_queryset()
  File "/Users/garrettlove/Desktop/evverest/notify/views.py", line 30, in get_queryset
    return UserNotification.objects.filter(user=request.user)

以下是我对此的看法:

// Bunch of imports are all here

User = get_user_model()

class UserNotifications(LoginRequiredMixin,ListView):
    login_url = 'account_login'
    model = UserNotification
    template_name = 'notify/usernotification_list.html'
    context_object_name = 'notifies'
    paginate_by = 25

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

这是我的UserNotification模型:

from django.db import models
from django.contrib.auth import get_user_model
from django.db.models.signals import post_save
from django.dispatch import receiver

User = get_user_model()

# Create your models here.
class UserNotification(models.Model):
    user = models.ForeignKey(User,related_name='user',null=True)
    post = models.ForeignKey('feed.UserPost',related_name='post')
    timestamp = models.DateTimeField(auto_now_add=True)
    notify_type = models.CharField(max_length=6)
    read = models.BooleanField(default=False)

    def __str__(self):
        return str(self.user)

1 个答案:

答案 0 :(得分:1)

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