Есть клас для создания инстанса модели, в которой есть связь на пользователя.
models.py
class Vendors(models.Model):
COUNTRY_CHOICES = tuple(COUNTRIES)
vendorid = models.AutoField(primary_key=True)
vendor_name = models.CharField(max_length=45, unique=True)
country = models.CharField(max_length=45, choices=COUNTRY_CHOICES)
nda = models.DateField(blank=True, null=True)
consent = models.DateField(blank=True, null=True)
active = models.BooleanField(default=False)
user_id = models.ForeignKey('c_users.CustomUser', on_delete=models.PROTECT)
timestamp = models.DateTimeField(auto_now_add=True)
class VendorsCreateView(APIView):
"""Create new vendor instances from form"""
def post(self, request, *args, **kwargs):
vendor_serializer = VendorsSerializer(data=request.data)
try:
vendor_serializer.is_valid(raise_exception=True)
vendor_serializer.save(user_id=request.user)
except ValidationError:
return Response({"errors": (vendor_serializer.errors,
)},
status=status.HTTP_400_BAD_REQUEST)
else:
return Response(request.data, status=status.HTTP_200_OK)
В postman в body передаю запрос в виде
{
"vendor_name": "Awaxddas",
"country": "Belarus",
"Primary Contact Name": "Jack Jhonson",
"Primary Contact Email": "jack@gmail.com",
"Secondary Contact Name": "Jack2 Jhonson",
"Secondary Contact Email": "jack2@gmail.com",
"Modules": "Module1, Module2",
"NDA date": ""
}
В Authorization использую Type: Basic Auth где ввожу логин и пароль. Но при сохранении получаю
ValueError: Cannot assign "<django.contrib.auth.models.AnonymousUser object at 0x7f112a911f28>": "Vendors.user_id" must be a "CustomUser" instance.
Анонимный юзер