Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django NameError: name 'views' is not defined

Tags:

python

django

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?

like image 646
user3181236 Avatar asked Jul 09 '14 09:07

user3181236


2 Answers

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.
like image 62
Rohan Avatar answered Nov 13 '22 19:11

Rohan


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

like image 24
Chirag Kanzariya Avatar answered Nov 13 '22 19:11

Chirag Kanzariya