我想只打印與我的模型的外鍵關聯的條目。我有一系列的列表,我想打印列表名稱和屬於該列表的所有項目。我當前的問題是,每個列表都有一個div生成,這很好,但是與每個列表關聯的每個項目都在div內打印出來,而不僅僅是與listname關聯的項目。打印字段只與django中的foreignkey有關
查看
def control_panel(request, username):
context = RequestContext(request)
if username == request.user.username:
if request.user.is_authenticated():
user = User.objects.get(username=username)
lists = request.user.newlist_set.all()
listitems = request.user.newlistitem_set.all().filter(list_name = lists)
return render_to_response('controlpanel.html', {'lists': lists,'listitems':listitems,}, context)
else:
return render_to_response('login.html', {}, context)
else:
return render_to_response('controlpanel.html', {}, context)
模型
from django.db import models
from django.contrib.auth.models import User
class newlist(models.Model):
user = models.ForeignKey(User)
list_name = models.CharField(max_length = 100)
picture = models.ImageField(upload_to='profiles/', default = "")
def __str__(self):
return self.list_name
class newlistitem(models.Model):
user = models.ForeignKey(User)
list_name = models.ForeignKey(newlist)
list_item = models.CharField(max_length = 200)
def __str__(self):
return self.list_item
HTML
{% for lista in lists %} <!-- This is a call to the lists that exist for eaach model taht s instantiates -->
<div id = "indivlistitem">
<b>{{lista}}</b><br> <!-- This is the title of each list that is rendered to the HTML -->
{% for eachlistitem in listitems %}
{{eachlistitem}}
{%endfor%}
</div>
{% endfor %}
我相信這就是我要做的,但是你的代碼片段無法打印任何東西。 – ryan
哼,我沒有把正確的模型名稱。它應該是lista.newlistitem_set.all。 –
非常感謝! – ryan