Reputation: 1329
I'm using Django to create an application with different types of words / terms. On one page, you may have the title "Terms" and then a list of terms. On another page, you have the exact same thing but for phrases (header, list of phrases).
Is it possible to do something like this -->
The hope is that I can avoid having one large template folder full of pages that are basically doing the same thing. For example, right now, if I wanted to add phrases_in_spanish and phrases_in_french, I'd have to add two new templates that are basically doing the same thing --> showing the header and the list. All I want to do is store the header and list somewhere and have Django do the rest of the work to create the pages. So I could technically have 1,000 pages without having to write 1,000 different template files that are all just showing headers and lists.
Template example:
{% extends "profile/base.html" %}
{% block content %}
<div class="row">
<div class="col-sm-6">
<a href="{% url 'profile:new_term' %}">Add a New Term</a>
<p>Terms:</p>
<ul>
{% for term in terms %}
<li><p><a href="{% url 'profile:term' term.id %}">{{ term.name }}</a> : {{ term.definition }}</p></li>
<a href="{% url 'profile:edit_term' term.id %}">Edit Term</a>
<a href="{% url 'profile:delete_term' term.id %}">Delete Term</a>
{% empty %}
<li>No terms have been added yet.</li>
{% endfor %}
</ul>
</div>
</div>
{% endblock content %}
Upvotes: 0
Views: 749
Reputation: 991
You don't have to create an html template for each page.
You have to create a URL dispatcher on urls.py
:
url(r'^(P<list_name>\w+)/$', views.your_view)
So instead of having many templates that have the same structure, you render only one with the info you want.
So your view should look like this:
def your_view(request, list_name):
list = get_object_or_404(List, pk=list_name)
context = {
'list_info':list.info
}
return render(request, 'your_app/template.html', context)
Of course in this example you need to have a table called List
on your database with primary key list_name
.
Upvotes: 2
Reputation: 16505
Maybe it would be possible to have a model called something generic like Concept
(this could be Terms or Phrases or Headers or something similar) with a related model like ConceptDetail
(which could be a list of terms or list of phrases, etc).
Then you have one URL config but different concepts have different PKs which appear in the URL to differenciate them (you can also use slugs in URL as kwargs to make the URLs more readable). For example:
path('concept/', ConceptListView.as_view()),
path('concept/<slug:concept_name>/', ConceptDetailView.as_view()),
As for views and templates, you have a ListView
that shows you all the concepts (here you can add filtering and other search options) and then in the DetailView
of each concept you could display its related ConceptDetail instances.
Does this sound like something that could help you?
Upvotes: 1