Home > Enterprise >  when i trying to object.save() i got an error "missing 1 required keyword-only argument: '
when i trying to object.save() i got an error "missing 1 required keyword-only argument: '

Time:02-20

when i trying save something in views . get an error ,

"    post_obj.save()
TypeError: __call__() missing 1 required keyword-only argument: 'manager'
"

models.py

class Post(models.Model):
  title = models.CharField(max_length=150)
  owner = models.ForeignKey(Customer, on_delete=models.CASCADE)

views.py

@api_view(["POST"])
def create_post(request):
    if request.data != {}:
        id = request.data["customer_id"]
        title = request.data["title"]

        user = Customer.objects.filter(id=id)
        
        if user.count() != 0:
          post_obj = Post(owner=user, title = title)
          post_obj.save()

then i get this error . how can i fix this error ?

CodePudding user response:

I expect that this line is causing you the problem:

user = Customer.objects.filter(id=id)

Change it to:

user = Customer.objects.get(id=id)

And even better, if you want to ensure it is the user which is authenticated in the session, then you can do this:

user = Customer.objects.get(user=request.user.pk)

Its worth also noting that the field we are filtering on user may not be the field name you have actually specified on your Customer model, and if it isn't user, simply switch it for the field that relates Customer and djangos user model (unless you have created an abstract user model called customer, which uses django user as base, then, id=id or id=request.user.id would suffice as replacements in this case).

Explanation: I believe you're trying to set a ForeignKey but you're passing it a queryset, which doesn't have the fields, but rather a group of a single object customer.

CodePudding user response:

@shamsucm will the following code produces the same error? The answer from @Swift was very compelling and if you are still having the same issue it could be related to some other part of the code you have.

@api_view(["POST"])
def create_post(request):
    if request.data != {}:
        id = request.data["customer_id"]
        title = request.data["title"]

        user = Customer.objects.filter(id=id).first()
        
        if user:
          post_obj = Post(owner=user, title=title)
          post_obj.save()
  • Related