'Cannot assign "str" must be a "User" instance
I'm trying to make a post request to django rest api from reactjs but the traceback shows,
ValueError: Cannot assign "<django.contrib.auth.models.AnonymousUser object at 0x00000247410D3670>": "BuildingClearance.resident_number" must be a "User" instance.
models.py
class BuildingClearance(models.Model):
resident_number = models.ForeignKey(to=User, to_field="resident_number", on_delete=models.CASCADE)
request_number = models.AutoField(primary_key=True)
maintenance_type = models.CharField(max_length=100, blank=False)
approval = models.BooleanField(default=False)
views.py
class BuildingClearanceList(ListCreateAPIView):
permission_classes = [AllowAny]
serializer_class = BuildingClearanceSerializer
queryset = BuildingClearance.objects.all()
def perform_create(self, serializer):
return serializer.save(resident_number=self.request.user)
def get_queryset(self):
return self.queryset.filter(resident_number=self.request.user)
class BuildingClearanceView(RetrieveUpdateDestroyAPIView):
serializer_class = BuildingClearanceSerializer
queryset = BuildingClearance.objects.all()
def perform_create(self, serializer):
return serializer.save(resident_number=self.request.user)
def get_queryset(self):
return self.queryset.filter(resident_number=self.request.user)
serializers.py
class BuildingClearanceSerializer(ModelSerializer):
class Meta:
model=BuildingClearance
exclude = ['resident_number']
If i set the permission_classes to [isAuthenticated], the error message will be 401 unauthorized (Authentication credentials were not provided) even though i included the right headers:
services.js
const API_URL = "http://127.0.0.1:8000/api/forms/";
buildingClearance(maintenance_type) {
var token = JSON.parse(localStorage.getItem('user')).access;
console.log(token)
return axios
.post(API_URL + "building/", {
headers:{
Accept: 'application/json',
Authorization: 'Bearer ' + token
},
maintenance_type
})
}
Solution 1:[1]
replac this code
class BuildingClearance(models.Model):
resident_number = models.ForeignKey(to=User, to_field="resident_number", on_delete=models.CASCADE)
resident_number = models.ForeignKey(User, to_field="resident_number", on_delete=models.CASCADE)
To read more infomation about models https://docs.djangoproject.com/en/4.0/topics/db/models/
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Zakaria Zhlat |
