【发布时间】:2020-01-21 03:27:51
【问题描述】:
我正在尝试在基于类的视图实例中传递参数,但我想不出正确的方法。
我的 api 服务在 REST Framework 视图中运行良好,并接收两个强制参数(用户和语言):
我发现了类似的answers,但发送参数作为回报,这不是我的情况。这是我的电话,
_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)
序列化器.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'''
额外: 如何发送额外的可选参数?
非常感谢,任何帮助将不胜感激:)
【问题讨论】:
标签: django python-3.x django-rest-framework django-views django-class-based-views