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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With