小能豆

Django-Python:The user image is not displayed on the user page when logged in with user details

py

When a user logs in, I want to see their profile picture if they have one; if not, the default profile picture should be displayed.

Here is my view.py

def header(request):
    if request.session.has_key('id'):
        user_id = request.session['id']
        user = registertb.objects.get(id=user_id)
        return render(request, 'headerfooter.html', {'user_image': user})
    else:
        return render(request, 'headerfooter.html')`
```


HTML CODE

```
<li>

    <p style="width:30px; height:30px; margin-left: 200px; margin-top: 10px;color: black;">{{ i.User_name }}</p>
    {% if user.user_image %}
        <img src="{{ i.user_image.url }}" style="height: 50px; width: 50px;" alt="Default Image">
    {% else %}
        <img src="/media/image/New folder/default-avatar-profile.jpg" style="height: 50px; width: 50px;" alt="Default Image">
    {% endif %}
 </li>`
```

 models.py

```
class registertb(models.Model):
    User_name=models.CharField(max_length=300)
    User_email=models.CharField(max_length=300)
    user_image=models.ImageField(upload_to='image/')
    password=models.CharField(max_length=400)
    conf_password=models.CharField(max_length=300)
`
```

阅读 71

收藏
2023-11-24

共1个答案

小能豆

It looks like you’re trying to display the user’s profile picture if it exists, and a default image if it doesn’t. The issue might be in how you’re passing the user object to the template.

In your header view, you are passing the user object with the key 'user_image'. However, in your template, you are checking if user.user_image, which may not be correct if the user object is passed with a different key.

Let’s update your view to pass the user object with the key 'user':

def header(request):
    if request.session.has_key('id'):
        user_id = request.session['id']
        user = registertb.objects.get(id=user_id)
        return render(request, 'headerfooter.html', {'user': user})
    else:
        return render(request, 'headerfooter.html')

Now, in your template, you can check if user.user_image exists:

<li>
    <p style="width:30px; height:30px; margin-left: 200px; margin-top: 10px;color: black;">{{ user.User_name }}</p>
    {% if user.user_image %}
        <img src="{{ user.user_image.url }}" style="height: 50px; width: 50px;" alt="Profile Image">
    {% else %}
        <img src="/media/image/New folder/default-avatar-profile.jpg" style="height: 50px; width: 50px;" alt="Default Image">
    {% endif %}
</li>

This should correctly display the user’s profile picture if it exists and the default image if it doesn’t.

2023-11-24