'How to render user profile (actual image) instead of filename in a Django form which basically update user-account

I am following a Django course on youtube, and I need a small change in my Django form.

The form looks like:

enter image description here

Rendering the form fields in 'edit-user.html' template:

<form action="" method="POST" enctype="multipart/form-data">
    {% csrf_token %}
    {% for field in form %}
    <div class="form-input">
        <label for="id_{{field.label}}">{{field.label}}</label>
        {{field}}
    </div>
    {% endfor %}
    <div id="lrf-options">
        <div id="lrf-btn">
            <input class="btn" type="submit" value="Update">
        </div>
    </div>
</form>

What I am actually asking: So in Avatar Currently: 1044-3840x2160.jpg, I want actual image to display here instead of <filename>.

I think maybe I need to change my forms.py to generate <img> tag instead if <a> tag but I don't know how to do this.

models.py

class UserModel(AbstractUser):
    name = models.CharField(max_length = 90)
    email = models.EmailField(unique = True)
    about = models.TextField(blank = True, null = True)
    avatar = models.ImageField(null=True, default="avatar.svg")

    USERNAME_FIELD = 'email'

and forms.py is:

class UserForm(forms.ModelForm):
    class Meta:
        model = UserModel
        fields = ['avatar', 'name', 'username', 'email', 'about']

and in views.py the update function is:

def editUserProfile(request):
    user = request.user
    form = UserForm(instance=user)
    if request.method == 'POST':
        form = UserForm(request.POST, request.FILES, instance = user)
        if form.is_valid():
            form.save()
            return redirect('chat:userProfileView', uname = user.username)

    context = {
        'form' : form
    }
    return render(request, 'chat/edit-user.html', context)


Solution 1:[1]

You can add request.user.avatar.url instead of currently url.Hide input and use jquery to give a click to input:

<div class="form-input">
    <label for="id_Avatar">Avatar</label>
    Currently:
    <img id="current-avatar" src="{{request.user.avatar.url}}"/>
    <br>
    <a id="change-avatar">Change</a>
    <input id="avatar-input" style="display:none;" type="file" name="avatar" accept="image/*" id="id_avatar">
</div>


<script>
$("#change-avatar").click(function(){
   $("#avatar-input").click();
});
</script>

If you don't have jQuery add this to your main HTML:

<head>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head> 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 enes islam