简体   繁体   中英

Django: Fetch logged in user information from database and show them in html

I've menaged to create a form that allow me to save my website user information in the database. Right now I'd like to create a page where the saved info are showed to my user also. Of course I want my user to be able to see only their own information. This is what I came up with until now, it doesn't wotk and unfortunly I'm not getting any error, just a blanck html page aside for the title. How can I solve this? Thank you all!

model.py

class Info(models.Model):
   first_name = models.CharField(max_length=120)
   last_name = models.CharField(max_length=120)
   phone = models.CharField(max_length=10)

views.py

def show(request):
   info = Info.objects.all().filter(first_name=request.user)
   return render(request, 'profile/show.html', {'info': info})

info.html

<h1> Profile  </h1>
</br></br> 
{% if user.is_authenticated %}


{% for info in info %}

   <li>First Name: {{ info.first_name }}</li>
   <li>Last Name: {{ info.last_name }}</li>
   <li>Phone Number: {{ info.phone }}</li>


{% endfor %}
{% endif %}

request.user type is User . So when you are passing it to first_name , doesn't seem right

You can do the followings:

def show(request):
    user_first_name = request.user.first_name
    info = Info.objects.all().filter(first_name=user_first_name)
    return render(request, 'profile/show.html', {'info': info})

The filter method apply on queryset in Django return a list not an single object.

You can fix your issue like this:

def show(request):
    # You can use id to get a single user like bellow
    info_id = Info.objects.get(user_id=request.user.id)
    # Or use the `first` method of queryset to retrieve the first element in the list
    info_name = Info.objects.all().filter(first_name=request.user.first_name).first()
    return render(request, 'profile/show.html', {'info': info})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM