From 92c6b39e129f865be647b06ae07dc7b56b583254 Mon Sep 17 00:00:00 2001 From: Jan Dittberner Date: Sat, 27 Dec 2014 00:24:05 +0100 Subject: [PATCH] implement automatic creation of mailbox names - create mailbox name when saving new mailboxes in admin - add MailboxManager that implement get_next_mailbox_name as manager for Mailbox --- docs/changelog.rst | 1 + gnuviechadmin/managemails/admin.py | 4 +++- gnuviechadmin/managemails/models.py | 20 ++++++++++++++++++++ 3 files changed, 24 insertions(+), 1 deletion(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 1ced26c..6dc9fdf 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -1,6 +1,7 @@ Changelog ========= +* :feature:`-` automatic creation of mailbox names from user names * :bug:`-` fix broken mailbox admin * :release:`0.2.3 <2014-12-26>` diff --git a/gnuviechadmin/managemails/admin.py b/gnuviechadmin/managemails/admin.py index aea5995..d1ddbdb 100644 --- a/gnuviechadmin/managemails/admin.py +++ b/gnuviechadmin/managemails/admin.py @@ -67,6 +67,8 @@ class MailboxCreationForm(forms.ModelForm): """ mailbox = super(MailboxCreationForm, self).save(commit=False) + mailbox.username = Mailbox.objects.get_next_mailbox_name( + mailbox.osuser) mailbox.set_password(self.cleaned_data['password1']) if commit: mailbox.save() @@ -118,7 +120,7 @@ class MailboxAdmin(ActivationChangeMixin, admin.ModelAdmin): add_fieldsets = ( (None, { 'classes': ('wide',), - 'fields': ('osuser', 'username', 'password1', 'password2')}), + 'fields': ('osuser', 'password1', 'password2')}), ) search_fields = ('username',) ordering = ('username',) diff --git a/gnuviechadmin/managemails/models.py b/gnuviechadmin/managemails/models.py index 425d79f..8ea4da0 100644 --- a/gnuviechadmin/managemails/models.py +++ b/gnuviechadmin/managemails/models.py @@ -20,12 +20,32 @@ class ActivateAbleMixin(models.Model): abstract = True +class MailboxManager(models.Manager): + + def get_next_mailbox_name(self, osuser): + count = 1 + mailboxformat = "{0}p{1:02d}" + mailboxname = mailboxformat.format(osuser.username, count) + + for box in self.values('username').filter(osuser=osuser).order_by( + 'username' + ): + if box['username'] == mailboxname: + count += 1 + mailboxname = mailboxformat.format(osuser.username, count) + else: + break + return mailboxname + + @python_2_unicode_compatible class Mailbox(ActivateAbleMixin, TimeStampedModel, models.Model): osuser = models.ForeignKey(OsUser) username = models.CharField(max_length=128, unique=True) password = models.CharField(max_length=255) + objects = MailboxManager() + class Meta: verbose_name = _('Mailbox') verbose_name_plural = _('Mailboxes')