首页 文章

Django - NoReverseMatch:反向'bha',没有找到参数

提问于
浏览
1

project/urls.py - 在这里,我传入了主键的正则表达式

from django.urls import path, re_path, include
from contextual import views

urlpatterns = [
    url('admin/', admin.site.urls),
    path('well_list/', include([

        re_path(r'^$', views.WellList_ListView.as_view(), name='well_list'),
        re_path(r'^create/', views.AddWell_CreateView.as_view(), name='create'),
        re_path(r'^(?P<pk>[-\w]+)/contextual/', include('contextual.urls')),

        ]))
]

contextual/urls.py

app_name = 'contextual'

urlpatterns = [

    re_path(r'^$', base_views.ContextualMainView.as_view(), name='main'),
    re_path(r'^bha/$', base_views.BHA_UpdateView.as_view(), name='bha'),

]

views.py

class ContextualMainView(DetailView):
    template_name = 'contextual_main.html'
    model = models.WellInfo


class WellList_ListView(ListView):
    template_name = 'well_list.html'
    context_object_name = 'well_info'
    model = models.WellInfo

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        # get string representation of field names in list
        context['fields'] = [field.name for field in models.WellInfo._meta.get_fields()]

        # nested list that has all objects' all attribute values
        context['well_info_values'] = [[getattr(instance, field) for field in context['fields']] for instance in context['well_info']]

        # includes well instance objects & values string list for each well
        context['well_info_zipped'] = zip([instance for instance in context['well_info']], context['well_info_values'])

        return context

class BHA_UpdateView(UpdateView):
    template_name = 'contextual_BHA.html'
    model = models.WellInfo
    fields = '__all__'
    success_url = reverse_lazy('well_list')

well_list.html - 主键在html中提供

<tbody>
  {% for well_instance, values in well_info_zipped %}
  <tr>
    {% for value in values %}
    <td><a href="{% url 'contextual:main' pk=well_instance.api %}">{{ value }}</a></td>
    {% endfor %}
  </tr>
  {% endfor %}
</tbody>

contextual_main.html - html中未提供主键

<button type="button" class="btn btn-default" data-container="body" data-toggle="popover">
  <a href="{% url 'contextual:bha' %}">BHA</a>
</button>

这是问题: http://127.0.0.1:8000/well_list/123412-11-33/contextual/ 不起作用,并给我错误:

NoReverseMatch at /well_list/123412-11-33/contextual/
Reverse for 'bha' with no arguments not found. 1 pattern(s) tried: ['well_list\\/(?P<pk>[-\\w]+)/contextual/bha/$']

但是,如果我修改我的 contextual_main.html ,并手动传入主键,它可以工作:

<button type="button" class="btn btn-default" data-container="body" data-toggle="popover">
  <a href="{% url 'contextual:bha' pk='123412-11-33' %}">BHA</a>
</button>

似乎我必须再次传入主键,如果我想访问 http://127.0.0.1:8000/well_list/123412-11-33/contextual/bha/

当我已经在父URL中传入pk时,为什么Django让我再次传入pk?由于我已经在 well_list.html 传递了pk,这是 contextual_main.html 的父页面,我的理解是我不必再次传递它 .

有没有办法解决这个问题,比如让django从父级继承主键,或者在不重新注入主键的情况下进行操作?

1 回答

相关问题