如何将all_auth / rest_auth用户与某个模型建立关系。与cookie /令牌djagno

时间:2022-04-09 19:18:42

I am using all_auth and rest_auth along with Angular. I have a model called Campaign

我正在使用all_auth和rest_auth以及Angular。我有一个名为Campaign的模型

class Campaign(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=100)
    hashtag = models.CharField(max_length=20)
    message = models.CharField(null=True, blank=True, max_length=100)
    sale_limit = models.IntegerField(null=True, blank=True)
    start_date = models.DateField(null=True, blank=True)
    expiry_date = models.DateField(default=now_plus_30)
    product_url = models.CharField(max_length=100)
    created_at = models.DateTimeField(default=datetime.now, blank=True)
    modified_at = models.DateTimeField(auto_now_add=True, blank=True)
    user = models.ForeignKey(User, unique=False)
    def __str__(self):              # __unicode__ on Python 2
        return self.name

and a view as

和视图

class ListCreateCampaign(APIView):
    """
    List all Campaigns or create one.
    """

    def post(self, request, format=None):
        serializer = CampaignSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

I don't want to pass user_id from via API, how do I get the user details and inject it in request.data

我不想从via API传递user_id,如何获取用户详细信息并将其注入request.data

1 个解决方案

#1


0  

One approach could be, make user field optional in serializer by making required=False. Then pass the user while calling .save() method of serializer like .save(user=request.user). For more info http://www.django-rest-framework.org/api-guide/serializers/#passing-additional-attributes-to-save

一种方法是,通过使required = False使用户字段在序列化器中可选。然后在调用序列化程序的.save()方法时传递用户,如.save(user = request.user)。欲了解更多信息http://www.django-rest-framework.org/api-guide/serializers/#passing-additional-attributes-to-save

#1


0  

One approach could be, make user field optional in serializer by making required=False. Then pass the user while calling .save() method of serializer like .save(user=request.user). For more info http://www.django-rest-framework.org/api-guide/serializers/#passing-additional-attributes-to-save

一种方法是,通过使required = False使用户字段在序列化器中可选。然后在调用序列化程序的.save()方法时传递用户,如.save(user = request.user)。欲了解更多信息http://www.django-rest-framework.org/api-guide/serializers/#passing-additional-attributes-to-save