LoginSignup
banana_777
@banana_777

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

Djangoのユーザー認証と表示について

解決したいこと

ForeignKeyでユーザー情報を引用したモデルを作成している。このデータベースの一覧を表示させた際にIDが表示されるが、姓を表示させたい。

models.py
class note(models.Model):
    ...
    mk_user = models.ForeignKey(User,on_delete=models.CASCADE,related_name='mk_user')
    ...
views.py
def  ichiran(request):
    user = request.user
    data = note.objects.filter(mk_user=user)
    params={'data':data,'user':user}
    return render(request,'@@@',params)
html
{% for note in data %}
...
   <th> {{ note.mk_user }} </th>
...

ユーザー認証は組み込みの機能をそのまま使用しています。

これで動かすと例えば【ID:user001/姓:山田/名:太郎】で登録しログインしてデータの一覧を見た際に【user001】が表示されます。
これを【山田】を表示するにはどうすればよいでしょうか。

Choiceについては{{note.get_[note.choice]_display}}とすれば表示できることは分かったのですがユーザーについてがわからなかったので教えてください。

0

1Answer

Userモデルのlast_nameフィールドに姓が入ってます

template.html
{% for note in data %}
<th>{{note.mk_user.last_name}}</th>
{% endfor %}

もし、ログイン中のユーザ名を表示したいのであれば、userで直接表示することもできます

template.html
<th>{{user.last_name}}</th>
0

Comments

  1. @banana_777

    Questioner
    ありがとうございます!
    解決しそうです。

Your answer might help someone💌