Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix unique constraint #23

Merged
merged 2 commits into from
May 4, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions mail_editor/migrations/0011_alter_mailtemplate_unique_together.py
Original file line number Diff line number Diff line change
@@ -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(),
),
]
19 changes: 13 additions & 6 deletions mail_editor/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand All @@ -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', {})
Expand Down