首页 > 解决方案 > Django用户关注者ajax问题

问题描述

我已经使用 Ajax 构建了用户关注功能,因此用户可以关注/取消关注另一个用户。问题是当我点击“关注”按钮时,前端什么也没有发生。我的意思是文字不会更改为“取消关注”,因为它应该是,并且关注者的数量也不会改变。如果重新加载页面,那很好 - 添加了一个关注者。然后,如果我单击“取消关注”按钮,一切正常 - Ajax 请求正常,并且在 db 中删除了一个关注者。我发现问题发生了,因为当按下“关注”按钮并发送 Post 请求时,响应代码是 500(内部服务器错误)。使用“取消关注”它可以正常工作,请求是 200。我花了很多时间来解决这个问题。任何帮助appriciated。

下面是代码。

用户模型和用于以下功能的模型:

    from django.db import models
    from django.contrib.auth.models import AbstractUser
    from django.utils.translation import ugettext_lazy as _
    from django.urls import reverse
    from django.conf import settings
    
    from .managers import CustomUserManager
    from team.models import Team
    
    
    
    class Contact(models.Model):
        user_from = models.ForeignKey('CustomUser',
                                      related_name='rel_from_set',
                                      on_delete=models.CASCADE)
        user_to = models.ForeignKey('CustomUser',
                                    related_name='rel_to_set',
                                    on_delete=models.CASCADE)
        created = models.DateTimeField(auto_now_add=True,
                                       db_index=True)
    
        class Meta:
            ordering = ('-created',)
    
        def __str__(self):
            return '{} follows {}'.format(self.user_from,
                                          self.user_to)
    
    
    class CustomUser(AbstractUser):
        username = None
        email = models.EmailField(_('email address'), unique=True)
        team = models.ForeignKey(Team, null=True, blank=True, on_delete=models.SET_NULL)
        profile_img = models.ImageField(null=True,blank=True)
        following = models.ManyToManyField('self', through=Contact, related_name='followers', symmetrical=False)
    
        USERNAME_FIELD = 'email'
        REQUIRED_FIELDS = []
    
        objects = CustomUserManager()
    
        def __str__(self):
            return self.email
    
    
        def get_absolute_url(self):
            return reverse('user-detail', kwargs={'id': self.id})
    

视图.py 文件:

```
@ajax_required
@require_POST
@login_required
def user_follow(request):
    user_id = request.POST.get('id')
    action = request.POST.get('action')
    if user_id and action:
        try:
            user = CustomUser.objects.get(id=user_id)
            if action == 'follow':
                Contact.objects.get_or_create(user_from=request.user,
                                              user_to=user)
                create_action(request.user, 'is following', user)
            else:
                Contact.objects.filter(user_from=request.user,
                                       user_to=user).delete()
            return JsonResponse({'status':'ok'})
        except CustomUser.DoesNotExist:
            return JsonResponse({'status':'ok'})
    return JsonResponse({'status':'ok'})

urls.py:


    urlpatterns = [
        
        path('users/follow/', views.user_follow, name='user_follow'),
    ...another urls...
    ]
    

显示在 html 中的关注/取消关注按钮:

       {% with total_followers=user.followers.count %}
       <span class="count-f">
         <span class="total-f">{{ total_followers }}</span>
         follower{{ total_followers|pluralize }}
       </span>
       <a href="#" data-id="{{ user.id }}" data-action="{% if request.user in user.followers.all %}un{% endif %}follow" class="follow button">
         {% if request.user not in user.followers.all %}
           Follow
         {% else %}
           Unfollow
         {% endif %}
       </a>
       
     {% endwith %}


在同一个 html 文件中的 ajax 代码:

    {% block domready %}
       $('a.follow').click(function(e){
        e.preventDefault();
        const $clickedFollowButton = $( this );
        
        $.post('{% url "user_follow" %}',
          {
            id: $clickedFollowButton.data('id'),
            action: $clickedFollowButton.data('action')
          },
          function(data){
            if (data['status'] == 'ok') {
              var previous_action = $clickedFollowButton.data('action');
    
              // toggle data-action
              $clickedFollowButton.data('action', previous_action == 'follow' ? 'unfollow' : 'follow');
              
              // toggle link text
              $clickedFollowButton.text(previous_action == 'follow' ? 'Unfollow-ha-ha' : 'Follow');
    
              // update total followers
              const $totalFollowers = $clickedFollowButton.prev('span.count-f').children('.total-f');
              var previous_followers = parseInt(
                $('span.count-f .total-f').text());
              
               $totalFollowers.text(previous_action == 'follow' ? previous_followers + 1 : previous_followers - 1);
               
               console.log(previous_action);
           
            }
          }
        );
      });  
    
    {% endblock %}

标签: djangoajaxdjango-templates

解决方案


我发现了问题所在。我得到的错误是由视图函数中的那行代码引起的:


    create_action(request.user, 'is following', user)

我使用了不存在的函数 create_action。删除后一切正常。


推荐阅读