1

为什么这会返回 NoReverseMatch 错误?

看法:

def browse(request):
    thing_list = Thing.objects.all()
    if request.method == 'POST':
        form = BrowseForm(request.POST)
        if form.is_valid():
            make = Make.objects.all()
            return HttpResponseRedirect(reverse('browse_makes', args=[make]))
    else:
        form = BrowseForm()
    return render(request, 'browse.html', {'form':form, 'thing_list':thing_list})

def makes(request, make):
    ad_list = Thing.objects.filter(make=make)
    return render(request, 'browse-makes.html', {'thing_list':thing_list})

网址:

url(r'^browse/$', 'axlepost.views.browse.browse', name='browse'),
url(r'^browse/(?P<make>[\w-]+)/$', 'axlepost.views.browse.makes', name='browse_makes'),

形式:

class BrowseForm(forms.Form):
     make = forms.ModelChoiceField(queryset=Make.objects.all())

模型:

class Make(models.Model):
    make = models.CharField(max_length=20)

class Thing(models.Model):
    make = models.ForeignKey(Make)

返回Reverse for 'browse_makes' with arguments '([<Make: Samsung>],)' and keyword arguments '{}' not found. 感谢您对如何解决此错误的想法!

4

2 回答 2

2

您正在处理reverse()QuerySet 而不是 1 值。它也是一个.all()查询,因此它很可能有多个对象,并且与表单结果无关。

make = Make.objects.all() # QuerySet = ([<Make: Samsung>], [<Make: Sony>], [<Make: Apple>], etc)
return HttpResponseRedirect(reverse('browse_makes', args=[make])) # Expects 1 value

假设您想重定向到Make表单中的选定内容,那么您将需要以下内容:

if form.is_valid():
    # Get the valid form data
    cd = form.cleaned_data

    # Get the selected Make
    make = cd.get('make')

    # Redirect - note 'make.make'.  You want to pass the value not the object
    return HttpResponseRedirect(reverse('browse_makes', kwargs={'make': make.make}))
于 2013-01-17T09:40:37.540 回答
0

我认为有几个问题

  • 您的网址与适当的视图不对应

更改此行

url(r'^browse/(?P<make>[\w-]+)/$', 'axlepost.views.browse.makes', name='browse_makes'),

url(r'^browse/(?P<make>[\w-]+)/$', 'axlepost.views.browse', name='browse_makes'),
  • 更改视图定义以获取make参数

    def browse(request, make): ... #将局部变量“make”更改为其他变量

于 2013-01-17T04:32:15.727 回答