python - Django: "Object is not iterable",当尝试修改所述对象时

标签 python django iterable

我正在尝试编辑已创建的对象(“Worry”)。

我在views.py中有这段代码:

def worry_edit(request, id):
    worry = get_object_or_404(Worry, pk = id)
    original_pub_date = worry.pub_date
    form = WorryForm(request.POST or None, instance = worry)
    if form.is_valid():
        worry = form.save(commit = False)
        worry.pub_date = original_pub_date
        worry.save()
        return redirect(worry)
    return render_to_response('holaProy/worry_edit.html', {'worry_form': form, 'worry_id': id}, context_instance=RequestContext(request))

点击表单上的发送按钮时会出现以下错误:

argument of type 'Worry' is not iterable

关于为什么会出现该错误以及如何解决它有什么见解吗?

编辑:根据 Girasquid 的建议,这是完整的回溯:

Environment:

Request Method: POST
Request URL: http://127.0.0.1:8000/holaProy/worry_edit/1/

Django Version: 1.4.1
Python Version: 2.7.3
Installed Applications:
('django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.admin',
 'django.contrib.admindocs',
 'holaProy',
 'registration',
 'django.contrib.humanize')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware')


Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
  111.                         response = callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Richard\proyectosPython\holaProyecto\holaProyecto\holaProy\views.py" in worry_edit
  50.         return redirect(worry)
File "C:\Python27\lib\site-packages\django\shortcuts\__init__.py" in redirect
  81.         if '/' not in to and '.' not in to:

Exception Type: TypeError at /holaProy/worry_edit/1/
Exception Value: argument of type 'Worry' is not iterable

最佳答案

为了能够将模型实例传递给redirect,您需要定义 get_absolute_url()方法就可以了。否则,Django 只是假设它是字符串形式的 URL 并尝试解析它。

关于python - Django: "Object is not iterable",当尝试修改所述对象时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13995724/

相关文章:

python - 如何查找单词 - 第一个字母大写,其他字母小写

python - 尝试获取字段 'status_code' 的值时出现 AttributeError

django - 如何在卖家和产品表之间使用 ManyToManyField 放置产品价格

python - 什么是迭代器、可迭代和迭代?

android - jnius.find_javaclass ,jnius.JavaException : Class not found 'android/webkit/WebView'

python - Py2exe lxml 问题

django - 使用 django-storages 解析 csv 文档时获取 "new-line character seen in unquoted field"

python-3.x - python的multiprocessing.Queue的可迭代实现中的继承

java - 将 Iterable<Character> 转换为 String 的最佳方法?

python - 交叉熵损失与重量手动计算