Home > Enterprise >  AttributeError: 'ModelName' object has no attribute 'get' if response.get("
AttributeError: 'ModelName' object has no attribute 'get' if response.get("

Time:04-28

I'm trying to get a list of Scripts

I'm not sure why this error is django throwing however, Can anybody identify if there's something is wrong.

Model

class Script(models.Model):
    name = models.CharField(max_length=100)
    script = models.TextField()

    def __str__(self):
        return self.name

Serializer

class ScriptSerializer(serializers.Serializer):
    id = serializers.IntegerField(read_only=True)
    name = serializers.CharField(read_only=True)
    script = serializers.CharField(read_only=True)

view;

@api_view(['GET'])
def scripts(request):
    scripts = Script.objects.all()
    serializer = ScriptSerializer(scripts, many=True)
    return Response(serializer.data)

but when I call this view, I get this error

Internal Server Error: /api/v1/seo/scripts
Traceback (most recent call last):
  File "E:\folder\venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
    response = get_response(request)
  File "E:\folder\venv\lib\site-packages\django\utils\deprecation.py", line 136, in __call__
    response = self.process_response(request, response)
  File "E:\folder\venv\lib\site-packages\django\middleware\clickjacking.py", line 27, in process_response
    if response.get("X-Frame-Options") is not None:
AttributeError: 'Script' object has no attribute 'get'

I have also seen answers related to that issue in Stackoverflow but not able to reproduce the solution. And also this approach is not new to me, I have been using this type of functions all over the project. But I'm surprised now why it's happening.

Edit: Imports

from rest_framework.decorators import api_view
from rest_framework.response import Response
from .serializers import ScriptSerializer
from .models import Script

urls

from django.urls import path
from . import views as views

app_name = "seo"

urlpatterns = [
    path('scripts', views.Script, name='scripts'),
]

CodePudding user response:

I believe the issue here is in naming collision. Take a closer look to this:

@api_view(['GET'])
def scripts(request):
    scripts = Script.objects.all()
    serializer = ScriptSerializer(scripts, many=True)

The function named scripts and then this name reassigned with scripts = Script.objects.all(). This may lead to really unexpected behaviours

So try to rename your local variable. I.e.:

@api_view(['GET'])
def scripts(request):
    script_items = Script.objects.all()

UPD after urls.py added:

It should point to the function view i.o. model:

path('scripts', views.scripts, name='scripts'),
  • Related