简体   繁体   中英

Multiple views in one url address in Django

The problem is this:

I have two classes Posts and Pubs in models.py , I need them to be displayed simultaneously on the main page, I have in views.py file:

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})

in urls.py:

    path('', views.posts_list, name='posts_list'),
#    path('', views.pubs_list, name='pubs_list'),

accordingly, if we uncomment the second condition, then the first will work.

The question is, is it possible to make 2 views have one path, or is it somehow necessary to register in the view? Thanks.

No, each URL can only be handled by one view.

For the example in your question, it would be straight forward to make a single view that fetches the posts and publications.

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})

You can use a unique view with both models:

urls.py

path('', views.posts_and_pubs, name='posts_and_pubs_list'),

views.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})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM