【问题标题】:Python-django url with two slugs带有两个蛞蝓的 Python-django url
【发布时间】:2017-05-18 04:15:41
【问题描述】:

您好,我在一个 url 中尝试两个 slug 时遇到问题。我有:

html 文件:

<div class="panel-heading">
   <h4><a class="link" href="{% url 'data:inspection_detail'
                                plant_slug=plant.slug
                                inspection_slug=inspection.slug%}">{{inspection.name}}</a></h4>
</div>

views.py 文件

def inspection_detail(request, inspection_slug, plant_slug):
    if not request.user.is_authenticated():
        return render(request, 'data/login.html')
    else:
        user = request.user
        plant = get_object_or_404(Plant, slug=plant_slug)
        inspection = get_object_or_404(Inspection, slug=inspection_slug)
        template = 'data/inspection_detail.html'
        context = {'inspection': inspection, 'user': user, 'plant':plant}
        return render(request, template, context)

和我的网址模式:

url(r'^plants/(?P<plant_slug>[-\w])/(?P<inspection_slug>[-\w]+)/$', views.inspection_detail, name='inspection_detail'),

但我明白了:

Page not found (404)

我看不出哪里错了!

【问题讨论】:

  • 回溯说什么?它指向哪条线?
  • The current URL, plants/mel-1/{% url plant.get_absolute_url}, didn't match any of these.
  • 贴出你写get_absolute_url函数的代码
  • class Plant(models.Model): ........... def get_absolute_url(self): return reverse ('data:detail', args=[self.slug]) .........
  • 您的plant_slug 捕获组只适合一个字符。

标签: python django url-pattern


【解决方案1】:

这就是我修复它的方法:

在 html 文件中:

<h4><a href="{% url 'data:inspection_detail' slug=plant.slug inspection_id=inspection.id %}" >{{inspection.name}}</a></h4>

我的意见.py

def inspection_detail(request,slug, inspection_id):
    inspection = get_object_or_404(Inspection, pk=inspection_id)
    plant = get_object_or_404(Plant, slug=slug)
    recordings = Recording.objects.filter(inspection__id=inspection_id)
    template = 'data/inspection_detail.html'
    context = {'plant': plant, 'inspection': inspection, 'recordings':recordings,}
    return render(request, template, context)

还有我的网址文件:

url(r'^plants/(?P<slug>[-\w]+)/inspection(?P<inspection_id>[0-9]+)/create_recording$', views.create_recording, name='create_recording'),

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-21
    • 2018-04-22
    • 2021-04-04
    • 2015-10-23
    • 2011-10-18
    • 2013-12-18
    • 2018-03-03
    • 1970-01-01
    相关资源
    最近更新 更多