gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 20:14:10 25 4
gpt4 key购买 nike

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

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)

我要创建的是一个关注按钮,按下该按钮后,目标就会成为关注者。在具有关注按钮的 View 中,具有以下逻辑:

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

当我们想为新的关注者创建一行时,会发生错误,提示 create() 接受 1 个位置参数但给出了 2 个我做错了什么?

最佳答案

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

target.followers.create(follower=follower)

或者您可以使用 add() 方法代替:

target.followers.add(follower)

也应该是remove而不是delete:

target.followers.remove(follower)

关于python - create() 需要 1 个位置参数但给出了 2 个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50713488/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com