我有以下网址:
主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时,请求为O.K
[08 / Sep / 2017 23:56:20]&#34; GET /accounts/profiles/luisa@gmail.com/ HTTP / 1.1&#34; 200 23577
但是,我希望匿名用户或未经身份验证的用户加入此视图,这些用户未在我的应用程序中注册。
当匿名用户访问/accounts/profiles/luisa@gmail.com/
网址时,我收到此消息:
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
和recommended()方法:
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
?
答案 0 :(得分:1)
首先创建一个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):