Django - Upload image is not working

Asked

Viewed 21 times

0

On the site already have some questions related to this, but none of them solved my problem in fact.

I have a table in the database with a FK table User, in this table I put my image that would be the profile image of the user.

Models py.

class UserProfile(models.Model):
user   = models.OneToOneField(User, on_delete=models.CASCADE)
avatar = models.ImageField(upload_to='profile_image', null=True, blank=True)

def __str__(self):
    return str(self.user.first_name)

Views.py

@login_required()
def editaFoto(request, id):
    data = {}
    foto = UserProfile.objects.get(user_id=id)
    form = UserProfileForm(request.POST or None, instance = foto) # inicia um formulario com os campos preenchidos
    data['foto'] = foto
    data['form'] = form

    if request.method == 'POST':
        if form.is_valid():
            form.save()
            return redirect('lista_perfil')
    else:
        return render(request, 'sistema/perfil/editafoto.html', data)

Forms py.

class UserProfileForm(ModelForm):
    class Meta:
        model = UserProfile
        fields = '__all__'

Editafoto.html

{% extends "base.html" %}

{% load bootstrap %}

{% block title %}
    Editar Foto
{% endblock title %}

{% block main %}    
    <div class="container">
        <h3>Editar Foto</h3>
        <div class="row">
            <div class="col-sm-6">
                {{ foto }}
                <form action="{% url 'edita_foto' user.id %}" method="POST">
                    {% csrf_token %}
                    {{ form | bootstrap}}
                    <button type="submit" class="btn btn-success">Salvar</button>
                    <a href="{% url 'lista_perfil' %}" class="btn btn-danger">Cancelar</a>
                </form>
            </div>
        </div>
    </div>
{% endblock main %}

Base.html

{% load static %}
<!DOCTYPE html>
<html lang="pt">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="icon" type="imagem/png" href="{% static 'img/icone.jpg' %}" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="{% static 'css/menu.css' %}">
    {% block scripts %} {% endblock scripts %}
    {% block style %} {% endblock style %}
    <title>{% block title %}  {% endblock title %}</title>
</head>
<body>
    <nav class="navbar navbar-expand-lg bg-dark navbar-dark" style="margin-bottom:20px">
        <a class="navbar-brand" href="#">Sistema</a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarNav">
            <ul class="nav navbar-nav">
                <li class="nav-item active">
                    <a class="nav-link" href="{% url 'lista_consultas' %}">Consultas<span class="sr-only">(current)</span></a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="{% url 'lista_medicos' %}">Medicos</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="{% url 'lista_pacientes' %}">Pacientes</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="{% url 'lista_especialidades' %}">Especialidades</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="{% url 'cadastra_usuario' %}">Usuários</a>
                </li>
            </ul>
            <ul class="nav navbar-nav ml-auto">
                {% if user.userprofile.avatar == "" %}
                    <img src="{% static 'img/user-anonimo-clinica.jpg' %}" style="border-radius: 100%; margin-top: .5rem;" width="30" height="30" alt="user">
                {% else %}
                    <img src="{{ user.userprofile.avatar.url }}" style="border-radius: 100%; margin-top: .5rem;" width="30" height="30" alt="user">
                {% endif %}
                <li class="nav-item dropdown ">
                    {% if user.is_authenticated %}
                        <a class="nav-link dropdown-toggle" href="#" id="navbardrop" data-toggle="dropdown">
                            {{user}}
                        </a>
                        <div class="dropdown-menu dropdown-perfil">
                            <a class="dropdown-item" href="{% url 'lista_perfil' %}">Meu Perfil</a>
                            <a class="dropdown-item" href="{% url 'logout' %}">logout</a>
                        </div>
                    {% endif %}
                </li>
            </ul>
                <!--
                {% if user.is_authenticated %}
                    <li class="nav-item">
                        <a class="nav-link disabled" href="">Olá {{user}}</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link disabled" href="{% url 'logout' %}">logout</a>
                    </li>
                {% else %}
                    <li class="nav-item">
                        <a class="nav-link disabled" href="{% url 'login' %}">login</a>
                    </li>
                {% endif %}-->

        </div>
    </nav>

    <div style="margin-bottom: 40px">
        {% block main %}
        {% endblock %}
    </div>

    <footer class="footer " style="height:20px;width: 100%; background-color:#000; position: fixed; margin:auto; bottom:0">

    </footer>
</body>

This current code of mine works very well when I use Django admin. If I log into Django admin and add an image to a user, the image appears in the system normally.

However I wanted to add the user profile image by my system, but when I go on the page editafoto.html and give a Ubmit, it does not save in the database the new image, no error appears, it just does not save and nothing happens.

Someone would show me where I’m going wrong?

  • 1

    Your mistake is in the method of POST in edit foto.html. I answered an identical question to this, here.

  • Sidon, Thank you very much, solved my problem, I came to see these posts that you mentioned, but as I had said did not solve my problem. This time reading your comment and redoing I managed to resolve, thank you very much!

  • If I can give you a hint, instead of using models.ImageField, use Vesatileimagefield, easier to use, allows Crop and even filter application on images.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.