0

I'm trying to adapt the example shown on http://www.django-rest-framework.org/ to Django 2.0, but I'm running into an error.

Firstly, I created a project using django-admin startproject rest_example. I've added 'rest_framework' to the INSTALLED_APPS list in settings.py and added the REST_FRAMEWORK variable:

REST_FRAMEWORK = {
    # Use Django's standard `django.contrib.auth` permissions,
    # or allow read-only access for unauthenticated users.
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
    ]
}

Here is my adapted urls.py:

from django.contrib import admin
from django.urls import path, include
from django.contrib.auth.models import User
from rest_framework import routers, serializers, viewsets


class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ('url', 'username', 'email', 'is_staff')


class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer


router = routers.DefaultRouter()
router.register(r'users', UserViewSet)

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api-auth/', include('rest_framework.urls'))
]

The problem is that when I python manage.py runserver and navigate to localhost:8000, I get a 404:

enter image description here

Similarly, if I navigate to localhost:8000/api-auth/, I get

enter image description here

Why is this not working?

2 Answers 2

1

I managed to fix this by changing the definition of urlpatterns to

urlpatterns = [
    path('admin/', admin.site.urls),
]

urlpatterns += router.urls

and also running python manage.py migrate before running the server. Now if I go to localhost:8000/users/ I get a user list view:

enter image description here

where I've run python manage.py createsuperuser once to create a (dummy) user.

Sign up to request clarification or add additional context in comments.

Comments

0

Alternatively, you can add the urls to their own sub-path by:

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include(router.urls)),
]

But otherwise having a database setup and a user record in it will definitely be needed for your example to function as expected ;-)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.