tags:

views:

130

answers:

3

I'm building a navigation menu in my django app, and one of the options is "My Account". There are different roles I have for users, but in order for them all to view their profile, I use a generic URL such as http://mysite/user//profile.

What's a Django best practice for building this url using templates?

Is it simply something like:

<a href="/user/{{ user.id }}/profile">My Account</a>

Or is it:

<a href="{{ url something something }}">My Account</a>

Not entirely sure what the appropriate syntax for using the url template tag is. Here's what my URLconf looks like:

(r'^user/(?P<user_id>\d+)/profile/$', user_profile)

What's my best bet?

A: 

Your first try matches the url listed in your URLconf. I'd also use that aproach.

Juanjo Conti
+5  A: 

Look into named URLs, you can find the official django documentation here.

Basically you can name your URLs in your URL conf as such:

url(r'^user/(?P<user_id>\d+)/profile/$', 'yourapp.views.view', name='user_url')

And then in any template, you can do this:

<a href="{% url user_url user.id %}">

However, this will make your URL structure pretty ugly, and there are better ways of doing this. For example you could just go to /profile/ and the userid is retrieved from the current session (each request has a 'user' attribute, use it). So for example, in your view you can do this:

def myview(request):
    user = request.user

And subsequently you can use that information to do what you want. Much nicer than using ids in the URL and you don't have to worry about any other security issues that might involve.

hora
+2  A: 

Easiest way - define a get_absolute_url method in your model and use that, in conjunction with the permalink decorator if you like.

Daniel Roseman
i wanted to say the same, so here is the link: http://docs.djangoproject.com/en/dev/ref/models/instances/#the-permalink-decorator I highly recommend the decorator
vikingosegundo