Reputation: 33
I'm starting a data analysis project in django and want to show text data and graph data in single tamplate which are generated from different views. Is it a good practice to do this way or I should rander two different template for text data and graph data?
Upvotes: 2
Views: 1996
Reputation: 37319
It's possible. A view is responsible for creating a response based on the request and returning it, and can use whatever approach makes sense to do so. A template is one tool to do so, and nothing stops you from using a given template in multiple views. If you're using functional views, it might look something like this:
def display_text(request):
context = ...
return render(request, "data.html", context)
def display_graph(request):
context = ... # some different context than the text case
return render(request, "data.html", context)
The details may vary - the point is just that there's nothing tying the template to just one view.
Whether this is a good idea or not depends on how much of the template behavior is shared between your two cases. In general, I would instead recommend factoring out the shared parts of the template to a parent template and using template inheritance to specialize the different behavior that's specific to the different data types without repeating the shared parts. Even if the current display behavior is the same, using two different templates makes it easier to change that in the future should you want to.
If a single template can genuinely handle both cases without needing to determine what the data type is, and you don't anticipate changing that, it could be a reasonable choice to reuse a single template in both views rather than create type-specific ones.
Upvotes: 1
Reputation: 1024
You can use one base template, and then in a block of that template display the data
base_data.html
some html
{% block data %}
{% endblock %}
more html
text_data.html
{% extends 'base_data.html' %}
{% block data %}
html to display the text data
{% endblock %}
graph_data.html
{% extends 'base_data.html' %}
{% block data %}
html to display the graph data
{% endblock %}
views.py
def display_text_data(request):
# your code
return render(request, 'text_data.html', context)
def display_grapth_data(request):
# your code
return render(request, 'graph_data.html', context)
I don't know exactly if you want the above or if you want in one html display the two, text and graph, is is the second it will be:
data.html
display text_data using textdata context
display graph data using graphdata context
views.py
def show_data(request):
textdata = # get text data context
graphdata = # get graph data context
return render(request, 'data.html', context={'textdata': textdata, 'graphdata': graphdata}
Upvotes: 0