[英]Multiple views in one url address in Django
問題是這樣的:
我在models.py中有兩個類 Posts 和 Pubs ,我需要它們同時顯示在主頁上,我在views.py文件中有:
def pubs_list(request):
publications = Pubs.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
return render(request, 'app/pubs_list.html', {'publications': publications})
def posts_list(request):
posts = Posts.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
return render(request, 'app/posts_list.html', {'posts': posts})
在 urls.py 中:
path('', views.posts_list, name='posts_list'),
# path('', views.pubs_list, name='pubs_list'),
因此,如果我們取消注釋第二個條件,那么第一個條件將起作用。
問題是,是否可以讓 2 個視圖有一個路徑,或者是否有必要在視圖中注冊? 謝謝。
不可以,每個 URL 只能由一個視圖處理。
對於您問題中的示例,創建一個獲取帖子和出版物的單一視圖將是直接的。
def pubs_and_posts(request):
publications = Pubs.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
posts = Posts.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
return render(request, 'app/pubs_.html', {'publications': publications, 'posts': posts})
您可以對兩種模型使用獨特的視圖:
網址.py
path('', views.posts_and_pubs, name='posts_and_pubs_list'),
視圖.py
def posts_and_pubs(request):
posts = Posts.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
publications = Pubs.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
return render(request, 'app/posts_list.html', {'posts': posts, 'publications': publications})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.