【问题标题】:Django - Reverse for 'contextual' with keyword arguments '{'api': ''}' not foundDjango - 使用关键字参数'{'api':''}'的'contextual'反向
【发布时间】:2018-12-28 03:02:45
【问题描述】:

models.py

from django.db import models
from django.urls import reverse


# Create your models here.
class WellInfo(models.Model):
    api = models.CharField(max_length=100, primary_key=True)
    well_name = models.CharField(max_length=100)
    status = models.CharField(max_length=100)
    phase = models.CharField(max_length=100)
    region = models.CharField(max_length=100)
    start_date = models.CharField(max_length=100)
    last_updates = models.CharField(max_length=100)

    def __str__(self):
        return self.well_name

views.py

class ContextualMainView(TemplateView):
    template_name = 'contextual_main.html'


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'] = [[getattr(instance, field) for field in context['fields']] for instance in context['well_info']]

        return context

html

<thead>
  <tr>
    {% for field in fields %}
    <th>{{ field }}</th>
    {% endfor %}
  </tr>
</thead>
<tbody>
  {% for well in well_info %}
  <tr>
    {% for value in well %}
    <td><a href="{% url 'eric_base:contextual' api=well.api %}">{{ value }}</a></td>
    {% endfor %}
  </tr>
  {% endfor %}
</tbody>

app/urls.py

from django.urls import re_path, include
from django.contrib.auth import views as auth_views
from eric_base import views as base_views

app_name = 'eric_base'

urlpatterns = [

        re_path(r'^(?P<api>\d+)/$', base_views.ContextualMainView.as_view(), name='contextual'),

]

在我的models.py 中,我将api 设置为主键,并希望使用api 作为唯一的url 标识符,并将其附加到url 的末尾,如下所示:

http://127.0.0.1:8000/well_list/contextual/api_number_1
http://127.0.0.1:8000/well_list/contextual/api_number_2
http://127.0.0.1:8000/well_list/contextual/api_number_3

我想我在views.pymodels.py 中遗漏了一些东西,但我不知道它是什么。我该如何解决这个问题?

【问题讨论】:

    标签: django django-models django-views django-urls


    【解决方案1】:

    您的正则表达式(?P&lt;api&gt;\d+) 是一个数字,但api 字段是CharField

    试试(?P&lt;api&gt;.+),它会匹配所有内容,而不仅仅是数字。

    【讨论】:

    • 这并没有解决我的问题。然后我收到此错误:Reverse for 'contextual' with keyword arguments '{'api': ''}' not found。尝试了 1 种模式:['well_list\\/contextual/$(?P.+)/$']
    • 啊,如果您查看关键字参数,这意味着您正在使用空字符串调用{% url %}。你确定well.api 是一个东西吗?
    猜你喜欢
    • 2018-12-28
    • 1970-01-01
    • 2014-07-23
    • 2013-08-21
    • 1970-01-01
    • 1970-01-01
    • 2013-10-20
    • 2014-11-25
    • 2021-07-20
    相关资源
    最近更新 更多