Python-django url with two slugs

2019-09-17 08:44发布

Hello I have a problem while I am trying two slugs in one url. I have:

html file:

<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 file

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)

and my url patterns:

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

But I get:

Page not found (404)

And I cant see where is the mistake!

1条回答
Rolldiameter
2楼-- · 2019-09-17 08:59

This is how I fixed it:

in the html file:

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

my views.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)

and my url file:

url(r'^plants/(?P<slug>[-\w]+)/inspection(?P<inspection_id>[0-9]+)/create_recording$', views.create_recording, name='create_recording'),
查看更多
登录 后发表回答