-DJANGO-我的以下功能似乎无效?

时间:2019-05-17 05:54:05

标签: django django-models django-views

我正在创建一个Twitter克隆,但现在我陷入以下问题和后续问题,我编写了可以使用户关注和取消关注用户的代码,但该代码无法正常工作。即使一切似乎都是正确的。我认为问题在于,当UserFollow视图执行时,它应该先执行该操作,然后重定向,但它不重定向,这不能完成整个视图,也许就是这种情况。

这是模型。py

class ProfileManager(models.Manager):
   def all(self):
    qs = self.get_queryset().all()
    if self.instance:
        qs = qs.exclude(user = self.instance)
    else:
        pass
    return qs

   def toggle_follow(self, user, to_toggle_user):
    user_profile, created = Profile.objects.get_or_create(user=user) # (user_obj, true)
    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

   def is_following(self, user, followed_by_user):
    user_profile, created = Profile.objects.get_or_create(user=user)
    if created:
        return False
    if followed_by_user in user_profile.following.all():
        return True
    return False




class Profile(models.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 = ProfileManager()

这是views.py

class UserProfile(DetailView):
       model = User.objects.all()
      template_name = 'accounts/user_detail.html'

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

def get_context_data(self, *args, **kwargs):
    context = super(UserProfile, self).get_context_data(*args, **kwargs)
    following = Profile.objects.is_following(self.request.user, self.get_object())
    context['following'] = following
    # context['recommended'] = UserProfile.objects.recommended(self.request.user)
    return context

class UserFollow(View):
       def get(self,request,username,*args,**kwargs):
         toggle_user = get_object_or_404(User, username__iexact=username)
         if request.user.is_authenticated():
             is_following = Profile.objects.toggle_follow(request.user, toggle_user)


         return redirect("accounts:detail",username=username)   

这是关注和取消关注的模板代码

 <a href='{% url 'accounts:follow' object.username %}'class="btn btn-info">
        {% if following %}Unfollow {% else %}Follow{% endif %}</a>

1 个答案:

答案 0 :(得分:0)

URL中的人为错误

URL是

url(r'(?P<pk>\w+)/follow/$',views.UserFollow.as_view(),name = 'follow')

实际上是

url(r'^(?P<pk>\w+)/follow/$',views.UserFollow.as_view(),name = 'follow')

一开始是胡萝卜