简体   繁体   English

Django Rest Api过滤器字段基于request.user的选择选项

[英]Django Rest Api filter field's select options based on request.user

I am currently working on a django rest framework api which involves displaying a list of campaigns and allowing user to create new campaign. 我目前正在开发django rest框架api,该API涉及显示广告系列列表并允许用户创建新的广告系列。

On the browsable api, I managed to display the list of campaigns that I wanted as well as have a form for the user to create new campaign. 在可浏览的api上,我设法显示了想要的广告系列列表,并为用户提供了一个表格来创建新的广告系列。

This is a screenshot of the form that the user is using for creating new campaign. 这是用户用于创建新广告系列的表单的屏幕截图。

A screenshot of the form on browsable API 可浏览API上的表单的屏幕截图

While everything is working, I faced an issue that I do not have any idea how to solve even after reading the documentation. 在一切正常的同时,即使在阅读了文档之后,我仍然面临一个不知道如何解决的问题。

As you can see on the screenshot, there is a clist field that allows user to select the contact list he/she want the campaign invitations to be sent to. 如您在屏幕快照中所见,有一个clist字段,允许用户选择他/她希望将活动邀请发送到的联系人列表。 However, I want to make sure only the contact lists created by the user's company are shown in that field (currently, all the contact lists from different companies can be selected). 但是,我想确保在该字段中仅显示由用户公司创建的联系人列表(当前,可以选择来自不同公司的所有联系人列表)。

Here is the codes in the api.py: 这是api.py中的代码:

class EditCampaignViewSet(ModelViewSet):
    queryset = Campaign.objects.all()
    serializer_class = EditCampaignSerializer
    parser_classes = (MultiPartParser, FormParser)

    def get_serializer_context(self):
        return {'request': self.request}

    def list(self, request, p_uuid=None, type=None, *args, **kwargs):
        company = request.user.profile.company
        queryset = Campaign.objects.filter(company=company,
                                           product__uuid=p_uuid,
                                           deleted=False,
                                           campaign_type=type)\
                                   .order_by('-created')\
                                   .prefetch_related('user__profile')
        serializer = EditCampaignSerializer(queryset, many=True)
        return Response(serializer.data)

This is the serializers.py 这是serializers.py

class EditCampaignSerializer(serializers.ModelSerializer):
    class Meta:
        model = Campaign
        fields = ('id', 'campaign_id', 'campaign_type', 'name', 'product', 'description', 'status', 'actual_file_name',
              'pdf_file', 'download', 'header', 'body', 'footer', 'company', 'created', 'updated', 'deleted',
              'clist', 'user')
        read_only_fields = ('id', 'campaign_id', 'campaign_type', 'product', 'status', 'actual_file_name', 'company', 'created',
                        'updated', 'deleted', 'user')

    def __init__(self, *args, **kwargs):
        super(EditCampaignSerializer, self).__init__(*args, **kwargs)
        user = self.context['request'].user
        self.fields['clist'] = ChoiceField(choices=CList.objects.filter(company=user.profile.company))

I am still pretty new to django rest framework, so please pardon me if the answer is obvious. 我对Django rest框架还很陌生,所以如果答案很明显,请原谅我。

Not sure what your models look like, but something like this will work: 不知道您的模型是什么样子,但是这样可以工作:

views.py: views.py:

class EditCampaignViewSet(ModelViewSet):
    ...

    def get_serializer_context(self):
        return {'request': self.request}

serializers.py: serializers.py:

class EditCampaignSerializer(serializers.ModelSerializer):

    class Meta:
        ...
        ...

    def __init__(self, *args, **kwargs):
        super(EditCampaignSerializer, self).__init__(*args, **kwargs)
        user = self.context['request'].user
        self.fields['clist'] = ChoiceField(choices=ContactList.objects.filter(company__user=user))

I removed the get_serializer_context and instead updated my codes to this. 我删除了get_serializer_context ,而是将代码更新为此。

serializer = EditCampaignSerializer(queryset, many=True, context={'request': self.request})

Now, the request is passed to the serializer. 现在,请求被传递给序列化器。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用REST Framework的Django 1.8.4根据通讯录中的request.user选择相反的列 - Django 1.8.4 with REST Framework select opposite column based on request.user in contacts table Django管理员:如何根据对象(而非request.user)的数据过滤ForeignKeyField小部件? - Django admin: how do I filter a ForeignKeyField widget based on the object's (not request.user's) data? Django-filter:具有基于 request.user 的查询集的 ModelChoiceFilter - Django-filter: ModelChoiceFilter with request.user based queryset 在Django的选择小部件中可以选择request.user - request.user as a choice in select widget in Django Django-Rest-Framework:如何使用request.user为登录用户发布到foreignkey字段 - Django-Rest-Framework: How to post to foreignkey field using request.user for logged in user 第一个 django rest api 调用返回 request.user 作为 AnonymousUser 但进一步调用返回正确的用户 - First django rest api call returns request.user as AnonymousUser but further calls return proper user 在django rest框架中使用request.user进行模型反序列化 - Use request.user for model deserialization in django rest framework 无法使用django rest框架进行身份验证(request.user = AnonymousUser) - Not able to authenticate using the django rest framework (request.user = AnonymousUser) 如何通过request.user过滤django-tastypie的ToManyField? - How to filter ToManyField of django-tastypie by request.user? Django:如何使用ModelFormSet通过request.user过滤ForeignKey选择 - Django: How to filter ForeignKey choices by request.user with ModelFormSet
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM