[Answer]-Use anchored urls in django (anchored by the id of http objects)

1πŸ‘

βœ…

I found the answer to my own question. The crucial element is that when the client (browser) goes for such an anchored url mysite.com/how_to_do_stuff#run, it sends to the server only the root url mysite.com/how_to_do_stuff and then applies the anchor to it locally. So you need:

  1. A classic, simple url/view/template combination that loads the page mysite.com/how_to_do_stuff when it is asked by the client.
  2. A way to send the client to these anchored pages and reference them for development. I do this through an other url/view couple that redirects the client to the right anchored url.

Below is the result:

In urls.py:

...
url(r'^how_to_do_stuff/(?P<part_id>[-\w]+)', views.how_to_redirect, name='how_to'),
url(r'^how_to_do_stuff', views.how_to)

In views.py:

def how_to_redirect(request, part_id):
    return HttpResponseRedirect("/how_to_do_stuff/#"+part_id)

def how_to(request):
     return render(request, "GWSite/how_to_do_stuff.html")

And then I refer to these in my templates through:

{% url "how_to" "run"}

0πŸ‘

From django project website

Take a look at how you they send the num var to views.py

# URLconf
from django.conf.urls import url

urlpatterns = [
    url(r'^blog/$', 'blog.views.page'),
    url(r'^blog/page(?P<num>[0-9]+)/$', 'blog.views.page'),
]

# View (in blog/views.py)
def page(request, num="1"):
    # Output the appropriate page of blog entries, according to num.
    ...
πŸ‘€Justin Andrew

Leave a comment