Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django embedding user id into URL template best practice

Tags:

python

django

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?

like image 233
randombits Avatar asked Mar 01 '23 00:03

randombits


1 Answers

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.

like image 85
hora Avatar answered Mar 07 '23 11:03

hora