skip to Main Content

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)
`
```

2

Answers


  1. Chosen as BEST ANSWER

    Hi it's functioning now, however the default picture isn't showing up. And also I've altered my code, instead of view.py . I called context_processor.py ..

    def user_image(request): user_img = None

    if 'id' in request.session:
        user_id = request.session['id']
        try:
            user = registertb.objects.get(id=user_id)
            user_img = user.user_image.url
        except registertb.DoesNotExist:
            pass
    
    return {'user_img': user_img}
    

    def user_image(request): user_img = None


  2. It looks like there might be a mismatch between the variable names used in your view function and the variable names used in your HTML template. In your view function, you are passing the user object using the key ‘user_image’, but in your template, you are trying to access it using user.
    if you are passing ‘user_image’ should use image ‘user_image.user_image.url’ in template

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search