如何在Django中创建详细信息路径

时间:2018-02-09 17:03:16

标签: python django

我想在Django中创建详细信息路径。我创建了一个类别和子类别目录,之后我将子类别放入帖子中。我想创建我的路径,如 localhost / category / subcategory / detail_page.html ,其中category是类别slug,子类别是子类别的slug。 在那一刻,我的应用创建路径,如 localhost / detail_page.html 怎么做?

views.py

from django.shortcuts import render, get_object_or_404
from .models import Kategoria, Firma


def strona_glowna(request):
    kategorie = Kategoria.objects.filter(parent=None).order_by('name')
    firmy = Firma.objects.all().order_by('publish')[:5]
    context = {'kategorie': kategorie, 'firmy': firmy}
    return render(request, 'ogloszenia/index.html', context=context)

def detale_firmy(request, slug):
    detale_firmy = get_object_or_404(Firma, slug=slug)
    return render(request, 'ogloszenia/detale_firmy.html', {'detale_firmy':detale_firmy})

urls.py:

    from django.urls import path
    from . import views

    urlpatterns = [
        path('', views.strona_glowna, name='strona_glowna'),
        path('<slug>', views.detale_firmy, name='detale_firmy'),

    ]

index.html

    {% for kategoria in kategorie %}
        <li>
            <b>{{kategoria.name}}</b>
            {% if kategoria.children.count > 0 %}
                <ul>
                    {% for sub in kategoria.children.all %}
                        <li>{{ sub.name }}</li>
                    {% endfor %}
                </ul>
            {% endif %}
        </li>
    {% endfor %}
</ul>
</div>
<div class="col-2">
Ostatio dodane:<br>


{% for firma in firmy %}

<strong>{{firma.title}}</strong><br>
<a href="{% url 'detale_firmy' slug=firma.slug %}"><img src="http://free.pagepeeker.com/v2/thumbs.php?size=m&url={{firma.www}}"/><br></a>

1 个答案:

答案 0 :(得分:0)

我建议您在应用中使用{"$schema": ... views.py,如果没有,则在您的主网址中添加urls.py行,如下所示:

(让我使用应用名称,例如你的views.py,urlpatterns名称)

/project_name/urls.py

app_firma

并在 /app_firma/views.py 中将方法更改为:

from app_firma.views import detale_firmy

urlpatterns = [
    path('admin/', admin.site.urls),
    ...
    path('<slug:category_slug>/<slug:subcategory_slug>/', detale_firmy, name='detale_firmy'),
    ...
]

现在,即使未在最后指定def detale_firmy(request, category_slug, subcategory_slug): ... use the category and subcategory slugs there ... return render(request, 'ogloszenia/detale_firmy.html', {'detale_firmy':detale_firmy}) ,您也可以访问localhost:8000/<category_slug>/<subcategory_slug>/处的detale_firmy。