I am making a django website in which the homepage shows links of domains... upon clicking on each domain, you links of respective topics and upon clicking each topic you get links of respective subtopics...
The problem is that I want to extract the domains, topics, and subtopics from database using queries... which means that I cannot hardcode urlpatterns into my program...
How can I make this work so that in the homepage, I extract the list of domains... display them... and upon clicking them, extract the list of topics under them and display them on a new link...
CodePudding user response:
You can include parameters in your paths. Indeed, for example:
urlpatterns = [
path('<str:domain>/<str:topic>/<str:subtopic>/', some_view)
]
and define your view as:
def some_view(request, domain, topic, subtopic):
# …
If you then visit /science/physics/quantum/
, it will call the some_view
with domain
set to 'science'
, topic
set to 'physics'
and subtopic
set to 'quantum'
.
CodePudding user response:
A recommended pattern for Django models is to build "fat" models. In your case I would add methods to your models that return the path. This way you can also easily test the url generation.
Idea:
class Topic:
# ...
def get_absolute_url(self):
return reverse( ... )
def get_other_url(self):
return reverse( ... )