''CityListViewSet' should either include a `serializer_class` attribute, or override the `get_serializer_class()` method
I am assuming by the error in the title, once more here for clarity
'CityListViewSet' should either include a `serializer_class` attribute,
or override the `get_serializer_class()` method.
that my serializer isn't connected to my view, which in my code it should be. I'm not really sure where the bug is in this one. I wonder if any of you have seen something similar?
Here is the code.
Router:
router.register(r'city-list', CityListViewSet, base_name='city-list')
view:
class CityListViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Venue.objects.values('city').distinct()
serializer = CitySerializer(queryset, many=True)
ordering_fields = ('city',)
ordering = ('city',)
serializer:
class CitySerializer(serializers.ModelSerializer):
class Meta:
model = City
fields =('city',)
what is it that would be causing such an assertion error with the code seemly wired up correctly?
Solution 1:[1]
The exception says it itself. You need a serializer_class
attribute. You have serializer
.
Solution 2:[2]
Add this code snippet to your views.py
file
class CityListViewSet(viewsets.ReadOnlyModelViewSet): # (viewsets.ModelViewSet)
serializer_class = CitySerializer
queryset = City.objects.values('city').distinct()
serializer = CitySerializer(queryset, many=True)
ordering_fields = ('city',)
ordering = ('city',)
Solution 3:[3]
i got this error when declared post method in view and trying to send post data without serialize, if you are doing the request from javascript i solved it using JSON.stringify()
Solution 4:[4]
error says you define a serializer attribute, you need to correct with writing serializer_class attribute in your code,
serializer_class = yourCreatedSerializer
Solution 5:[5]
serializer = CitySerializer(queryset, many=True)
The above line should be replaced with
serializer_class = CitySerializer(queryset, many=True)
Solution 6:[6]
Here you used a different model name:
view:
class CityListViewSet(viewsets.ReadOnlyModelViewSet): #(viewsets.ModelViewSet)
queryset = City.objects.values('city').distinct()
serializer = CitySerializer(queryset, many=True)
ordering_fields = ('city',)
ordering = ('city',)
import -> from .serializers import TaskSerializers,CitySerializer
serializer:
class CitySerializer(serializers.ModelSerializer):
class Meta:
model = City
fields =('city',)
Solution 7:[7]
you have to override the user just add
from django.contrib.auth.models import User
from rest_framework.permissions import IsAdminUser
and in createViewList
permission_classes = [IsAdminUser]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Cory Madden |
Solution 2 | Benyamin Jafari |
Solution 3 | franciscorode |
Solution 4 | Simas Joneliunas |
Solution 5 | Saeed |
Solution 6 | Tarak Sivakoti |
Solution 7 | Martin Brisiak |