[Fixed]-How do I get username by user_id in Django?

1👍

It’s better if you have a ForeignKey to User in your Entries model

from django.contrib.auth.models import User
class Entries(models.Model):
    user = models.ForeignKey(User) # instead of user_id = IntegerField()

If you don’t want that, you can add a property to your model

from django.contrib.auth.models import User
class Entries(models.Model):
    @property
    def user(self):
        return User.objects.get(pk=self.user_id)

This property makes the user available as entry.user as if it were an attribute, so:

{% for entry in entries %}
    {{ entry.user.username }}
{% endfor %}
👤bakkal

Leave a comment