Place a media image in the template

What I want to achieve is for the user to send their image through the form and save it in a context and display it in the template

class PerfilGestion(View):
def get(self,request,*args,**kwargs):
    return render(request,"Perfil.html",{"Form":Perfil})
def post(self,request,*args,**kwargs):
    Formulario = Perfil(request.POST, request.FILES)
    if Formulario.is_valid():
        Formulario.save()
        Imagen = Formulario.cleaned_data["Imagen"]
        Nombre = Formulario.cleaned_data["Nombre"]
        

        return render(request,"Perfil2.html",{"Imagen":Imagen,"Nombre":Nombre}) 
    else:
        return render(request,"listadeerrores.html",{"Form":Formulario})

But I don't know how to place it in the template

Just that if someone could help me I would appreciate it.

You "def get" has issues. You are passing this {"Form":Perfil}, its not mentioned anywhere. You need to fix that.

Ideally This is how you should add it in the html file. If everything is correct.

<p>Nombre: {{ Nombre }}</p>
<img src="{{ Imagen.url }}" alt="Perfil Image">

Some other config are like this

# settings.py example

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'


# urls.py exmaple
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # existing urls
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Back to Top