Search code examples
djangodjango-rest-frameworkdjango-rest-viewsets

Django REST Framework TypeError: register() missing 1 required positional argument: 'viewset'


Im learning Django REST Framework and Im trying to get to work a simple ViewSet but I keep getting this error on the console when trying to run the server

  File "C:\Users\anahu\Projects\guatudu-api\api\api\locations\urls.py", line 13, in <module>
    router.register(r'countries', country_views.CountryViewSet, basename='country')
TypeError: register() missing 1 required positional argument: 'viewset'

this is my app's urls.py

"""Locations Urls"""

# Django
from django.urls import path, include

# Django Rest Framework
from rest_framework.routers import DefaultRouter

# Views
from api.locations.views import countries as country_views

router = DefaultRouter
router.register(r'countries', country_views.CountryViewSet, basename='country')

urlpatterns = router.urls

And this is my ViewSet

"""Countries view"""

# Django REST Framework
from rest_framework import viewsets

# Serializers
from api.locations.serializers import CountryModelSerializer

# Models
from api.locations.models import Country

class CountryViewSet(viewsets.ModelViewSet):
    """Country viewset"""

    queryset = Country.objects.all()
    serializer_class = CountryModelSerializer

and this is my serializer

"""Country Serializers"""

#Django Rest Framework
from rest_framework import serializers
from rest_framework.validators import UniqueValidator

#Model
from api.locations.models import Country

class CountryModelSerializer(serializers.ModelSerializer):
    """Country Model Serializer"""

    class Meta:
        """Meta class"""
        model = Country
        fields = (
            'id',
            'name',
            'image'
        )

is pretty basic stuff, but I keep getting that error. All I can imagine is that for some reason Im not getting the ViewSet from on the urls.py correctly? I hope you guys can help me


Solution

  • Try changing your url:

    """Locations Urls"""
    
    # Django
    from django.urls import path, include
    
    # Django Rest Framework
    from rest_framework.routers import DefaultRouter
    
    # Views
    from api.locations.views import countries as country_views
    
    router = DefaultRouter()
    router.register(r'countries', country_views.CountryViewSet, basename='country')
    
    urlpatterns = router.urls