Answer the question
In order to leave comments, you need to log in
How to pass the first object to the slug view?
Hello!
I think the task is quite trivial: when you go to a page with a menu, you need to automatically select the first menu item, highlight it as active, and display information on it.
I have implemented this logic:
url(r'^excursions$', views.excursions, name='excursions'),
url(r'^excursions/(?P<slug>[\S]+)/$', views.excursions, name='excursions')
def excursions(request, slug=None):
list_of_excursions = models.Excursion.objects.all()
if slug == None:
try:
start_value = models.Excursion.objects.all()[0]
except IndexError:
return render(request, 'ex/excursions.html', {'Error_message': 'Извините, тут пока ничего нет'})
else:
return render(request, 'ex/excursions.html', {'list_of_excursions': list_of_excursions, 'first': start_value})
else:
start_value = get_object_or_404(models.Excursion, slug=slug)
return render(request, 'ex/excursions.html', {'list_of_excursions': list_of_excursions, 'first':start_value, 'slug': slug})
{% if Error_message %}
<p>{{Error_message}}</p>
{% else %}
<div class="col-lg-2 col-md-4 col-xs-12">
<ul class="nav nav-pills nav-stacked" >
{% if slug %}
{% for ex in list_of_excursions %}
{% if ex.slug == slug %}
<li class="active"><a href="{% url 'ex:excursions' ex.slug %}">{{ex.name}}</a></li>
{% else %}
<li><a href="{% url 'ex:excursions' ex.slug %}">{{ex.name}}</a></li>
{% endif %}
{% endfor %}
{% else %}
{% for ex in list_of_excursions %}
{% if forloop.counter == 1 %}
<li class="active"><a href="{% url 'ex:excursions' ex.slug %}">{{ex.name}}</a></li>
{% else %}
<li><a href="{% url 'ex:excursions' ex.slug %}">{{ex.name}}</a></li>
{% endif %}
{% endfor %}
{% endif %}
</ul>
</div>
<div class="col-lg-10 col-md-8 col-xs-12">
<div class="center_place">
<h1>{{first.name}}</h1><br>
<p>{{first.text| safe}}</p>
</div>
</div>
{% endif %}
Answer the question
In order to leave comments, you need to log in
return render(request, 'ex/excursions.html',
{'list_of_excursions': Excursion.objects.all() })
{% for ex in list_of_excursions %}
{% if forloop.first %}
первона
{% endif %}
<a href="{{ ex.get_absolute_url }}">ex.name</a>
{% else %}
нифига нет екскурсий
{%endfor%}
r'^excursions$'
write with a slash at the end
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question