现在我的网址是:https://mywebsite.com/newscategory_lists-5
我想将其更改为:https://mywebsite.com/categoryname
这是我的模特:
class Category(models.Model):
name = models.CharField(max_length=40) # 分类名
class Meta:
verbose_name = "分类"
verbose_name_plural = verbose_name
def __str__(self):
return self.name
这是urls.py:
path('category_lists-<int:category_pk>', views.categoryNewsList, name="category_news_list"),
这是我的view.py:
def categoryNewsList(request, category_pk):
category = get_object_or_404(Category, pk=category_pk)
news_list = News.objects.filter(category=category)
return render(request, "categories_list.html", {
'news_list': news_list,
'category': category
})
答案 0 :(得分:0)
尝试一下, 在url.py
中url(r'^(?P<link>[\w|-]+)/$', views.categoryNewsList, name='categoryNewsList')
view.py
def categoryNewsList(request, link):
categories = {
"graphics-design": "GD",
"digital-marketing": "DM",
"video-animation": "VA",
"music-audio": "MA",
"programming-tech": "PT"
}
try:
foos = Category.objects.filter(name=categories[link])
return render(request, 'yoursite/home.html', locals())
except KeyError:
return redirect('yoursite/home.html')
,然后在您的template.html上放置链接:
<nav class="navbar navbar-expand-sm bg-light navbar-light justify-content-center">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="/">All categories</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/graphics-design">Graphics & Design</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/digital-marketing">Digital Marketing</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/video-animation">Video & Animation</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/music-audio">Music & Audio</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/programming-tech">Programming & Tech</a>
</li>
</ul>