# coding: utf-8
from django.contrib import admin
from gestioncof.models import *
from gestioncof.petits_cours_models import *
from django.contrib.auth.models import User
from django.contrib.auth.admin import UserAdmin
from django.core.urlresolvers import reverse
from django.utils.safestring import mark_safe
import django.forms as forms
#import eav.admin
from django.utils.translation import ugettext_lazy as _
from django.contrib.admin import SimpleListFilter
from django.db.models import Q
def add_link_field(target_model = '', field = '', link_text = unicode, desc_text = unicode):
def add_link(cls):
reverse_name = target_model or cls.model.__name__.lower()
def link(self, instance):
app_name = instance._meta.app_label
reverse_path = "admin:%s_%s_change" % (app_name, reverse_name)
link_obj = getattr(instance, field, None) or instance
if not link_obj.id:
return ""
url = reverse(reverse_path, args = (link_obj.id,))
return mark_safe("%s" % (url, link_text(link_obj)))
link.allow_tags = True
link.short_description = desc_text(reverse_name + ' link')
cls.link = link
cls.readonly_fields = list(getattr(cls, 'readonly_fields', [])) + ['link']
return cls
return add_link
class SurveyQuestionAnswerInline(admin.TabularInline):
model = SurveyQuestionAnswer
@add_link_field(desc_text = lambda x: "Réponses", link_text = lambda x: "Éditer les réponses")
class SurveyQuestionInline(admin.TabularInline):
model = SurveyQuestion
class SurveyQuestionAdmin(admin.ModelAdmin):
inlines = [
SurveyQuestionAnswerInline,
]
class SurveyAdmin(admin.ModelAdmin):
inlines = [
SurveyQuestionInline,
]
class EventOptionChoiceInline(admin.TabularInline):
model = EventOptionChoice
@add_link_field(desc_text = lambda x: "Choix", link_text = lambda x: "Éditer les choix")
class EventOptionInline(admin.TabularInline):
model = EventOption
class EventCommentFieldInline(admin.TabularInline):
model = EventCommentField
class EventOptionAdmin(admin.ModelAdmin):
inlines = [
EventOptionChoiceInline,
]
class EventAdmin(admin.ModelAdmin):
inlines = [
EventOptionInline,
EventCommentFieldInline,
]
#from eav.forms import BaseDynamicEntityForm
#class CofProfileInline(eav.admin.BaseEntityInline, admin.StackedInline):
class CofProfileInline(admin.StackedInline):
model = CofProfile
#form = BaseDynamicEntityForm
inline_classes = ("collapse open",)
class FkeyLookup(object):
def __init__(self, fkeydecl, short_description=None, admin_order_field=None):
self.fk, fkattrs = fkeydecl.split('__', 1)
self.fkattrs = fkattrs.split('__')
self.short_description = short_description or self.fkattrs[-1]
self.admin_order_field = admin_order_field or fkeydecl
def __get__(self, obj, klass):
if obj is None:
return self # hack required to make Django validate (if obj is None, then we're a class, and classes are callable )
item = getattr(obj, self.fk)
for attr in self.fkattrs:
item = getattr(item, attr)
return item
def ProfileInfo(field, short_description, boolean = False):
def getter(self):
try:
return getattr(self.get_profile(), field)
except CofProfile.DoesNotExist:
return ""
getter.short_description = short_description
getter.boolean = boolean
return getter
User.profile_login_clipper = FkeyLookup("profile__login_clipper", "Login clipper")
User.profile_num = FkeyLookup("profile__num", "Numéro")
User.profile_phone = ProfileInfo("phone", "Téléphone")
User.profile_occupation = ProfileInfo("occupation", "Occupation")
User.profile_departement = ProfileInfo("departement", "Departement")
User.profile_mailing_cof = ProfileInfo("mailing_cof", "ML COF", True)
User.profile_mailing_bda = ProfileInfo("mailing_bda", "ML BDA", True)
User.profile_mailing_bda_revente = ProfileInfo("mailing_bda_revente", "ML BDA-R", True)
class UserProfileAdmin(UserAdmin):
def is_buro(self, obj):
try:
return obj.get_profile().is_buro
except CofProfile.DoesNotExist:
return False
is_buro.short_description = 'Membre du Buro'
is_buro.boolean = True
def is_cof(self, obj):
try:
return obj.get_profile().is_cof
except CofProfile.DoesNotExist:
return False
is_cof.short_description = 'Membre du COF'
is_cof.boolean = True
list_display = ('profile_num',) + UserAdmin.list_display + ('profile_login_clipper','profile_phone','profile_occupation','profile_mailing_cof','profile_mailing_bda','profile_mailing_bda_revente','is_cof','is_buro',)
list_display_links = ('username','email','first_name','last_name')
list_filter = UserAdmin.list_filter + ('profile__is_cof', 'profile__is_buro', 'profile__mailing_cof', 'profile__mailing_bda')
inlines = [
CofProfileInline,
]
import autocomplete_light
def user_unicode(self):
if self.first_name and self.last_name:
return u"%s %s (%s)" % (self.first_name, self.last_name, self.username)
else:
return self.username
User.__unicode__ = user_unicode
class EventRegistrationAdmin(admin.ModelAdmin):
form = autocomplete_light.modelform_factory(EventRegistration)
list_display = ('__unicode__','event','user','paid')
list_filter = ('paid',)
search_fields = ('user__username', 'user__first_name', 'user__last_name', 'user__email', 'event__title')
"""
class VoterProfileInlineForm(BaseDynamicEntityForm):
def __init__(self, data=None, *args, **kwargs):
super(BaseDynamicEntityForm, self).__init__(data, *args, **kwargs)
config_cls = self.instance._eav_config_cls
self.entity = getattr(self.instance, config_cls.eav_attr)
self.base_fields = {}
self._build_dynamic_fields()
class VoterProfileInline(eav.admin.BaseEntityInline, admin.StackedInline):
model = CofProfile
form = VoterProfileInlineForm
inline_classes = ("collapse open",)
fields = None
fieldsets = None
def get_fieldsets(self, request, obj=None):
formset = self.get_formset(request)
fk_name = self.fk_name or formset.fk.name
kw = {fk_name: obj} if obj else {}
instance = self.model(**kw)
form = formset.form(request.POST, instance=instance)
return [(None, {'fields': form.fields.keys()})]
class VotedListFilter(SimpleListFilter):
# Human-readable title which will be displayed in the
# right admin sidebar just above the filter options.
title = _(u'A voté')
# Parameter for the filter that will be used in the URL query.
parameter_name = 'voted'
def lookups(self, request, model_admin):
return (
('1', _('Yes')),
('0', _('No')),
)
def queryset(self, request, queryset):
# Returns the filtered queryset based on the value
# provided in the query string and retrievable via
# `self.value()`.
#
# Compare the requested value (either '80s' or '90s')
# to decide how to filter the queryset.
if self.value() == '1':
qs2 = User.objects.filter(profile__eav__a_vot = True)
return queryset.filter(pk__in = qs2.values_list('id', flat = True))
return voters
if self.value() == '0':
qs2 = User.objects.filter(profile__eav__a_vot = False)
return queryset.filter(pk__in = qs2.values_list('id', flat = True))
class VoterAdmin(UserProfileAdmin):
form = forms.ModelForm
fields = ('username','first_name','last_name')
readonly_fields = ('username','first_name','last_name')
fieldsets = None
def is_cof(self, obj):
try:
return obj.get_profile().is_cof
except CofProfile.DoesNotExist:
return False
is_cof.short_description = 'Membre du COF'
is_cof.boolean = True
def a_vote(self, obj):
try:
if not obj.get_profile().eav.a_vot:
return False
else:
return True
except CofProfile.DoesNotExist:
return False
a_vote.short_description = 'A voté'
a_vote.boolean = True
list_display = ('profile_num',) + UserAdmin.list_display + ('is_cof','a_vote')
list_filter = ('profile__is_cof', 'profile__is_buro', VotedListFilter)
inlines = [
VoterProfileInline,
]
"""
class PetitCoursAbilityAdmin(admin.ModelAdmin):
list_display = ('user','matiere','niveau','agrege')
search_fields = ('user__username', 'user__first_name', 'user__last_name', 'user__email', 'matiere__name', 'niveau')
list_filter = ('matiere','niveau','agrege')
class PetitCoursAttributionAdmin(admin.ModelAdmin):
list_display = ('user','demande','matiere','rank',)
class PetitCoursAttributionCounterAdmin(admin.ModelAdmin):
list_display = ('user','matiere','count',)
list_filter = ('matiere',)
search_fields = ('user__username', 'user__first_name', 'user__last_name', 'user__email', 'matiere__name')
class PetitCoursDemandeAdmin(admin.ModelAdmin):
list_display = ('name','email','agrege_requis','niveau','created','traitee','processed')
list_filter = ('traitee','niveau')
admin.site.register(Survey, SurveyAdmin)
admin.site.register(SurveyQuestion, SurveyQuestionAdmin)
admin.site.register(Event, EventAdmin)
admin.site.register(EventOption, EventOptionAdmin)
admin.site.unregister(User)
admin.site.register(User, UserProfileAdmin)
admin.site.register(CofProfile)
admin.site.register(Club)
admin.site.register(CustomMail)
admin.site.register(PetitCoursSubject)
admin.site.register(PetitCoursAbility, PetitCoursAbilityAdmin)
admin.site.register(PetitCoursAttribution, PetitCoursAttributionAdmin)
admin.site.register(PetitCoursAttributionCounter, PetitCoursAttributionCounterAdmin)
admin.site.register(PetitCoursDemande, PetitCoursDemandeAdmin)
#admin.site.register(Voter, VoterAdmin)
admin.site.register(EventRegistration, EventRegistrationAdmin)