how to limit the sending of emails in django

0

Good morning:

On the website that I am developing, send an email to the owner of the product every time another user puts it in favorite and I have found that if you start clicking many times it will not stop sending emails to that person with the same message, then I want to know if there is any way to control that and that I do not repeat emails at least in a period of time Appointment in block

def dar_like(request):
    producto = Producto.objects.get(id=request.GET.get('producto'))
    perfil = Perfil.objects.get(usuario = request.user)
    notificacion = Notificacion.objects.get(perfil=producto.perfil)
    data = {'mensaje':'completado'}
    if Like.objects.filter(producto=producto,perfil=perfil).exists():
        like = Like.objects.get(producto=producto)
        like.perfil.remove(perfil)
        like.save()
        json_data = json.dumps(data)
        return HttpResponse(json_data, content_type='application/json')
    else:
        like = Like.objects.get(producto=producto)
        like.perfil.add(perfil)
        like.save()
        if notificacion.nuevo_seguidor == True:
            html = render_to_string('intranet/emails/like_producto.html',{'producto':producto,'perfil':perfil})
            msg = EmailMessage('Like a un producto tuyo', html, settings.EMAIL_HOST_USER, to=[producto.perfil.usuario.email])
            msg.content_subtype = 'html'
            msg.send(fail_silently=False)
        json_data = json.dumps(data)
        return HttpResponse(json_data, content_type='application/json')

this is the code, as you can check every time it enters the condition of the if it will send an email without any control

My model is this

class Like(models.Model):
    perfil = models.ManyToManyField(Perfil, related_name='likes')
    producto = models.OneToOneField(Producto)
    
asked by F Delgado 27.12.2017 в 17:16
source

1 answer

1

You would have to persist the moment of sending the like (usually in BD) and compare each new like to see if the period of time has elapsed before sending the message .

Better option would be to count the likes during the period and send a message with the likes produced in x hours, daily, weekly, etc. giving the option to the owner of the product to select the period. Also, if you keep every like with your timestamp, you can get more complete statistics such as the hours of the day and days when a product gets more likes, it depends a little on what you want to offer.

    
answered by 28.12.2017 / 10:02
source