Django中的用户关注者模型。显示用户名而不是用户的电子邮件地址

我有一个自定义的用户模型和关注者系统。一切运行良好,我有一个供稿系统,其中显示了用户遵循的操作。 每当一个用户关注另一个用户时,其显示如下:

User A started following userb@gmail.com

我需要像

User A started following User B or User A started following username(user B)

如何在我的代码中进行更改。请先看一下代码,在此先感谢。

意见

@login_required
def user_follow(request):
    user_id = request.POST.get('id')
    action = request.POST.get('action')
    if user_id and action:
        try:
            user = Account.objects.get(id=user_id)
            if action == 'follow':
                Contact.objects.get_or_create(user_from=request.user, user_to=user)
                create_action(request.user, 'started following', user) # TODO: change email to username
            else:
                Contact.objects.filter(user_from=request.user, user_to=user).delete()
            return JsonResponse({'status':'ok'})
        except User.DoesNotExist:
            return JsonResponse({'status':'error'})
    return JsonResponse({'status':'error'})

跟随的js

  $('a.follow').click(function(e){
e.preventDefault();
$.post('{% url "posts:user_follow" %}',
  {
    id: $(this).data('id'),
    action: $(this).data('action')
  },
  function(data){
    if (data['status'] == 'ok') {
      var previous_action = $('a.follow').data('action');
      // toggle data-action
      $('a.follow').data('action',
        previous_action == 'follow' ? 'unfollow' : 'follow');
      // toggle link text
      $('a.follow').text(
        previous_action == 'follow' ? 'Unfollow' : 'Follow');
      // update total followers
      var previous_followers = parseInt(
        $('span.count .total').text());
      $('span.count .total').text(previous_action == 'follow' ?
      previous_followers + 1 : previous_followers - 1);
    }
  }
);

});

模型

    class Contact(models.Model):
    user_from = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='rel_from_set', on_delete=models.CASCADE)
    user_to = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='rel_to_set', on_delete=models.CASCADE)
    created = models.DateTimeField(auto_now_add=True, db_index=True)

    #USER_FROM IS THE ONE WHO IS FOLLOWING AND USER_TO IS ONE BEING FOLLOWED
    class Meta:
        ordering = ('-created',)

    def __str__(self):
        return f'{self.user_from} follows {self.user_to}'

following = models.ManyToManyField('self', through=Contact, related_name='followers', symmetrical=False)

#adding the above field to User Model class
user_model = get_user_model()
user_model.add_to_class('following', models.ManyToManyField('self', through=Contact, related_name='followers',
                            symmetrical=False))

用户模型

class Account(AbstractBaseUser):
    email                   = models.EmailField(verbose_name="email", max_length=60, unique=True)
    username                = models.CharField(max_length=30, unique=True)
    first_name              = models.CharField(max_length=50)
    last_name               = models.CharField(max_length=50, blank=True)
    date_joined             = models.DateTimeField(verbose_name='date joined', auto_now_add=True)
    last_login              = models.DateTimeField(verbose_name='last login', auto_now=True)
    is_admin                = models.BooleanField(default=False)
    is_active               = models.BooleanField(default=True)
    is_staff                = models.BooleanField(default=False)
    is_superuser            = models.BooleanField(default=False)


    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username', 'first_name', 'last_name']

    objects = MyAccountManager()

    def __str__(self):
        return self.email


    def has_perm(self, perm, obj=None):
        return self.is_admin

    def has_module_perms(self, app_label):
        return True
评论
DJHongKong
DJHongKong

更换:

def __str__(self):
        return self.email

与:

def __str__(self):
        return self.username

这是用于显示模型的默认字符串。

For more info see https://docs.djangoproject.com/en/3.0/ref/models/instances/#str

点赞
评论