Home > Net >  Django: How render two or more FBV into one template
Django: How render two or more FBV into one template

Time:11-13

I'd like to direct more then one view to my file.html template. Unfortunly my second view function file_category doesn't render the context in my page. Is there a specific way to do so? Thanks

VIEWS

def file_view(request, file_id):  
    file = File.objects.filter(pk=file_id)
    files_p = File.objects.filter(user=request.user.userprofile)

    context = {
             'file': file,
             'files_p': files_p ,
             }
    return render(request, 'file.html', context)


def file_category(request): 
    cat = list(for num in range(0, 37)) 

    context = {
             'cat': cat
             }
    return render(request, 'file.html', context)

URLS


urlpatterns = [    
  path('show/<file_id>', views.file_view, name="file"),
  path('show/<file_id>', views.file_category),    
]

CodePudding user response:

Other than your urls being the same as Rowan said, your context on your second view only has cat and no files_p I assume you want to display file objects. So you need to pass those objects into your context on the second view, otherwise there is nothing to display. If you need to display completely different objects in your second view then better use a different template.

CodePudding user response:

You can have multiple views pointing to the same html template. So long as it handles the context variables properly.

For example the template doesn't require file as that isn't passed in the context on file_category view.

The issue here looks like it’s because you can’t have the same url pattern pointing to different views. How would it know which you wanted to use?

Try this:

path('show/<file_id>/category', views.file_category, name='file_category')
  • Related