Konstantinos Korovesis
Konstantinos Korovesis

Reputation: 285

Django cant import my app in urls.py

I have issues importing my app in url patterns, but everything seems in place. I get errors in from fairy_app import views and an error name 'News' is not defined

directory:

fairy-

  fairy-
    _init_.py
    settings.py
    urls.py
    wsgi.py

  fairy_app-
    _init_.py
    admin.py
    models.py
    tests.py
    views.py

  db.fairy
  manage.py

views.py

from django.shortcuts import render
from django.views.generic import TemplateView

# Create your views here.

class News(TemplateView):
    template_name = 'news.html'

urls.py

from django.conf.urls import patterns, include, url
from django.contrib import admin
from fairy_app.views import News

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'fairy.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),

    url(r'^admin/', include(admin.site.urls)),
    url(r'^news/', News.as_view()),
)

setting.py

INSTALLED_APPS = (

    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'fairy_app',
)

Upvotes: 2

Views: 3315

Answers (3)

Rohan Abraham
Rohan Abraham

Reputation: 105

I had the same problem. I worked around it by giving the full path

from fairy.fairy_app.views

alternatively

from ..fairy_app.views

Upvotes: 1

venkatesh konangi
venkatesh konangi

Reputation: 11

I found the same problem,but got sorted it out.

Create a new python file in app-level for urls use include function in fairy-/urls file to include all other urls of the app and import views in the new file

for example;

#in url.py

urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^greet/',include('greetings.url')),
]

#created a new file(url.py) in greetings app
#in greetings/url.py

from . import views 
urlpatterns = [
url(r'^$',views.greet),
]

#greet is the function in my views`

Upvotes: 1

djangonaut
djangonaut

Reputation: 7778

In your urls.py you reference the News view without importing it. You import the views file as module.

So you can either do:

views.News.as_view()

or:

from fairy_app.views import News

2nd way is shorter but gets inconvenient if you have many view classes, so I prefer the first one.

Upvotes: 1

Related Questions