diff --git a/mail_editor/migrations/0011_alter_mailtemplate_unique_together.py b/mail_editor/migrations/0011_alter_mailtemplate_unique_together.py new file mode 100644 index 0000000..4844508 --- /dev/null +++ b/mail_editor/migrations/0011_alter_mailtemplate_unique_together.py @@ -0,0 +1,17 @@ +# Generated by Django 3.2 on 2021-05-04 12:58 + +from django.db import migrations + + +class Migration(migrations.Migration): + + dependencies = [ + ('mail_editor', '0010_auto_20210422_1354'), + ] + + operations = [ + migrations.AlterUniqueTogether( + name='mailtemplate', + unique_together=set(), + ), + ] diff --git a/mail_editor/models.py b/mail_editor/models.py index 97d5710..60391bc 100644 --- a/mail_editor/models.py +++ b/mail_editor/models.py @@ -5,6 +5,7 @@ from tempfile import NamedTemporaryFile from django.conf import settings as django_settings +from django.core.exceptions import ValidationError from django.contrib.sites.shortcuts import get_current_site from django.core.mail import EmailMultiAlternatives from django.db import models @@ -61,7 +62,6 @@ class MailTemplate(models.Model): class Meta: verbose_name = _('mail template') verbose_name_plural = _('mail templates') - unique_together = (('template_type', 'language'), ) def __init__(self, *args, **kwargs): super(MailTemplate, self).__init__(*args, **kwargs) @@ -78,11 +78,18 @@ def __str__(self): def clean(self): validate_template(self) - def validate_unique(self, **kwargs): - if not getattr(django_settings, 'UNIQUE_LANGUAGE_TEMPLATES', True): - super().validate_unique(**kwargs, exclude=['template_type', 'language']) - else: - super().validate_unique(**kwargs) + if getattr(django_settings, 'MAIL_EDITOR_UNIQUE_LANGUAGE_TEMPLATES', True): + queryset = ( + self.__class__.objects.filter( + language=self.language, template_type=self.template_type + ) + .values_list('pk', flat=True) + ) + + if queryset.exists() and not (self.pk and self.pk in queryset): + raise ValidationError( + _('Mail template with this type and language already exists') + ) def render(self, context, subj_context=None): base_context = getattr(django_settings, 'MAIL_EDITOR_BASE_CONTEXT', {})