This is probably a simple answer but I cant figure it out. I have a comment system on my blog. I need to get the username from the user id.
I get the id from which is a fk to the users table
{{child_comment.parent_userdata_id}}
Usually when I need to do this I just user .username but it doesn't seem to work in this case
CodePudding user response:
The only way you can get object data from the database is to fetch it on the server-side.
Unfortunately, you can't do that on the live HTML template.
Django template is just for evaluating the pre-existing context data for better use.
So, filtering the username from user id in views (backend) and passing it via the context into the template is the only (and probably the best) option.
CodePudding user response:
Assuming user login is required to comment, you can create a variable of user = request.user in your view function, now user variable has the instance of user and pass it as context in template. It would look like this
views.py
def view_function(request):
user = request.user
# do something
context = {
'user' : user,
}
return render(request, 'template.html', context)
template.html
<p>{{user.username}}</p>