我正在尝试编辑已创建的对象(“忧虑”)。
我在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
答案 0 :(得分:4)
为了能够将模型实例传递给redirect
,您需要在其上定义get_absolute_url()
方法。否则,Django只是假设它是一个字符串形式的URL并试图解析它。