问题
I'm trying to create a submenu for a sports site. Each sport would need its own submenu. The problem I'm having is I need the namespace itself to be dynamic in someway.
SportListView returns the sport so I can then filter the news articles by the sport.
Views:
class SportListView(ListView):
template_name="sports/sport-home.html"
context_object_name='sport_list'
def get_context_data(self, **kwargs):
context = super(SportListView, self).get_context_data(**kwargs)
context['sport_menu'] = get_object_or_404(Sport,
sport_slug=self.kwargs['sport_slug'])
return context
Template:
<nav class="navbar navbar-expand-lg main-nav">
<a href="{% url 'sports:sport-home' sport_menu.sport_slug %}">
{{sport_menu.name}}</a>
<a href="{% url sport_menu.sport_slug 'monthly' %}">Monthly View</a>
</nav>
The first link in the submenu works fine. As you can see it effectively acts as a home button for each sport.
The second link does not on the other hand. In the error message it returns the slug of the sport but I can't get that to act as the namespace.
I do have an app and its URLs.py file configured correctly for the current sport as well by the way. So I know that isnt the problem.
edit:
Current error message I'm getting withi this configuration is:
Reverse for 'cricket' not found. 'cricket' is not a valid view function or pattern name.
回答1:
You can use the add template filter:
<a href="{% url sport_menu.sport_slug|add:':monthly' %}">Monthly View</a>
来源:https://stackoverflow.com/questions/47755463/django-using-a-variable-as-the-url-namespace