如何在Django中增加用户之间的友谊

时间:2018-11-22 11:38:18

标签: python html django view model

我正在做一个学校项目。我正在使用Django创建一个社交媒体网站。我在添加用户之间的友谊时遇到问题。

在模型中,我扩展了基本的Django用户。 get_friendship是否正确完成?

models.py

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    real_name = models.CharField(max_length=60)
    address = models.CharField(max_length=60)
    phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$')
    phone_number = models.CharField(validators=[phone_regex], max_length=17)

        def get_friendships(self):
            friendships = Friendship.objects.all()
            return friendships

class Friendship(models.Model):
    creator = models.ForeignKey(User, related_name="friendship_creator_set", on_delete=models.CASCADE)
    new_friend = models.ForeignKey(User, related_name="friend_set", on_delete=models.CASCADE, null=True)
    confirmed = models.BooleanField(default=False)

    @classmethod
    def make_friend(cls, creator, new_friend, confirmed=True):
    friendship, created = cls.objects.get_or_create(
        creator = creator, new_friend = new_friend, confirmed=True)
    friendship.save()

views.py

class Index(LoginRequiredMixin, generic.ListView):
    login_url = '/login'
    redirect_field_name = ''
    template_name = 'home/index.html'
    context_object_name = 'posts_list'

    def get(self, request):
        form = HomeForm()
        posts = Post.objects.all().order_by('-pub_date')
        users = User.objects.exclude(id=request.user.id)
        user = Profile.user
        friends = Profile.get_friendships(user)

        args = {
        'form': form, 'posts': posts, 'users': users, 'friends': friends
    }

def add_friend(request, operation, pk):
    friend = User.objects.get(pk=pk)
    Friendship.make_friend(request.user, friend)
    return redirect('/')

index.html

<h2>Friends</h2>
    {% for friend in friends %}
        <h3>{{ friend.username }}</h3>
    {% endfor %}

所以问题是我无法访问朋友列表。似乎get_friendships无法正常工作。一些代码仅用于测试,因此它们不是最终形式。所有可能的帮助将不胜感激。我对Django完全陌生。

0 个答案:

没有答案