Search code examples
pythondjangopermalinks

Django url keeps duplicating(Dynamic Navigation)


class Entry(models.Model):
    ....
    slug = models.SlugField(help_text = "You do not need to change this unless you want to change the url")

class Meta:
    verbose_name_plural = "Entries"

def __unicode__(self):
    return self.title

def get_absolute_url(self):
    cat = slugify(self.category)    
    return "%s/%s/"  % (cat,self.slug)

views

def index(request):
    all_entries = Entry.objects.filter(status=1)
    treatments = all_entries.filter(category='treatments')
    female = all_entries.filter(category='female')
    male = all_entries.filter(category='male')
    work = all_entries.filter(category='work')

    return render_to_response('index.html',locals())

def entry_page(request,slug_add):
    all_entries = Entry.objects.filter(status=1)
    page = all_entries.get(slug=slug_add)

    treatments = all_entries.filter(category='treatments')
    female = all_entries.filter(category='female')
    male = all_entries.filter(category='male')
    work = all_entries.filter(category='work')
    return render_to_response('index.html',locals())

url

 url(r'^$','hypno_pages.views.index'),
 url(r'^admin/', include(admin.site.urls)),
 url(r'^$','hypno_pages.views.index'),   
 url(r'^(treatments|male|female|work)/(?P<slug_add>[a-zA-Z0-9-]+)/$','hypno_pages.views.entry_page'),

template

<div class="subnav ui-corner-all">
  <h3>xxxxx can help to treat any of the following conditions </h3>
<ul class = 'float' >       
         {% for line in treatments|slice:":5" %} 
        <li ><a href='{{line.get_absolute_url}}'>{{ line.title }}</a></li>
     {% empty %}

         {% endfor %}
    </ul>
    <ul class = 'float'>
     {% for line in treatments|slice:"5:10" %}
        <li ><a href="{{line.get_absolute_url }}" >{{ line.title }}</a></li>
     {% empty %}
     {% endfor %}
</ul>
  .......

*edit*That is the template code,just truncated it,other parts are just repeated.

My issue.I have a main index page with a navigation bar that has a dropdown box with lots of links(which will be added dynamically from the database once the client adds something,Now my problem is that on the navigation link say I click on a link 'http://127.0.0.1:8000/treatments/what-to-do/' I go to a the linked page but now all the links in the navigation bar change to 'http://127.0.0.1:8000/treatments/what-to-do/treatments/what-to-do/' accrording to the particular link. I am 1 week with Django and a month with python maybe am just missing something. thanks


Solution

  • For me it looks like you should use absolute pathing in your "a hrefs", since like you use it, the link is relative and will be appended to the (url-)path your are already on,

    try <a href="/{{line.get_absolute_url }}" > instead.

    Also I would use the @pemarlink decorator for your get_absolute_url function. Have a look here.