Как правильно передать параметры экземпляру Class Based View в Django? - PullRequest
0 голосов
/ 20 сентября 2019

Я пытаюсь передать параметры в экземпляре Class Based View, но не могу найти правильный способ сделать это.

Мой сервис API хорошо работает в представлении REST Framework и получает дваобязательные параметры (пользователь и язык):

enter image description here

enter image description here

Я нашел похожие отвечает но отправляет параметры взамен, это не моя ситуация.Это мой звонок,

_customdictionary = CustomDictionaryViewSet()
_customdictionary.custom_dictionary_kpi(request) 

Я попробовал и потерпел неудачу с:

_customdictionary.custom_dictionary_kpi(request)
_customdictionary.custom_dictionary_kpi({'language': 1, 'user': 1})
_customdictionary.custom_dictionary_kpi(1,1)
# In all cases i receive status = 500

Когда я вижу свой error.log, в этой части:

class CustomDictionaryViewSet(viewsets.ModelViewSet):
...
    def custom_dictionary_kpi(self, request, *args, **kwargs):
        try:
            import pdb;pdb.set_trace()

Отправка запрос , он показывает мне:

AttributeError: 'WSGIRequest' object has no attribute 'data'

Отправка dict , он показывает мне:

AttributeError: 'dict' object has no attribute 'data'

Отправка толькозначения:

AttributeError: 'int' object has no attribute 'data'

api / urls.py

urlpatterns = [
url(r'^api/customdictionary/custom_dictionary_kpi/user/<int:user_id>/language/<int:language_id>', CustomDictionaryViewSet.as_view({'post': 'custom_dictionary_kpi'}), name='custom_dictionary_kpi')
]

api / api.py

class CustomDictionaryViewSet(viewsets.ModelViewSet):
    queryset = CustomDictionary.objects.filter(
        is_active=True,
        is_deleted=False
    ).order_by('id')
    permission_classes = [
        permissions.AllowAny
    ]
    pagination_class = StandardResultsSetPagination

    def __init__(self,*args, **kwargs):
        self.response_data = {'error': [], 'data': {}}
        self.code = 0

    def get_serializer_class(self):
        if self.action == 'custom_dictionary_kpi':
            return CustomDictionaryKpiSerializer
        return CustomDictionarySerializer

    @action(methods=['post'], detail=False)
    def custom_dictionary_kpi(self, request, *args, **kwargs):
        try:
            '''some logic'''
        except Exception as e:
            '''some exception'''
        return Response(self.response_data,status=self.code)

serializers.py

class CustomDictionarySerializer(serializers.ModelSerializer):
    class Meta:
        model = CustomDictionary
        fields = ('__all__')

class CustomDictionaryKpiSerializer(serializers.ModelSerializer):
    class Meta:
        model = CustomDictionary
        fields = ('user','language')

web / views.py

class CustomDictionaryView(View):
    """docstring for CustomDictionaryView"""
    def __init__(self,*args, **kwargs):
        self.response_data = {'error': [], 'data': {}}
        self.code = 0

    def get(self, request, *args, **kwargs):
        try:
            _customdictionary = CustomDictionaryViewSet()
            import pdb;pdb.set_trace()
            _customdictionary.custom_dictionary_kpi()   # Here is the call, 
            self.response_data['data'] = _customdictionary.response_data['data']
            self.code = _customdictionary.code

        except Exception as e:
            '''some exception'''

Extra: Как я могу отправить дополнительный необязательный параметр?

Большое спасибо, любая помощь будет оценена по достоинству:)

1 Ответ

1 голос
/ 20 сентября 2019

Да, это правильные данные, вы должны вызывать request.data в вашем custom_dictionary_kpi, и вы не задаете параметр в качестве веб-запроса.

Вы можете в любое время отправлять дополнительные данные в самом запросе из браузера, почтальона или клиента, например {"language": 1, "user": 1,"foo": "bar"}

и делать request.POST.get('foo') на стороне сервера.

Если хотитечтобы передать данные в класс, вы можете сделать это с помощью ключевого аргумента, подобного этому

_customdictionary = CustomDictionaryViewSet()
_customdictionary.custom_dictionary_kpi(request,language=1,user=1) 

, а в реализации вашего метода вы можете получить доступ к args например (запрос) здесь как кортеж и как словарь, если выпосмотрите kwargs как словарь, например {"language": 1, "user": 1} здесь

Попробуйте напечатать или отладить аргументы и kwargs и посмотрите.

...