开发者

django embedding user id into URL template best practice

开发者 https://www.devze.com 2022-12-13 01:28 出处:网络
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'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?


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.


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号