Nameerror: name X' is not defined - Django Rest framework

Asked

Viewed 603 times

-1

Following the tutorial for creating API with DRF, I encountered difficulties while mapping the urls. By running 'python manage.py runserver', I get the following error path('', include(loja.urls)), NameError: name 'loja' is not defined. I can’t see where I’m failing in this process and hope I can count on help.

project structure:

sistema/
  loja/
    urls.py
    views.py
  sistema/
    urls.py

py views.

@csrf_exempt
def store_list(request):

if request.method == 'GET':
    store= Lojas.objects.all()
    serializer = LojasSerializer(store, many=True)
    return JsonResponse(serializer.data, safe=False)

elif request.method == 'POST':
    data = JSONParser().parse(request)
    serializer = LojasSerializer(data=data)
    if serializer.is_valid():
        serializer.save()
        return JsonResponse(serializer.data, status=201)
    return JsonResponse(serializer.errors, status=400)

shop/urls.py

from django.urls import path
from loja import views

urlpatterns = [
    path('loja/',  views.store_list),
]

system/urls.py

from django.contrib import admin
from django.urls import include, path
from rest_framework import routers
from loja import views


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

output error:

path('', include(loja.urls)), NameError: name 'loja' is not defined

EDIT: After output error, another error message appears and my operation is automatically terminated.

error:

SError: [WinError 123] A sintaxe do nome do arquivo, do nome do diretório ou do rótulo do volume está incorreta: '<frozen importlib._bootstrap>'

I believe I followed the tutorial carefully, so I can’t understand where I’m going wrong.

  • 1

    If you see the documentation about url namespaces, you have to pass as a string: path('', include('loja.urls'))

  • @drec4s I tried to pass as string. Unfortunately the result was the same.

  • 1

    So the problem is with the module name. It is loja or lojas? Another thing, you added this app to INSTALLED_APPS in the Settings?

  • In case it would be store same. Yes, I added in INSTALLED_APPS, but persists the same error :(

1 answer

1

Hi, it matters this way:

py.

from [a_tua_app_name].loja import views

NOTE: Test case replaces [a_tua_app_name] by your app name.

Or

from .loja import views

Or

from django.urls import path
import [a_tua_app_name].views

urlpatterns = [
    path('loja/',  [a_tua_app_name].views.store_list, name='loja'),
]
  • The format is already set that way. I really can’t understand what happens to generate this error. I made an edit showing another error message that appears after this. It would be very important to me that this topic did not die.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.