【问题标题】:No Reverse Match没有反向匹配
【发布时间】:2017-08-02 17:19:07
【问题描述】:
Reverse for 'details' with arguments '('Federal Airports Authority of Nigeria (FAAN)',)' and keyword arguments '{}' not found. 

1 pattern(s) tried: 

['details/(?P<company_name>[0-9A-Za-z]+)/$']

这是我的urls.py

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^details/(?P<company_name>[0-9A-Za-z]+)/$', views.details, name='details'),
    url(r'^full_list/$', views.full_list, name='full_list' ),
]

这是models.py

class CompanyDetail(models.Model):

    name = models.CharField(max_length=300)
    company_logo = models.FileField(default='')
    company_info = models.TextField()
    company_address = models.TextField()
    tag = models.CharField(max_length=300)

    def __str__(self):
        return self.name

这是我的views.py

def details(request, company_name):
    company = CompanyDetail.objects.get(name=company_name)
    return render(request, 'company_profiles/details.html',
    {'company':company} )

def full_list(request):
    lists = CompanyDetail.objects.all()
    return render(request, 'company_profiles/full_list.html', 
    {'lists':lists})

这是模板:

{% extends 'company_profiles/base.html' %}

{% block content %}

{% for company in lists %}
    <p>
    <div class="alert alert-info" role="alert">
     <a href="{% url 'company_profiles:details' company.name %}" class="alert-link">{{ company }}</a>
    </div>
    </p>


{% empty %}
    <p>No companies found</p>

{% endfor %}
{% endblock content %}

只有当公司名称中有空格时,我才会得到反向匹配。

【问题讨论】:

    标签: python regex django


    【解决方案1】:

    那是因为你的正则表达式

    (?P<company_name>[0-9A-Za-z]+)
    

    不允许在公司名称中使用空格。 Django 正确地告诉你没有反向匹配。

    选择以下选项之一:

    • 更改名称验证代码以禁止使用空格(并迁移现有行),或者
    • 更改urls.py 中的正则表达式以允许空格

    我推荐第二个选项。

    【讨论】:

    • 这行得通:url(r'^details/(?P[A-Za-z0-9_ +()]+)/$', views.details, name='details '),
    【解决方案2】:

    你应该在 urls.py 中尝试这个来匹配公司名称

    (?P<company_name>[\w-]+)
    

    还有一件事为什么您不使用公司 ID 作为参数?如下:

    在 urls.py 中

    (?P<company_id>[0-9]+)/
    

    在模板中

    <a href="{% url 'company_profiles:details' company.pk %}" 
    class="alert-link">{{ company }}</a>
    

    【讨论】:

    • 我猜他想要 url 中的名字而不是 id。个人选择正确。
    • 但标题不是好办法。否则他应该使用 slug 字段。
    • 你能解释一下吗?
    • seo-hacker.com/url-seo-tutorial 阅读关于 slug 的完整文章为什么 slug 在 URL 中很好
    猜你喜欢
    • 2020-08-01
    • 2012-10-21
    • 2017-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多