我在谷歌应用程序引擎应用程序上,使用django处理视图、模板和文件结构,使用ndb处理模型/查询/处理数据存储。
我的问题是,我不知道如何通过查询正确地显示模型。看起来我可以发布到数据存储并从中检索,但我无法打印我检索到的内容。我得到了一个StringProperty()对象,我认为Django请求处理程序无法解密它,所以它实际上只是打印"StringProperty(()"。要么是这样,要么我就是不理解ndb查询,就像我想的那样:)
不管怎样,有什么想法可以让它正确地出现吗?我是不是注定要把ndb和django这样结合在一起?
如何显示:
https://i.stack.imgur.com/kERoQ.jpg
在models.py中:
from google.appengine.ext import ndb
# Create your models here.
class Contact(ndb.Model):
name = ndb.StringProperty
address_street = ndb.StringProperty
address_extra = ndb.StringProperty
address_city = ndb.StringProperty
address_state = ndb.StringProperty
address_zipcode = ndb.StringProperty
email = ndb.StringProperty
phone = ndb.StringProperty
视图.py:
from django import http
from django.core.context_processors import csrf
from django.views.decorators.csrf import csrf_protect
from django.template import RequestContext
from django.shortcuts import render_to_response
from models import Contact
def home(request):
contacts = Contact.query().fetch()
return render_to_response('index.html', {'message':'Hello World', 'contacts':contacts})
def form(request):
c = RequestContext(request)
if request.method == 'POST':
contact = Contact()
contact.name = request.POST['name']
address_street = request.POST['street']
address_extra = request.POST['extra']
address_city = request.POST['city']
address_state = request.POST['state']
address_zipcode = request.POST['zipcode']
email = request.POST['email']
phone = request.POST['phone']
contact.put()
return render_to_response('form.html', {'message':'Your contact, ' + contact.name + ', has been added.'}, c)
else:
return render_to_response('form.html', {'message':'Form!'}, c)
在index.html中:
{% extends "base.html" %}
{% block pagestyle %}
{% endblock %}
{% block content %}
{{ message }}
<br><br>
<table border=1>
<tr>
<td>Name</td><td>Address</td><td>City</td><td>State</td><td>Zipcode</td><td>Email</td><td>Phone</td>
</tr>
{% for contact in contacts %}
<tr>
<td>{{ contact.name }}</td>
</tr>
{% endfor %}
</table>
<div class="button" value="/form">Add a contact</div>
{% endblock %}
您的模型定义不正确。您不是在创建属性,只是持有对Property类的引用,它应该是
class Contact(ndb.Model):
name = ndb.StringProperty()
address_street = ndb.StringProperty()
address_extra = ndb.StringProperty()
address_city = ndb.StringProperty()
address_state = ndb.StringProperty()
address_zipcode = ndb.StringProperty()
email = ndb.StringProperty()
phone = ndb.StringProperty()
这就是您在输出中看到StringProperty的原因。