Home > Blockchain >  django How get creator username instead id using two for
django How get creator username instead id using two for

Time:10-04

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 %}

CodePudding user response:

you should do it in this way:

{{ item.r.creator.username }}

CodePudding user response:

Per your comment the answer was to use the Foreign Key mapping 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 their default model stores username, so from that your username attr can be accessed from your creator instance. Overall your template call should have been:

{{ item.r.creator.username }}

  • Related