0

我有一个“上传”视图,一旦表单被填写并被认为是有效的,它就会创建一个模型的实例:

...
from CrossStitch.models import Pattern

def upload(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            newpattern = Pattern(imagefile = request.FILES['pattern'],filename = request.POST['title'])
            return HttpResponseRedirect(reverse('configure', args=newpattern))
                                                                ^^
    else:
        form = UploadFileForm()
...

如向上箭头所示,我想将我的模型实例传递给下一个视图。配置视图如下:

def configure(request, pattern):
...

我的两个观点都有这样的网址:

url(r'^upload/$','CrossStitch.views.upload', name='upload'),
url(r'^configure/$','CrossStitch.views.configure', name='configure'),

但是,我收到此错误:

TypeError at /CrossStitch/upload/
_reverse_with_prefix() argument after * must be a sequence, not Pattern
Request Method: POST
Request URL:    http://127.0.0.1:8000/CrossStitch/upload/
Django Version: 1.4.5
Exception Type: TypeError
Exception Value:    
_reverse_with_prefix() argument after * must be a sequence, not Pattern
Exception Location: /usr/lib/python2.7/dist-packages/django/core/urlresolvers.py in reverse, line 476
Python Executable:  /usr/bin/python
Python Version: 2.7.3
Python Path:    
['/home/stacey/work/Django/StaceyAnne',
 '/usr/lib/python2.7',
 '/usr/lib/python2.7/plat-linux2',
 '/usr/lib/python2.7/lib-tk',
 '/usr/lib/python2.7/lib-old',
 '/usr/lib/python2.7/lib-dynload',
 '/usr/local/lib/python2.7/dist-packages',
 '/usr/lib/python2.7/dist-packages',
 '/usr/lib/python2.7/dist-packages/PIL',
 '/usr/lib/python2.7/dist-packages/gtk-2.0',
 '/usr/lib/pymodules/python2.7']
Server time:    Wed, 4 Sep 2013 15:22:12 +0200

如何正确地将对象的实例从一个视图传递到另一个视图?

4

1 回答 1

1

to的args关键字参数reverse 是一个迭代的. 您应该传递例如一个列表或一个元组。

但是,在您的情况下,pattern参数 toconfigure不应该是一个对象。在 URL 配置中,正则表达式应包含您要配置的模式的标识符,如本教程的第 3 部分所述。这样,configure您将通过其 ID 获取模式,并且reverse调用将如下所示reverse('configure', args=[newpattern.id])

于 2013-09-04T13:38:05.563 回答