我想从一个模型中得到Django中的对象列表。你知道吗
我只想从请求用户那里得到'dht node'的列表,但是它在html文件中没有显示任何内容(就像列表是空的一样)。我使用的用户有2个“dht节点”,它们显示在django admin中。你知道吗
我不知道怎么了,因为如果我使用指令成员.dht.create(…)”在视图函数中,创建一个新的“dht节点”,如下所示。只有我通过表单输入的“dht节点”不显示。可以是表格吗?你知道吗
非常感谢,这是我的密码:
你知道吗型号.py你知道吗
class Node(models.Model):
name = models.CharField(primary_key=True, null=False, max_length= 50)
description= models.CharField(default=None, null=False, max_length= 250)
topic=models.CharField(default=None, null=False, max_length= 50, unique=True)
def __unicode__(self):
return self.name
class dht(Node):
temp = models.IntegerField(default=None, null=True)
hum = models.IntegerField(default=None, null=True)
class UserProfile(User):
uid = models.CharField(default=None, null=False, max_length= 250)
dht = models.ManyToManyField(dht, blank=True)
def __unicode__(self):
return self.user.username
你知道吗视图.py-dht列表-
@login_required(login_url = '/web/login')
def listDhtSensor(request):
member = request.user.userprofile
list = member.dht.all()
return render(request, 'web/listDhtSensor.html', {'list':list})
Html格式-listDhtSensor.html文件-你知道吗
{% block content %}
{% for dht in list %}
{{ dht.name }}
{{ dht.topic }}
{% endfor %}
{% endblock %}
你知道吗表单.py你知道吗
class newDHTSensorForm(forms.ModelForm):
class Meta:
model = dht
field = ['name',
'description',
'topic',]
labels = {'name': 'Name' ,
'description': 'Description',
'topic': 'Topic',}
exclude = ['temp', 'hum']
你知道吗视图.py-dht表格-
@login_required(login_url = '/web/login')
def newDHTSensor(request):
if request.method == "POST":
form = newDHTSensorForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.save()
return redirect('/web/dhtDetail')
else:
form = newDHTSensorForm()
return render(request, 'web/newDhtSensor.html', {'form': form})
Html格式-新建DHTSensor.html-你知道吗
{% block content %}
<div class="boxReg">
<form method="post">
{% csrf_token %}
<h2>{{ form.name.errors.as_text }}</h2>
<p><label for="id_name">Name:</label> <input class="barraForm" type="text" name="name" maxlength="150" autofocus="" required="" id="id_name"></p>
<p><label for="id_description">Description:</label> <input class="barraForm" type="text" name="description" maxlength="150" id="id_description"></p>
<h2>{{ form.topic.errors.as_text }}</h2>
<p><label for="id_topic">Topic:</label> <input class="barraForm" type="text" name="topic" maxlength="254" id="id_topic"></p>
<div class="boxButtonReg">
<button class="buttonReg" type="submit">Save</button>
</div>
</form>
</div>
{% endblock %}
它没有显示任何内容,因为您没有将您的
dht
对象链接到该UserProfile
,所以如果您稍后查询该dht
的UserProfile
,显然列表是空的。您应该将其添加到dht
关系中,如:注意,您首先需要保存
post
,因此应该省略commit=False
参数。你知道吗相关问题 更多 >
编程相关推荐