I have a model named Following that has these fields:
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)
What I'm trying to create is a follow button that when pressed, gives the target a follower. Inside the view that has the follow button, has this logic:
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
When we want to create a row for the new follower, an error happens saying that create() takes 1 positional argument but 2 were given
What am I doing wrong?
To solve this ” Typeerror: takes 1 positional argument but 2 were given ” is by adding self argument for each method inside the class. It will remove the error.
The Python "TypeError: takes 2 positional arguments but 3 were given" occurs for multiple reasons: Forgetting to specify the self argument in a class method. Forgetting to specify a third argument in a function's definition. Passing three arguments to a function that only takes two.
Using Positional Arguments Followed by Keyword Arguments One method is to simply do what the error states and specify all positional arguments before our keyword arguments! Here, we use the positional argument 1 followed by the keyword argument num2=2 which fixes the error.
You need to pass keyword arguments to create()
method:
target.followers.create(follower=follower)
Or you can use add()
method instead:
target.followers.add(follower)
Also it should be remove
not delete
:
target.followers.remove(follower)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With