Django视图:无法识别对象值

时间:2013-10-22 21:14:41

标签: python django django-models django-templates django-views

我正在尝试从官方教程中学习django。

我遇到了一个奇怪的问题,这可能是微不足道的,但我无法弄明白 -

我正在学习本教程:

Tutorial 3

我的问题是,当我尝试访问http://hello.djangoserver:8080/poll时,我得到以下输出:

Output

但输出应该是对象的值,我不知道出了什么问题?本教程中描述的所有先前步骤对我来说都很好。

这是控制台输出:

(InteractiveConsole)
>>> from poll.models import Question, Choice
>>> Question.objects.get(pk=1)
<Question: What's up?>
>>> quit()

/srv/www/hello/poll/views.py

# Create your views here.  
from django.http import HttpResponse
from django.template import RequestContext, loader
from poll.models import Question

def index(request):
     latest_question_list = Question.objects.order_by('-pub_date')[:5]
     template = loader.get_template('poll/index.html')
     context = RequestContext(request, {
    'latest_question_list': latest_question_list,
    })  
    return HttpResponse(template.render(context))  

def detail(request, question_id):
    return HttpResponse("You're looking at question %s." % question_id)

def results(request, question_id):
    response = "You're looking at the results of question %s."
    return HttpResponse(response % question_id)

def vote(request, question_id):
    return HttpResponse("You're voting on question %s." % question_id)

/srv/www/hello/poll/urls.py

  from django.conf.urls import patterns, url 
  from poll import views

  urlpatterns = patterns('',
  url(r'^$', views.index, name='index'),

   # ex: /polls/5/
   url(r'^(?P<question_id>\d+)/$', views.detail, name='detail'),
   # ex: /polls/5/results/
   url(r'^(?P<question_id>\d+)/results/$', views.results, name='results'),
   # ex: /polls/5/vote/
   url(r'^(?P<question_id>\d+)/vote/$', views.vote, name='vote'),

/srv/www/hello/hello/urls.py

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

  # Uncomment the next two lines to enable the admin:
  from django.contrib import admin
  admin.autodiscover()

  urlpatterns = patterns('',

      url(r'^poll/', include('poll.urls')),

/srv/www/hello/poll/templates/poll/index.html

  {% if latest_question_list %}
  <ul>
  {% for question in latest_question_list %}
    <li><a href="/poll/{
   question.id }}/">{
  question.question_text }}</a></li>
  {% endfor %}
  </ul>
  {% else %}
     <p>No polls are available.</p>
  {% endif %}
  }"
  }"

来自settings.py -

的一些相关构造

/srv/www/hello/hello/settings.py:

  DEBUG = True

  DATABASES = { 
  'default': {
     'ENGINE': 'django.db.backends.mysql', 
             # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
     'NAME': 'mysite_db',                      
             # Or path to database file if using sqlite3.
    # The following settings are not used with sqlite3:
    'USER': 'root',
    'PASSWORD': '<my password>',
    'HOST': '',                      
             # Empty for localhost through domain sockets or 
             #'127.0.0.1' for localhost through TCP.
    'PORT': '',                      
             # Set to empty string for default.
    }   
  }


  MEDIA_ROOT = ''

  MEDIA_URL = ''

  STATIC_ROOT = ''

  STATIC_URL = '/static/'


  STATICFILES_DIRS = (
     # Put strings here, like "/home/html/static" or "C:/www/django/static".
     # Always use forward slashes, even on Windows.
     # Don't forget to use absolute paths, not relative paths.   
  )


  STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    # 'django.contrib.staticfiles.finders.DefaultStorageFinder',
  )



  TEMPLATE_LOADERS = (
   'django.template.loaders.filesystem.Loader',
   'django.template.loaders.app_directories.Loader',
    # 'django.template.loaders.eggs.Loader',
  )


  ROOT_URLCONF = 'hello.urls'

  WSGI_APPLICATION = 'hello.wsgi.application'

  TEMPLATE_DIRS = (

  )


  INSTALLED_APPS = (
   'django.contrib.auth',
   'django.contrib.contenttypes',
   'django.contrib.sessions',
   'django.contrib.sites',
   'django.contrib.messages',
   'django.contrib.staticfiles',
   'poll',
   # Uncomment the next line to enable the admin:
   'django.contrib.admin',
   # Uncomment the next line to enable admin documentation:
   'django.contrib.admindocs',
  )

/srv/www/hello/poll/models.py:

from django.db import models

from django.utils import timezone

import datetime


# Create your models here.

class Question(models.Model):
      question_text = models.CharField(max_length=200)
      pub_date = models.DateTimeField('date published')


def __unicode__(self):  # Python 3: def __str__(self):
    return self.question_text

def was_published_recently(self):
    return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
was_published_recently.admin_order_field = 'pub_date'    
was_published_recently.boolean = True
was_published_recently.short_description = 'Published recently?'

服务器运行命令:

    $ python manage.py runserver hello.djangoserver:8080

2 个答案:

答案 0 :(得分:2)

在HTML模板中,使用{{ question.id }}{{ question.question_text }}。请注意双{{}}

答案 1 :(得分:2)

您忘记了/srv/www/hello/poll/templates/poll/index.html中的一个大括号。