2

I am trying to learn the Django Rest Framework.

I create a project called djangorest. Then I created an app called api

In djangorest/urls.py I have:

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

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

]

In djangorest/settings.py I included the new app api:

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

However, when I run the server I get the error:

NameError: name 'api' is not defined

4
  • You forgot to import the api. Add import api.urls in the djangorest/urls.py. Commented Sep 6, 2019 at 14:50
  • With include(api.urls) you are instructing Django to include the url patterns from another object, where those patterns are taken from the url attribute of an object named api. If api is supposed to be a Python package (all Django apps are) then you forgot to import that package. Commented Sep 6, 2019 at 14:51
  • Thanks, api is the name of my app, not a python package. If I add import api.urls, I get "No module named api" Commented Sep 6, 2019 at 14:57
  • As @MartijnPieters said, all django apps are python modules. Is there an __init__.py file in your api app? Commented Sep 6, 2019 at 15:05

1 Answer 1

2

You need to use strings when including URLs.

path('api/', include('api.urls')),
Sign up to request clarification or add additional context in comments.

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.