create()需要1个位置参数,但是给出了2个?

时间:2018-06-06 06:24:56

标签: python django

我有一个名为Following的模型,它包含以下字段:

values = [row.delay, ...]

我想要创建的是一个按下按钮,当按下该按钮时,会给目标成为追随者。在具有跟随按钮的视图内,具有以下逻辑:

class Following(models.Model):
    target = models.ForeignKey('User', related_name='followers', on_delete=models.CASCADE)
    follower = models.ForeignKey('User', related_name='targets', on_delete=models.CASCADE)

    def __str__(self):
        return '{} is followed by {}'.format(self.target, self.follower)

当我们想为新关注者创建一行时,会发生错误,说class ProfileView(DetailView): model = User slug_field = 'username' template_name = 'oauth/profile.html' context_object_name = 'user_profile' # Without this, Django would default to request.user instead which is the logged in user def post(self, request, slug): follower = self.request.user self.object = self.get_object() context = self.get_context_data(object=self.object) follow_unfollow(follower, self.object.id) # Error is found inside this function return render(request, self.template_name, context=context) def follow_unfollow(follower, id): target = get_object_or_404(User, id=id) if follower.is_authenticated(): if follower in target.followers.all(): target.followers.delete(follower) else: target.followers.create(follower) # Error outputs: create() takes 1 positional argument but 2 were given 我做错了什么?

2 个答案:

答案 0 :(得分:5)

您需要将关键字参数传递给create()方法:

target.followers.create(follower=follower)

或者您可以改为使用add()方法:

target.followers.add(follower)

也应remove而不是delete

target.followers.remove(follower)

答案 1 :(得分:2)

当您获得User实例时,您错过了视图中的某个点,实际上,您需要删除Following实例以防它存在,请尝试以下操作:

def follow_unfollow(follower, id):
    target = get_object_or_404(User, id=id)

    if follower.is_authenticated():
        following = target.followers.filter(follower=follower)
        if following.exists():
            following.delete()
        else:
            # target.followers.create(follower=follower,target=target) 
            Following.objects.create(follower=follower,target=target)