Django embed user id in best url pattern

I am creating a navigation menu in my django application, and one of the options is “My Account”. There are different roles for users, but in order for them to view their profile, I use a common URL, for example, http: // mysite / user / / profile.

What is the best Django practice for creating this url using patterns?

It is just something like:

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

Or that:

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

Not quite sure what the appropriate syntax for using the url template tag is. This is what my URLconf looks like:

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

What is my best choice?

+4
source share
3 answers

Take a look at the named URLs, you can find django's official documentation here .

Basically you can name your urls in your url 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 to do this. For example, you can simply go to / profile / and the userid will be retrieved from the current session (each request has a user attribute, use it). So, for example, in your opinion, you can do this:

 def myview(request): user = request.user 

And later you can use this information to do what you want. Much better than using identifiers in the URL, and you don't need to worry about any other security issues that may arise.

+9
source

The easiest way is to define the get_absolute_url method in your model and use it in conjunction with the permalink decorator if you want.

+2
source

Your first attempt is the same as the URL provided in your URL. I would also use this aproach.

-2
source

All Articles