Python-django url with two slugs

偶尔善良 提交于 2019-12-12 05:29:50

问题


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:


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'),


来源:https://stackoverflow.com/questions/44038482/python-django-url-with-two-slugs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!