[英]dynamic url for specific primary key in Django
我的 model 有一個字段調用topic
,我想創建一個可以顯示具體內容的頁面,並且 url 可以是同一 html 模板呈現的不同主題的動態路徑。 我該怎么做?
模型.py:
TOPIC = (
(0,"Finance"),
(1,"Toys"),
(2,"Foods"),
(3,"Travel"),
)
class Post(models.Model):
name = models.CharField(max_length=200)
slug = models.SlugField(unique=True, max_length=200)
author = models.ForeignKey(User, on_delete=models.CASCADE,related_name='blog_posts')
updated_on = models.DateTimeField(auto_now= True)
created_on = models.DateTimeField(auto_now_add=True)
body = RichTextField(null=True)
status = models.IntegerField(choices=STATUS, default=0)
topic = models.IntegerField(choices=TOPIC, default=0)
cover_img = models.ImageField(upload_to='post_cover', null=True, default='post_cover/coming_soon.jpg')
def __str__(self):
return self.name
def get_img(self):
return f"{'/media/post_cover/'+self.cover_img}"
html
<div class="col-md-6 mt-3 ">
<a href="{% url 'topic_list' %}">
<img src="../media/topic/travel3.jpg" alt=''>
</a>
</div>
視圖.py
def topic_list(request):
posts = Post.objects.filter(topic=0)
context = {'posts': posts, 'autor_list':autor_list}
return render(request, 'topic_list.html', context)
網址.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
path('topic/', views.topic_list, name='topic_list'),
path('<slug:slug>/', views.post_detail, name='post_detail'),]
要在模板中生成動態 url使用 url-reversion function 和 arguments
{% for post in post_list %}
<a href="{% url 'post_detail' post.slug %}">{{ post.name}}</a>
{% endfor %}
這將從您的 urls.py 中反轉post_detail
url 模式, post.slug
值傳遞給'<slug:slug>/'
如果您需要列出每個主題的帖子,請修復您的 url 模式和如下視圖:
urlpatterns = [
...
path('topic/<int:pk>/', views.topic_post_list, name='topic-posts-list'),
]
def topic_post_list(request, pk):
posts = Post.objects.filter(topic_id=pk, )
context = {'posts': posts, }
return render(request, 'post_list.html', context)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.