Django Url, Slug для Детальной Страницы

У меня проблемы с настройкой моего URL для отображения подробного представления. Нажав на эту ссылку: <a href='{% url blog_detail blog.slug %}'>{{ blog.name }}</a> шоу blog.htmlкогда я думал, что это покажет blog-detail.html, Там нет ошибок, и панель браузера говорит: example.com/blog/the-slug, но по-прежнему отображает HTML из blog.htmlне blog-detail.html, Есть идеи почему? Спасибо за ваши идеи.

URL:

url(r'^blog/', 'myapp.views.blog', name='blog'),
url(r'^blog/(?P<slug>[\w-]+)/$', 'myapp.views.blog_detail', name='blog_detail'),

Просмотры:

def blog(request):
    blog_list = Blog.objects.all()
    return render(request, 'blog.html', {'blog_list':blog_list})

def blog_detail(request, slug):
    blog = get_object_or_404(Blog, slug=slug)
    return render(request, 'blog-detail.html', {'blog':blog})

РЕДАКТИРОВАТЬ: вывод запрашивается @omouse

Это результат нажатия на ссылку. Это точно так же, как blog.html, но это должно быть blog-detail.html, Argggg!

<div id='content-wrapper'>
<section>
<div class='blog-name'><h2><a href='/blog/test/'>Test</a></h2></div>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry&#39;s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a ...

<div class='blog-name'><h2><a href='/blog/second-test/'>Second Test</a></h2></div>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry&#39;s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a ...
</section>
</div>

1 ответ

Решение

URL-адреса являются проблемой, первый будет соответствовать всем (/blog/, /blog/test/, /blog/awdlawdjaawld), вам нужен знак доллара $ в конце этого, чтобы соответствовать /blog/,

url(r'^blog/$', 'myapp.views.blog', name='blog'),
url(r'^blog/(?P<slug>[\w-]+)/$', 'myapp.views.blog_detail', name='blog_detail'),

Выше должно работать правильно.

Это хорошая ссылка для регулярных выражений

Рудольф абсолютно прав

В /$ остановил блог от перехвата всех подстраниц, вызываемых слагом, поэтому, если у вас есть подстраницы, вам нужно добавить /$ на уровень папки следующим образом:

re_path('brands/$', AllBrands.as_view(), name="brands"),
re_path(r'^brands/(?P<slug>[\w-]+)/$', BrandDetail.as_view(), name = 'brandetail'),

Это django 2.2

Без /$ после брендов на странице-ярлыке отображалась страница со списком брендов.

Другие вопросы по тегам