gpt4 book ai didi

python - Django session 将参数从一个 View 传递到另一个 View ,但为所有用户实例设置相同的值

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

我将一个 (is_followed) 参数从一个基于类的 View FollowToggleAPIView 传递到另一个 UserDetailAPIVIew。我使用 Django session (通过阅读该平台上的其他线程)执行此操作,希望显示 user_to_toggle< 的后续状态(TrueFalse) UserSingleProfileSerializer 上的/strong> 变量。

以下是我的观点:

class UserDetailAPIVIew(generics.RetrieveAPIView):
'''
Displays a list of a user's posts
'''
serializer_class = UserSingleProfileSerializer
queryset = User.objects.all()

def get_object(self):
self.object = get_object_or_404(User,
username__iexact=self.kwargs.get('username')
)
return self.object

def get_serializer_context(self):
'''
passing the extra is_following argument to the UserDetailAPIVIew
'''
context = super(UserDetailAPIVIew, self).get_serializer_context()
is_followed = self.request.session.get('followed')
context.update({'followed': is_followed})
return context


class FollowToggleAPIView(APIView):
'''
Uses the custom model manager for user toggle follow
'''
def get(self, request, username, format=None):
user_to_toggle = get_object_or_404(User, username__iexact=username)
me = request.user
message = 'Not allowed'

if request.user.is_authenticated():
is_followed = UserProfile.objects.toggle_follow(me, user_to_toggle)
request.session['followed'] = is_followed
return Response({'followed': is_followed})
return Response({'message': message}, status=400)

toggle_follow 方法在自定义模型管理器中定义如下:

class UserProfileManager(models.Manager):

def toggle_follow(self, user, to_toggle_user):
''' follow unfollow users '''
user_profile, created = UserProfile.objects.get_or_create(user=user)
if to_toggle_user in user_profile.following.all():
user_profile.following.remove(to_toggle_user)
added = False
else:
user_profile.following.add(to_toggle_user)
added = True
return added


class UserProfile(models.Model):
'''
Extends the Django User model
'''
user = models.OneToOneField(settings.AUTH_USER_MODEL,
related_name='profile')
following = models.ManyToManyField(settings.AUTH_USER_MODEL,
blank=True,
related_name='followed_by')


objects = UserProfileManager()

def get_absolute_url(self):
return reverse_lazy('profiles:detail',
kwargs={'username':self.user.username})

def __str__(self):
return 'Username: {} [ Followers ({});
Following({})]'.format(self.user.username,
self.user.followed_by.all().count(),
self.following.all().count())

urls.py:

urlpatterns = [
url(r'^(?P<username>[\w.@+-]+)/$', UserDetailAPIVIew.as_view(),
name='user-posts-api'),
url(r'^(?P<username>[\w.@+-]+)/follow/$',
FollowToggleAPIView.as_view(), name='follow-api'),
]

唯一的问题是 UserSingleProfileSerializer 中显示的 (is_followed) 值是为所有用户实例一次性设置的(不是为我们要关注的特定用户) 。

我当然不会同时关注/取消关注所有用户(因为 FollowToggleAPIView 通过用户名定位特定用户)。

我想知道如何将 (is_followed) 的值仅传输给 UserDetailAPIVIew 中的特定用户 (user_to_toggle)。先感谢您。

最佳答案

这里使用 session 是完全错误的。您正在存储一个“关注”值,该值仅记录他们最后切换的用户,与他们实际查看的个人资料无关。

您应该简单地在 UserDetailAPIVIew 中查询特定用户的关注状态,而不是这样做。

def get_serializer_context(self):
context = super(UserDetailAPIVIew, self).get_serializer_context()
is_followed = self.request.user.profile.following.filter(username=self.object).exists()
context.update({'followed': is_followed})
return context

另请注意,您的切换方法本身效率非常低 - 无需从数据库中检索每个关注只是为了检查当前用户是否在其中。再次使用 exists:

user_profile, created = UserProfile.objects.get_or_create(user=user) 
if user_profile.following.filter(username=to_toggle_user).exists():

关于python - Django session 将参数从一个 View 传递到另一个 View ,但为所有用户实例设置相同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47186027/

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