[Answered ]-Django, url not found 404

1👍

Three things:

1 – Have you installed rest_framework in your INSTALLED_APPS of your settings.py?

2 – Your path() in your urls.py should not contain the r'^ portion, meaning the proper paths are path('admin/', admin.site.urls) and path('zzz/', DisplayItemsViews.as_view()). This is old behavior from when Django suggested using url() instead of path()

3 – I assume you’ve imported APIView in your views.py, if not, you need to from rest_framework.views import APIView

EDIT: My working local version.

views.py

from rest_framework.response import Response
from rest_framework import status
from rest_framework.views import APIView

from .serializers import DisplayItemsSerializer
from .models import DisplayItems


class DisplayItemsViews(APIView):
    def get(self, request):
        displayItems = DisplayItems.create("YES!", "There's yoga today", "At 2:00 pm Eastern Time")
        serializer = DisplayItemsSerializer(displayItems)
        return Response({"status": "success", "data": serializer.data}, status=status.HTTP_200_OK)

settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'base',
    'rest_framework'
]

urls.py

from django.contrib import admin
from django.urls import path

from base.views import DisplayItemsViews

urlpatterns = [
    path('admin/', admin.site.urls),
    path('zzz/', DisplayItemsViews.as_view())

]

models.py

class DisplayItems(models.Model):
    yesNo = models.CharField(max_length=10)
    yogaMessage = models.CharField(max_length=50)
    yogaTimeMessage = models.CharField(max_length=100)

    @classmethod
    def create(cls, yesNo, yogaMessage, yogaTimeMessage):
        displayItems = cls(yesNo=yesNo, yogaMessage=yogaMessage, yogaTimeMessage=yogaTimeMessage)
        return displayItems

serializers.py

from rest_framework import serializers

from .models import DisplayItems

class DisplayItemsSerializer(serializers.ModelSerializer):
    yesNo = serializers.CharField(max_length=10)
    yogaMessage = serializers.CharField(max_length=50)
    yogaTimeMessage = serializers.CharField(max_length=100)

    class Meta:
        model = DisplayItems
        fields = ('__all__')

And the result, at localhost:8080/zzz
Image of DRF

Leave a comment