没有使用 slug_pattern 反向匹配 django

Posted

技术标签:

【中文标题】没有使用 slug_pattern 反向匹配 django【英文标题】:No reverse match django with slug_pattern 【发布时间】:2021-01-26 18:31:57 【问题描述】:

所以我想从 urls.py 中插入一个 url,但是因为我们有一个 slug_pattern arg,我很困惑如何做到这一点。

以下是回溯:

Environment:


Request Method: GET
Request URL: http://localhost:8000/universitas-indonesia

Django Version: 1.11.20
Python Version: 2.7.15
Installed Applications:
('neliti',
 'publisher',
 'accounts',
 'hal',
 'mtam',
 'haystack',
 'django_countries',
 'storages',
 'select2',
 'modeltranslation',
 'tastypie',
 'mathfilters',
 'fastsitemaps',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.sites',
 'django.contrib.redirects',
 'debug_toolbar',
 'django_extensions')
Installed Middleware:
('corsheaders.middleware.CorsMiddleware',
 'django.middleware.locale.LocaleMiddleware',
 'publisher.middleware.CustomDomainMiddleware',
 'publisher.middleware.IndexingMiddleware',
 'django.middleware.gzip.GZipMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.middleware.common.CommonMiddleware',
 'publisher.middleware.RemoveSlashMiddleware',
 'publisher.middleware.ToLowercaseMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'django.middleware.common.BrokenLinkEmailsMiddleware',
 'django.contrib.redirects.middleware.RedirectFallbackMiddleware',
 'debug_toolbar.middleware.DebugToolbarMiddleware',
 'publisher.middleware.NonhtmlDebugToolbarMiddleware')


Template error:
In template E:\Project\neliti\backend\publisher\templates\publisher\headers\sub-menu\sub_menu_repository.html, error at line 51
   Could not parse the remainder: '-indonesia' from 'universitas-indonesia'   41 :       <li>
   42 :         <a href="#">Policies</a>
   43 :       </li>
   44 :       <li>
   45 :         <a href="#">For developers</a>
   46 :       </li>
   47 :     </ul>
   48 :   </div>
   49 : 
   50 :   <div class="section">
   51 :     <a id="contact" href=" % url 'organisation_detail' slug=universitas-indonesia % ">
   52 :       <div class="header">
   53 :         CONTACT
   54 :       </div>
   55 :     </a>
   56 :   </div>
   57 : </div>

urls.py 看起来像这样

我们使用 OrganisationDetailView 和 slug_pattern

slug_pattern = '(?P<slug>[a-z0-9_\\-]+)'

url(r'^%s$' % slug_pattern, cache_page(content_page_cache_time)(OrganisationDetailView.as_view()), name='organisation_detail'),
    prefix_default_language=False
)

我的组织视图如下所示

class OrganisationDetailView(NelitiDetailView):
    model = Organisation
    filter_set = 'Publication'
    template_name = 'publisher/organisation_detail.html'
    display_filters = ['language', 'year', 'contribution', 'type', 'grade', 'country', 'province']

    def get_select_and_prefetch_objects(self):
        return self.model.objects.select_related(
            'primary_type', 'country', 'style_settings'
        ).prefetch_related(
            'parents', 'disciplines'
        )

    def get_search_box_placeholder(self):
        return _("Search %(name)s repository") % 'name': self.object.name_short

    def get_narrow_query(self):
        # return 'author_org:"%(pk)s" OR funder:"%(pk)s" OR publisher:"%(pk)s"' % 'pk': self.object.pk
        return 'repository:"%s"' % self.object.pk

    def get_context_data(self, **kwargs):
        # Add journal_lists and conference_lists to context

        # order_by('title') doesn't work, probably because half the titles are in title_en and half in title_ind
        journal_set = sorted(Journal.objects.indexed().filter(
            Q(primary_publisher__in=self.object.descendants) | Q(secondary_publishers__in=self.object.descendants)).distinct()
            , key=lambda x: x.title)
        # According to Anton, don't include proceedings published by descendent organisations
        conference_set = sorted(ConferenceNew.objects.indexed().filter(
            Q(primary_organiser=self.object) | Q(secondary_organisers=self.object)).distinct()
            , key=lambda x: x.name, reverse=True)

        for obj_set, key in [(journal_set, 'journal_lists'), (conference_set, 'conference_lists')]:
            n = len(obj_set)
            if n == 0:
                kwargs[key] = []
            elif n <= 6:
                kwargs[key] = [obj_set]
            else:
                split_point = int(math.ceil(n/2))
                kwargs[key] = [
                    obj_set[:split_point],
                    obj_set[split_point:],
                ]
        favicon = get_favicon_href(self.model, self.object)
        kwargs['favicon'] = favicon
        return kwargs

我尝试做任何相关的组合来插入网址,但没有找到解决方案,如果你能提供任何见解,它会有所帮助

感谢您的帮助

【问题讨论】:

【参考方案1】:

更新您的 html &lt;a&gt; 标签。 universitas-indonesia 也应该用单引号引起来 slug='universitas-indonesia'

<div class="section">
 <a id="contact" href=" % url 'organisation_detail' slug='universitas-indonesia' % ">
    <div class="header">
       CONTACT
     </div>
 </a>
</div>

假设 URL 有 ?var1='universitas-indonesia' 动态获取 slug

<div class="section">
 <a id="contact" href=" % url 'organisation_detail' slug=request.GET.var1 % ">
    <div class="header">
       CONTACT
     </div>
 </a>

请根据您的 URL 更新您的 var1 变量。

【讨论】:

完美!!谢谢阿卡什 与此相关,我可以动态地将 slug 更改为 window.location 的值吗?谢谢 您可以通过 request.GET 方法获取 views.py 文件中的 URL 值,然后通过上下文将其传递给 HTML,在 HTML 中您可以使用该变量。 @Studentofcode 好吧,你能给我一个简单的例子吗?非常感谢 link 你可以关注这个问题,希望它能解决你的问题。

以上是关于没有使用 slug_pattern 反向匹配 django的主要内容,如果未能解决你的问题,请参考以下文章

Django:密码重置时没有反向匹配[重复]

Django 没有反向匹配错误 - 模板渲染

没有反向匹配 - django.urls.exceptions.NoReverseMatch

我怎样才能避免在 django 中没有反向匹配

渲染带有 uid/token 变量的电子邮件模板时没有反向匹配

ImportError:导入 dj_database_url ImportError:没有名为“dj_database_url”的模块