Skip to content
Advertisement

Python Django REST Infinite Recursion Problem

As of late I’ve started working towards learning REST Api with Django Rest Framework, Cors headers, and mssql connector both for personal purposes, and for a project I’m working on. Beneath I’ll include snippets of code and or the errors I got to make this easier to digest.

RecursionError: maximum recursion depth exceeded while calling a Python object

Working with this project, I got close to completing a Get/Post/Put method, but once I attempted to run the server itself, it ended in an endless recursion. I’ve attempted to search a variety of threads but I’m quite unsure what the problem may be.

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

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

class Users(models.Model):
    UID = models.AutoField(primary_key=True)
    UFName = models.CharField(max_length=100)
    ULName = models.CharField(max_length=100)
    UEmail = models.CharField(max_length=100)
 
from rest_framework import serializers
from BingeWatcherApp.models import Users

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model=Users
        fields=('UID', 'UFName','ULName', 'UEmail')

urlpatterns=[
    path('', views.Users, name='Users'),
    path('BingeWatcherApp/', include('BingeWatcherApp.urls'))

]

def UserAPI(request, id=0):
    if request.method=='GET':
        users = Users.objects.all()
        user_serializer = UserSerializer(users, many=True)
        return JsonResponse(user_serializer.data, safe=False)
    elif request.method =='POST':
        user_data=JSONParser().parse(request)
        user_serializer=UserSerializer(data=user_data)
        if user_serializer.is_valid():
            user_serializer.save()
            return JsonResponse("User Inserted Correctly", safe=False)
        return JsonResponse("Error. Please insert valid data.")
    elif request.method=='PUT':
        user_data=JSONParser().parse(request)
        user = Users.objects.get(UID=user_data['UID'])
        user_serializer=UserSerializer(user, data=user_data)
        if user_serializer.is_valid:
            user_serializer.save()
            return JsonResponse("Data updated successfully")
        return JsonResponse("Data update unsuccesfull. Try again.")

In order are the main url.py document, models.py, serializer.py, url.py within my app, and my view. Note these are all in different files, not a single file. As for the major imports I’m using Django 4.0, Django-cors-headers, DjangoRestFramework and MSSQL-Django.

If you need more information, or find the error. Let me know and I’ll respond as quickly as possible.

Advertisement

Answer

It looks like you are including BingeWatcherApp.urls inside itself. This is what leads to the error

Advertisement