反驳参数'(u' d3 ...',)'和关键字参数' {}'未找到。尝试了1种模式

时间:2015-11-06 16:05:50

标签: python django django-templates

我想在我的django模板(home-page.html)中使用django反向网址:

{% for entry in zippedContent %}
    <li> <p style="display: inline-block;">{{ entry.0 }}</p>
        <a href="/">
            preview
        </a>
        <p style="display: inline-block;">{{ entry.1 }}</p>
        <a href="{% url 'fileDownloadPage' entry.2 %}{{ entry.2 }}">
            download
        </a>
    </li>
{% endfor %}

这是我的urls.py

urlpatterns = [
    # ...
    url(r'^home-page/', views.home_page, name="homePage"),
    url(r'^preview/', views.file_preview, name="filePreview"),
    url(r'^download/(?P<hash>[\w]+/$)', views.file_download, name="fileDownloadPage"),

在我的views.py我有home_pagefile_download次观看的代码:

@login_required
def home_page(request):
    current_group = Group.objects.get(name=request.user.username)
    return render(request, 'home-page.html', {
    'zippedContent': zip([f.file.name for f in current_group.file_set.all()],
                         [f.privacy for f in current_group.file_set.all()],
                         [f.hash for f in current_group.file_set.all()])
})


@login_required
def file_download(request, requested_file_hash):
    try:
        requested_file = File.objects.get(hash=requested_file_hash)
        response = HttpResponse(mimetype='application/force-download')
        response['Content-Disposition'] = 'attachment; filename=%s'\
                                          % smart_str(requested_file.file.name)
        response['X-Sendfile'] = smart_str(requested_file.file.url)
        return response
    except ObjectDoesNotExist:
        return Http404()

但是当我在浏览器中测试下载URL(download/something_here)时出现此错误:

  

反向&#39; fileDownloadPage&#39;参数&#39;(u&#39; d3b63b8895e15a8722668bd1da752b47842d13fa&#39;,)&#39;和关键字参数&#39; {}&#39;未找到。尝试了1种模式:[&#39;下载/(?P [\ w] + / $)&#39;]

home-page.html页面中的以下声明有什么问题:

<a href="{% url 'fileDownloadPage' entry.2 %}{{ entry.2 }}">

2 个答案:

答案 0 :(得分:0)

Django需要一个尾部斜杠。所以这个网址:

url(r'^download/(?P<hash>[\w]+/$)', views.file_download, name="fileDownloadPage"),

应该是:

url(r'^download/(?P<hash>\w+)/$', views.file_download, name="fileDownloadPage"),

此外,href可能存在问题。它应该改变:

<a href="{% url 'fileDownloadPage' entry.2 %}{{ entry.2 }}">

要:

<a href="{% url 'fileDownloadPage' entry.2 %}">{{ entry.2 }}</a>

答案 1 :(得分:0)

在您当前的正则表达式r'^download/(?P<hash>[\w]+/$)'中,完整的捕获组由r'(?P<hash>[\w]+/$)'定义。捕获组包括尾部斜杠,并且在反转时,完整的捕获组将被您的参数替换。传递不包含尾部斜杠的参数时,它将被替换,但它与原始正则表达式不匹配。这就是Django提出NoReverseMatch的原因。

这就是为什么你需要按照Aron的建议将尾部斜线移出捕获组:

url(r'^download/(?P<hash>\w+)/$', views.file_download, name="fileDownloadPage"),