gpt4 book ai didi

python - “AnonymousUser”对象不可迭代 - 匿名和经过身份验证的用户访问 View

转载 作者:太空宇宙 更新时间:2023-11-03 14:47:39 24 4
gpt4 key购买 nike

我有以下网址:

主要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 时,请求正常

[2017年9月8日23:56:20]“获取/accounts/profiles/luisa@gmail.com/HTTP/1.1”200 23577

但是,我希望匿名用户或未经身份验证的用户可以访问此 View ,这些用户不会在我的应用程序中注册。当匿名用户访问 /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

最佳答案

首先创建一个LoginRequired类。

from django.contrib.auth.decorators import login_required
from django.views.generic import View
from django.utils.decorators import method_decorator


class LoginRequired(View):
"""
Redirects to login if user is anonymous
"""
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(LoginRequired, self).dispatch(*args, **kwargs)

然后然后:

class UserDetailView(LoginRequired,UserProfileDataMixin, generic.DetailView):

关于python - “AnonymousUser”对象不可迭代 - 匿名和经过身份验证的用户访问 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46126051/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com