user3181236
user3181236

Reputation: 357

Django NameError: name 'views' is not defined

I am working through this tutorial on rapid site development with Django.

I have followed it exactly (as far as I can see), but get the following error when I try to view the index page:

NameError at /name 'views' is not defined
Exception location: \tuts\urls.py in <module>, line 12

Here's urls.py:

from django.conf.urls import patterns, include, url

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',

    url(r'^admin/', include(admin.site.urls)),
    url(r'^$', views.index, name='index'),
)

Here's views.py:

from django.shortcuts import render

# Create your views here.
def index(request):
    items = Item.objects.order_by("-publish_date")
    now = datetime.datetime.now()
    return render(request,'portfolio/index.html', {"items": items, "year": now.year})

And here's models.py:

from django.db import models

# Create your models here.
class Item(models.Model):
    publish_date = models.DateField(max_length=200)
    name = models.CharField(max_length=200)
    detail = models.CharField(max_length=1000)
    url = models.URLField()
    thumbnail = models.CharField(max_length=200)

I also have a basic index.html template in place. From looking around I think I need to import my view somewhere.

But I'm completely new to Django so I have no clue. Any ideas?

Upvotes: 15

Views: 56077

Answers (3)

Sajid2405
Sajid2405

Reputation: 318

If you are using rest_framework in django then import:

from rest_framework import views

Upvotes: 0

Chirag Kanzariya
Chirag Kanzariya

Reputation: 397

from .views import index
  • here we have to import views model classes on urls model so above sentence import your view model class on urls model.

add this code in urls.py

Upvotes: 1

Rohan
Rohan

Reputation: 53316

The error line is

    url(r'^$', views.index, name='index'),
    #----------^

Here views is not defined, hence the error. You need to import it from your app.

in urls.py add line

from <your_app> import views
# replace <your_app> with your application name.

Upvotes: 35

Related Questions