尝试使用外键从不同类中选择字段,获取错误

时间:2022-02-10 21:52:36

I'm creating a reddit clone as a personal project to get to grips with django, and so far I've got two classes:

我正在创建一个reddit克隆作为个人项目来掌握django,到目前为止我有两个类:

from django.db import models
from django.contrib.auth.models import User

class Board(models.Model):
    name = models.CharField(max_length =100, blank = False)
    created_on = models.DateTimeField('Date Created', auto_now_add=True)
    deleted = models.BooleanField(default = False)

    def __unicode__(self):
        return self.name

class Notice(models.Model):
    title = models.CharField(max_length=200) #title as it appears on the notice
    author = models.ForeignKey(User, null=False, blank=False)
    posted_on = models.DateTimeField('Posted On', auto_now_add= True)
    updated_on = models.DateTimeField('Last Updated', auto_now = True)
    board = models.ForeignKey(Board, null=False)
    isText = models.BooleanField(null=False, blank = False)
    content = models.TextField()
    thumps_up = models.PositiveIntegerField()
    thumps_down = models.PositiveIntegerField()
    deleted = models.BooleanField(default=False)

    def __unicode__(self):
        return self.title

And in my urls I have:

在我的网址中,我有:

urlpatterns = patterns('',
    url(r'^$', views.index, name='index'),
    url(r'^(?P<board_name>\w+)/$', views.board_lv)
)

What I want to do is have the url pattern compare against the "name" field in the "Board" model using the "board" foreign key in the "Notice" model, and then open up a page listing all the notices with in that board (similar to subreddits in reddit).

我想要做的是使用“通知”模型中的“board”外键将url模式与“Board”模型中的“name”字段进行比较,然后打开一个列出所有通知的页面。 board(类似于reddit中的subreddits)。

I'm getting a type error saying "Notice object is not iterable", which leads me to think I've only got one object instead of a list, but I shouldn't have should I?

我收到一个类型错误,说“通知对象不可迭代”,这让我觉得我只有一个对象而不是一个列表,但我不应该这样做吗?

The iteration is in this part of the noticeList.html file;

迭代是在noticeList.html文件的这一部分;

{% for n in latest_notices %}
    <li>
    {% if not n.isText %} 
        <h2><a href="{{ n.content }}">{{ n.title }}</a></h2>            
    {% else %}
        <h2>{{ n.title }}</h2>
        <p>{{ n.content }}</p>
    {% endif %}
    </li>
{% endfor %}

where the views are:

意见在哪里:

from django.shortcuts import render, get_object_or_404
from notices.models import Board, Notice

def index(request):
    latest_notices = Notice.objects.order_by('-posted_on')
    context = {'latest_notices': latest_notices}
    return render(request, 'noticeList.html', context)

def board_lv(request, board_name):
    latest_notices = get_object_or_404(Notice, board__name=board_name)
    context = {'latest_notices': latest_notices}
    return render(request, 'noticeList.html', context)

Also, in the error traceback, the board_name variable value is preceded by a 'u' before the quoted string, e.g:

此外,在错误回溯中,board_name变量值在引用的字符串之前以'u'开头,例如:

Variable        Value
board_name      u'worldnews'

If I'm getting the url pattern wrong or haven't explained the problem well enough, please let me know as any help would be greatly appreciated.

如果我的网址格式错误或者没有充分解释问题,请告诉我,因为任何帮助都会非常感激。

EDIT: full traceback error

编辑:完全回溯错误

Traceback:
File "/usr/local/lib/python2.7/dist-packages/Django-1.5.2-py2.7.egg/django/core/handlers/base.py" in get_response
  115.                         response = callback(request, *callback_args, **callback_kwargs)
File "/home/adnan/Documents/django-noticeboard/noticeboard/notices/views.py" in board_lv
  13.   return render(request, 'noticeList.html', context)
File "/usr/local/lib/python2.7/dist-packages/Django-1.5.2-py2.7.egg/django/shortcuts/__init__.py" in render
  53.     return HttpResponse(loader.render_to_string(*args, **kwargs),
File "/usr/local/lib/python2.7/dist-packages/Django-1.5.2-py2.7.egg/django/template/loader.py" in render_to_string
  177.         return t.render(context_instance)
File "/usr/local/lib/python2.7/dist-packages/Django-1.5.2-py2.7.egg/django/template/base.py" in render
  140.             return self._render(context)
File "/usr/local/lib/python2.7/dist-packages/Django-1.5.2-py2.7.egg/django/template/base.py" in _render
  134.         return self.nodelist.render(context)
File "/usr/local/lib/python2.7/dist-packages/Django-1.5.2-py2.7.egg/django/template/base.py" in render
  830.                 bit = self.render_node(node, context)
File "/usr/local/lib/python2.7/dist-packages/Django-1.5.2-py2.7.egg/django/template/debug.py" in render_node
  74.             return node.render(context)
File "/usr/local/lib/python2.7/dist-packages/Django-1.5.2-py2.7.egg/django/template/defaulttags.py" in render
  284.                 return nodelist.render(context)
File "/usr/local/lib/python2.7/dist-packages/Django-1.5.2-py2.7.egg/django/template/base.py" in render
  830.                 bit = self.render_node(node, context)
File "/usr/local/lib/python2.7/dist-packages/Django-1.5.2-py2.7.egg/django/template/debug.py" in render_node
  74.             return node.render(context)
File "/usr/local/lib/python2.7/dist-packages/Django-1.5.2-py2.7.egg/django/template/defaulttags.py" in render
  147.             values = list(values)

Exception Type: TypeError at /b/worldnews/
Exception Value: 'Notice' object is not iterable

1 个解决方案

#1


1  

The problem is that get_object_or_404(Notice, board__name=board_name) returns one Notice model instance and it's not iterable.

问题是get_object_or_404(注意,board__name = board_name)返回一个Notice模型实例,它不可迭代。

One possible solution is to add this to a list and pass to the context:

一种可能的解决方案是将其添加到列表并传递给上下文:

def board_lv(request, board_name):
    latest_notices = get_object_or_404(Notice, board__name=board_name)
    context = {'latest_notices': [latest_notices]}
    return render(request, 'noticeList.html', context)

UPD for the next error: then, don't use get_object_or_404 if there could be more than one Notices per board. Use filter:

UPD用于下一个错误:然后,如果每个板可能有多个Notice,请不要使用get_object_or_404。使用过滤器:

def board_lv(request, board_name):
    latest_notices = Notice.objects.filter(board__name=board_name)
    context = {'latest_notices': latest_notices}
    return render(request, 'noticeList.html', context)

Hope that helps.

希望有所帮助。

#1


1  

The problem is that get_object_or_404(Notice, board__name=board_name) returns one Notice model instance and it's not iterable.

问题是get_object_or_404(注意,board__name = board_name)返回一个Notice模型实例,它不可迭代。

One possible solution is to add this to a list and pass to the context:

一种可能的解决方案是将其添加到列表并传递给上下文:

def board_lv(request, board_name):
    latest_notices = get_object_or_404(Notice, board__name=board_name)
    context = {'latest_notices': [latest_notices]}
    return render(request, 'noticeList.html', context)

UPD for the next error: then, don't use get_object_or_404 if there could be more than one Notices per board. Use filter:

UPD用于下一个错误:然后,如果每个板可能有多个Notice,请不要使用get_object_or_404。使用过滤器:

def board_lv(request, board_name):
    latest_notices = Notice.objects.filter(board__name=board_name)
    context = {'latest_notices': latest_notices}
    return render(request, 'noticeList.html', context)

Hope that helps.

希望有所帮助。