Reputation: 1579
I have 2 templates to render one listview and I am choosing the template according to the request url given by the user. I know that, I can add 2 classes for 2 templates on 2 seperate urls respectively. For example
class MyListView1(generic.ListView):
template_name = 'myapp/list_one.html'
.....
.....
class MyListView2(generic.ListView):
template_name = 'myapp/list_two.html'
.....
.....
But is there a way if I could check the url request inside one class and render the template according to it inside one listview class ? something like
class MyListView(generic.ListView):
if request.path == '/list1'
template_name = 'myapp/list_one.html'
if request.path == '/list2'
template_name = 'myapp/list_two.html'
I know this is not a valid code but just to visualise
Upvotes: 7
Views: 7552
Reputation: 56
Just pass template from urls.py like
path("/list1",views.MyListView.as_view(template_name="myapp/list_one.html"),name="list1")
path("/list2",views.MyListView.as_view(template_name="myapp/list_two.html"),name="list2")
Upvotes: 1
Reputation: 599610
Whenever you want to do something dynamic in a generic view, it needs to be in a method. This page shows the methods available for ListViews, and you can see that it includes get_template_names()
which should do exactly what you want.
An alternative though would be to have two separate view classes, each defining their own template name, that inherit from a common base class which defines the rest of the shared functionality.
Upvotes: 9