我的愿望是创建一个包含以下选项的选择菜单:
models.py
TITLE_CHOICES = (
('MR', 'Mr.'),
('MRS', 'Mrs.'),
('MS', 'Ms.'),
)
显示在hello.html
上。但我一直得到这个错误:ImportError: No module named hello
对象:#continuation of models.py
class hello(models.Model):
title = models.CharField(max_length=3, choices=TITLE_CHOICES)
def __unicode__(self):
return self.name
view.py:
from django.http import HttpResponse
from django.template.loader import get_template
from django.template import Context
from testApp.models import hello
from testApp.models.hello import title
from django.shortcuts import render_to_response
from django.template import RequestContext
def contato(request):
form = hello()
return render_to_response(
'hello.html',
locals(),
context_instance=RequestContext(request),
)
def hello_template(request):
t = get_template('hello.html')
html = t.render(Context({'name' : title}))
return HttpResponse(html)
My app in INSTALLED_APPS
(setting.py
):
INSTALLED_APPS = (
'testApp',
'hello',
)
感谢您的帮助。
为什么在你安装的应用程序是hello
?我想这可能就是问题所在。hello
是属于testApp
的models.py
中的一个类。testApp
是你唯一需要包含在INSTALLED_APPS
中的东西。
同样,你也应该从代码中删除这一行:from testApp.models.hello import title
,这也会产生一个错误,因为你不能从类中导入一个字段。如果你需要访问title
字段,你必须这样做:
def contato(request):
form = hello()
title = form.title
return render_to_response(
'hello.html',
locals(),
context_instance=RequestContext(request),
)
def hello_template(request):
t = get_template('hello.html')
# see here the initialization and the access to the class field 'title'
title = hello().title
html = t.render(Context({'name' : title}))
return HttpResponse(html)