Cannot assign "'user_name'": "Class.user" must be a "Account_class" instance

Viewed 26

enter image descripI am getting this error when I try to make a post requesttion here

How to can I solve this problem?

Here is my model:

class Coffee(models.Model):
name = models.CharField(max_length=60)
ratings = models.CharField(max_length=5)
taste = models.TextField()
coffeeType = models.CharField(max_length=60)
price = models.CharField(max_length=60)
img = models.CharField(max_length=200)
updated_at = models.DateTimeField(auto_now_add=True)
shopName = models.CharField(max_length=60)
coffeeShopID = models.CharField(max_length=200)
location = models.CharField(max_length=200)
user = models.ForeignKey(Account, on_delete=models.CASCADE, null=False, blank=False, related_name='user')

def __str__(self):
    return self.name[0:50]

class Meta:
    ordering = ['-updated_at']

Here is the serializer of that model:

class CoffeeSerializers(serializers.ModelSerializer):
class Meta:
    model = Coffee
    fields = '__all__'

Here is views for post request:

def addCoffee(request):
data = request.data

coffee = Coffee.objects.create(
    name=data['name'],
    ratings=data['ratings'],
    taste=data['taste'],
    coffeeType=data['coffeeType'],
    price=data['price'],
    img=data['img'],
    shopName=data['shopName'],
    coffeeShopID=data['coffeeShopID'],
    location=data['location'],
    user=data['user']
)

coffee.save()
serializer = CoffeeSerializers(coffee)

return Response(serializer.data)
1 Answers

i can only assume how your Account model looks like, problem is that you must send Account model, but you are sending string data['user']

def addCoffee(request):
    data = request.data

    account_object = Account.objects.get(THIS_IS_ACCOUNT_NAME = data['user']) 

    coffee = Coffee.objects.create(
        name=data['name'],
        ratings=data['ratings'],
        taste=data['taste'],
        coffeeType=data['coffeeType'],
        price=data['price'],
        img=data['img'],
        shopName=data['shopName'],
        coffeeShopID=data['coffeeShopID'],
        location=data['location'],
        user=account_object
    )

    coffee.save()
    serializer = CoffeeSerializers(coffee)

    return Response(serializer.data)
Related