Search code examples
djangodjango-users

django How get creator username instead id using two for


I want get creator username instead id. The item.r.username dont work. item.r.bornplace work correctly. Where i do mistake?

My model.py:

class Rec(models.Model):
        creator = models.ForeignKey(auth.get_user_model(), on_delete=models.CASCADE)
        bornplace = models.CharField(default='default')

My views.py

def lists(request):
        list = Rec.objects.all()
        lists = []
        for r in list:
                lists.append({'r':r})
        context = {'lists': lists}
        return render(request, 'lists.html', context)

My lists.html

{% for item in lists %}
        {{ item.r.username }}
        {{ item.r.author_id }}
        {{ item.r.bornplace }}
{% endfor %}

Solution

  • For your issue you should use the Foreign Key mapping in the model fields you have defined from creator as defined below:

    class Rec(models.Model):
        ...
        creator = models.ForeignKey(auth.get_user_model(), on_delete=models.CASCADE)
    

    In this instance I can see you are using Django's auth, and without going into too much detail their default model stores username, so from that your username attr can be accessed from your creator instance. With that, overall your template call should have been:

    {{ item.r.creator.username }}

    But this idea is not specific to Django's auth system, for all FK relationships defined in your models you can use the standard syntax to access fields as needed, both in templates and in views.

    Models have attributes so use nested access to gather the values you need. For example:

    model.FKField.field or model.FKField.method()

    Naturally in templates there are no parentheses, so for using a method in a template the syntax is:

    {{ model.FKField.method }}