J
J
Jekson2020-02-26 11:23:49
Django
Jekson, 2020-02-26 11:23:49

How to pass the current user in a POST request to Django Rest Framework in Postman?

There is a class for creating a model instance in which there is a connection to the user.
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)


In postman in body I pass the request in the form

{
        "vendor_name": "Awaxddas",
        "country": "Belarus",
        "Primary Contact Name": "Jack Jhonson",
        "Primary Contact Email": "[email protected]",
        "Secondary Contact Name": "Jack2 Jhonson",
        "Secondary Contact Email": "[email protected]",
        "Modules": "Module1, Module2",
        "NDA date": ""
    }


In Authorization I use Type: Basic Auth where I enter login and password. But when I save, I get
ValueError: Cannot assign "<django.contrib.auth.models.AnonymousUser object at 0x7f112a911f28>": "Vendors.user_id" must be a "CustomUser" instance.

Anonymous user

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim, 2020-02-26
@Lepilov

There is no way to pass the user object directly in the postman, but you can pass data by which you can select the desired user (by his id, by email, etc.)
In the VendorsCreateView.post method, get this data from request and search for the user in the database if it is found, then save it to a variable (for example, user_object_from_db) and pass this user object here - vendor_serializer.save(user_id=user_object_from_db)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question