我有以下网址:
主要urls.py
:
url(r'^accounts/profiles/', include('accounts.urls', namespace = 'accounts')),
这accounts/urls.py
url(r"^(?P<email>[\w.@+-]+)/$", views.UserDetailView.as_view(), name='detail'),
我创建了 UserDetailView 来查看用户的数据
User = get_user_model()
class UserDetailView(UserProfileDataMixin, generic.DetailView):
template_name = 'accounts/user_detail.html'
queryset = User.objects.all()
def get_object(self):
return get_object_or_404(
User,
email__iexact=self.kwargs.get("email")
)
def get_context_data(self, *args, **kwargs):
context = super(UserDetailView, self).get_context_data(*args, **kwargs)
user = self.request.user
following = UserProfile.objects.is_following(self.request.user, self.get_object())
context['following'] = following
context['recommended'] = UserProfile.objects.recommended(self.request.user)
return context
当我在执行请求的用户登录时访问/accounts/profiles/luisa@gmail.com/
URL 时,请求正常
[08/Sep/2017 23:56:20]“GET /accounts/profiles/luisa@gmail.com/HTTP/1.1”200 23577
但是,我希望匿名用户或未经身份验证的用户可以访问此视图,这些用户未在我的应用程序中注册。当匿名用户访问 /accounts/profiles/luisa@gmail.com/
url 时,我收到以下消息:
TypeError: 'AnonymousUser' object is not iterable
[09/Sep/2017 00:00:50] "GET /accounts/profiles/luisa@gmail.com/ HTTP/1.1" 500 151513
我的自定义管理器方法is_following()
是:
def is_following(self, user, followed_by_user):
user_profile, created = UserProfile.objects.get_or_create(user=user)
if created:
return False
if followed_by_user in user_profile.following.all():
return True
return False
和推荐的()方法:
def recommended(self, user, limit_to=10):
print(user)
profile = user.profile
# my profile
following = profile.following.all()
# profile of the people that I follow
following = profile.get_following()
# TO avoid recommend myself
# Exclude the users recommendations which I already follow
qs = self.get_queryset().exclude(user__in=following).exclude(id=profile.id).order_by("?")[:limit_to]
return qs
如何允许UserDetailView
匿名用户访问我的?