Z
Z
zelsky2015-04-22 16:30:54
Django
zelsky, 2015-04-22 16:30:54

How to check Request.path in Django?

Here is the urls.py code

url(r'^category/(?P<cat_id>\d+)$',  'adst.views.alboms', name='Albom'),

It is necessary to check for this url and add a class to the activate link
Tried like this. Did not help.
{% for cat in categor %}
          <li  {% if  cat.id_cat in request.path %}class="active"{% endif %} >
             <a href="{% url "Albom" cat.id_cat %}">{{ cat.Name_cat }}</a>
             <span class="sr-only">(current)</span>
              </li>
              {% endfor %}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
marazmiki, 2015-04-22
@marazmiki

And exactly id_cat? By default, dzhang does something completely different. Typically, models have a primary key called id . Or, if a non-standard name is used, it can be referred to via the pk alias .
Thus, if I correctly understood that we are talking about enumeration of the queriset, then the condition should look something like this:
Not the most, I must say, a good solution. It would be more correct, for example, to implement the get_absolute_url() method on the model and compare request.path with it in a loop.

R
Roman Kitaev, 2015-04-22
@deliro

id_alb = models.AutoField(primary_key=True)- bad practice. For what purpose did you change the standard id to exactly the same, but named id_alb?
In general, this is not the only remark to your code. Your URL is called with a capital letter and, in general, is called Russian transliteration (very bad practice). {% url 'Albom' cat.id_cat %} should be replaced with {{ cat.get_absolute_url }} and, accordingly, add the Cat model method to models.py:

# В начале:
from django.core.urlresolvers import reverse
# Метод модели:
def get_absolute_url(self):
    return reverse('name_of_your_detail_view_for_cutties', args=[self.pk])

The name of the field cat.Name_cat is a duplication + a capital letter in the variable (and you need cat.name). Regular expressions in URLs must end with /$, not just $. In general, it's up to you, but I advise you to read PEP8.
The answer to your question is much simpler:
$(function(){
  function stripTrailingSlash(str) {
    if(str.substr(-1) == '/') {
      return str.substr(0, str.length - 1);
    }
    return str;
  }

  var url = window.location.pathname;
  var activePage = stripTrailingSlash(url);

  $('.nav li a').each(function(){
    var currentPage = stripTrailingSlash($(this).attr('href'));

    if (activePage == currentPage) {
      $(this).parent().addClass('active');
    }
  });
});

V
Vladisus, 2015-04-22
@Vladisus

I advise you to look at django-activelink

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question