import copy
from django import forms
from django.contrib import admin
from django.core.urlresolvers import reverse
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _
from orchestra.admin import ExtendedModelAdmin, ChangePasswordAdminMixin
from orchestra.admin.utils import admin_link, change_url
from orchestra.apps.accounts.admin import SelectAccountAdminMixin, AccountAdminMixin
from .filters import HasMailboxListFilter, HasForwardListFilter, HasAddressListFilter
from .forms import MailboxCreationForm, MailboxChangeForm, AddressForm
from .models import Mailbox, Address, Autoresponse
class AutoresponseInline(admin.StackedInline):
model = Autoresponse
verbose_name_plural = _("autoresponse")
def formfield_for_dbfield(self, db_field, **kwargs):
if db_field.name == 'subject':
kwargs['widget'] = forms.TextInput(attrs={'size':'118'})
return super(AutoresponseInline, self).formfield_for_dbfield(db_field, **kwargs)
class MailboxAdmin(ChangePasswordAdminMixin, AccountAdminMixin, ExtendedModelAdmin):
list_display = (
'name', 'account_link', 'filtering', 'display_addresses'
)
list_filter = (HasAddressListFilter, 'filtering')
add_fieldsets = (
(None, {
'fields': ('account', 'name', 'password1', 'password2', 'filtering'),
}),
(_("Custom filtering"), {
'classes': ('collapse',),
'fields': ('custom_filtering',),
}),
)
fieldsets = (
(None, {
'fields': ('name', 'password', 'is_active', 'account_link', 'filtering'),
}),
(_("Custom filtering"), {
'classes': ('collapse',),
'fields': ('custom_filtering',),
}),
(_("Addresses"), {
'fields': ('addresses_field',)
}),
)
readonly_fields = ('account_link', 'display_addresses', 'addresses_field')
change_readonly_fields = ('name',)
add_form = MailboxCreationForm
form = MailboxChangeForm
def display_addresses(self, mailbox):
addresses = []
for addr in mailbox.addresses.all():
url = change_url(addr)
addresses.append('%s' % (url, addr.email))
return '
'.join(addresses)
display_addresses.short_description = _("Addresses")
display_addresses.allow_tags = True
def get_fieldsets(self, request, obj=None):
""" not collapsed filtering when exists """
fieldsets = super(MailboxAdmin, self).get_fieldsets(request, obj=obj)
if obj and obj.filtering == obj.CUSTOM:
fieldsets = copy.deepcopy(fieldsets)
fieldsets[1][1]['classes'] = fieldsets[0][1]['fields'] + ('open',)
return fieldsets
def addresses_field(self, mailbox):
""" Address form field with "Add address" button """
account = mailbox.account
add_url = reverse('admin:mailboxes_address_add')
add_url += '?account=%d&mailboxes=%s' % (account.pk, mailbox.pk)
img = ''
onclick = 'onclick="return showAddAnotherPopup(this);"'
add_link = '{img} Add address'.format(
add_url=add_url, onclick=onclick, img=img)
value = '%s
' % add_link
for pk, name, domain in mailbox.addresses.values_list('pk', 'name', 'domain__name'):
url = reverse('admin:mailboxes_address_change', args=(pk,))
name = '%s@%s' % (name, domain)
value += '