Skip to content
Advertisement

TypeError: post() takes 1 positional argument but 2 were given

I have my model class:

class Subscription(models.Model):
    email = models.EmailField(max_length=250, unique=True)

    def __str__(self):
        return self.email

and my View:

class SubscriptionView(APIView):
    queryset = Subscription.objects.all()

    def post(request):
        email = request.data.get('email')
        print(email)
        save_email = Subscription.objects.create(email=email)
        save_email.save()

        return Response(status=status.HTTP_201_CREATED)

My model only takes in 1 field which is the email. Not sure why I keep getting ‘TypeError: post() takes 1 positional argument but 2 were given’.

Advertisement

Answer

Your post is a method, so the first parameter is self:

class SubscriptionView(APIView):
    queryset = Subscription.objects.all()

    def post(self, request):
        email = request.data.get('email')
        Subscription.objects.create(email=email)
        return Response(status=status.HTTP_201_CREATED)

It is however quite seldom that one implements a post method itself. Usually you work for example with a CreateAPIView [drf-doc], and one can let the serializer, etc. handle all the work.

Advertisement