DieStockEnte
DieStockEnte

Reputation: 3

Django: Submit button gets triggered twice

Hi, I am making currently a form where the user can edit his profile image. I am trying to delete the profile image that the user had before, after he changes his profile image to a new one. I made so far the scripts, but by the print commans I found out, my submit button(my script) get's triggered twice.

Some Informations: I am using Django 3.1 - Python 3.7.2 - JS,Bootstrap from CDN

html site code

{% extends "blog/base.html" %}
{% load crispy_forms_tags %}
{% block content %}

<div class="content-section">
    <div class="media">
        <img class="rounded-circle account-img" src="{{ user.profile.image.url }}">
        <div class="media-body">
            <h2 class="account-heading">{{ user.username }}</h2>
            <p class="text-secondary">{{ user.email }}</p>
        </div>
    </div>
    <form method="POST" enctype="multipart/form-data">
        {% csrf_token %}
        <fieldset class="form-group">
            <legend class="border-bottom mb-4">Informazioni sul profilo</legend>
            {{ u_form|crispy }}
            {{ p_form|crispy }}
        </fieldset>
        <div class="form-group">
            <button class="btn btn-outline-info" type="submit">Aggiorna</button>
        </div>
    </form>
    <!--form here-->
    </div>
{% endblock content %}

models.py

from django.db import models
from django.contrib.auth.models import User
from PIL import Image, ImageChops
import os
import time

# Create your models here.

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    image = models.ImageField(default='profile_pics/default.jpg', upload_to='profile_pics')

    def __str__(self):
        return f'{self.user.username} Profile'

    def save(self):
        super().save()

        #
        path = 'media/profile_pics/'
        media_pics = os.listdir(path)
        img = Image.open(self.image.path)

        for imgm in media_pics:
            print(imgm)
            im2 = Image.open('media/profile_pics/' + imgm)
            if list(img.getdata()) == list(im2.getdata()):
                print(imgm)
                print('Identical')
                im2.close()
                os.remove('media/profile_pics/' + imgm)
                break
            else:
                print(imgm)
                print('Different')
        #
        if img.height > 300 or img.height > 300:
            output_size = (300, 300)
            img.thumbnail(output_size)
            img.save(self.image.path)

views.py(Here gets the model.py triggered)

from django.shortcuts import render, redirect
from django.contrib import messages
from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm
from django.contrib.auth.decorators import login_required

# Create your views here.

def register(request):
    if request.method == 'POST':
        form = UserRegisterForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            messages.success(request, f'Account di {username} è stato creato!')
            return redirect('login')
    else:
        form = UserRegisterForm()
    return render(request, 'users/register.html', {'form': form})

@login_required
def profile(request):
    if  request.method == 'POST':
        u_form = UserUpdateForm(request.POST, instance=request.user)
        p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile)
        if u_form.is_valid() and p_form.is_valid():
            u_form.save()
            p_form.save()
            messages.success(request, f'Tuo account è stato aggiornato!')
            return redirect('profile')
    else:
        u_form = UserUpdateForm(instance=request.user)
        p_form = ProfileUpdateForm(instance=request.user.profile)
    context = {
        'u_form': u_form,
        'p_form': p_form,
    }

    return render(request, 'users/profile.html', context)

urls.py

from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from users import views as user_views
from django.contrib.auth import views as auth_views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('blog.urls')),
    path('register/', user_views.register, name='register'),
    path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'),
    path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'),
    path('profile/', user_views.profile, name='profile'),
]

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
-django_project
--blog (has nothing to do with this scripts up here/\)
--django_project
---__init__.py
---asgi.py
---settings.py
---urls.py
---wsgi.py
--media
---profile_pics
----(bunch of player added images)
--static
---CSS
----main.css
----JS (nothing inside)
----Images (nothing inside)
-users
--__pycache__
--migrations
--templates
---users
----profile.html
----register.html
----login.html
----logout.html
--__init__.py
--admin.py
--apps.py
--forms.py
--models.py
--signals.py
--tests.py
--views.py

Have a nice day!

Upvotes: 0

Views: 471

Answers (1)

edgars
edgars

Reputation: 1068

The submit button does not trigger twice. The prints happen in the code that loops over media pics - for imgm in media_pics: It will loop as many times as you have pictures stored in the folder media/profile_pics.

You probably want to check for old image before calling super().save(). You can get the old version by calling eg - old_profile = Profile.objects.get(pk=self.pk) and compare/delete the image (os.remove(old_profile.image.name) and then call super().save()

Upvotes: 1

Related Questions