admin.py 4.91 KB
Newer Older
1
2
3
"""
This module registers admin pages for the models
"""
4
5
import datetime

6
7
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
8
from django.contrib.auth.models import User
9
from django.utils.translation import ugettext as t
10
from django.utils.translation import ugettext_lazy as _
11
12
from django.http import HttpResponse
import csv
13

14
from . import forms, models
15
16


17
18
class MembershipInline(admin.StackedInline):
    model = models.Membership
19
    extra = 0
20
21


22
class MemberInline(admin.StackedInline):
23
24
25
26
27
28
29
30
31
    fields = ('starting_year', 'programme', 'address_street',
              'address_street2', 'address_postal_code', 'address_city',
              'student_number', 'phone_number', 'receive_optin',
              'receive_newsletter', 'birthday', 'show_birthday',
              'direct_debit_authorized', 'bank_account', 'initials',
              'nickname', 'display_name_preference', 'profile_description',
              'website', 'photo', 'emergency_contact',
              'emergency_contact_phone_number', 'language',
              'event_permissions')
32
33
34
35
    model = models.Member
    can_delete = False


36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
class MembershipTypeListFilter(admin.SimpleListFilter):
    title = _('membership type')
    parameter_name = 'membership'

    def lookups(self, request, model_admin):
        return models.Membership.MEMBERSHIP_TYPES

    def queryset(self, request, queryset):
        if not self.value():
            return queryset
        queryset.prefetch_related('user__memberships')
        users = set()
        for user in queryset:
            try:
                if user.member.current_membership:
                    if user.member.current_membership.type == self.value():
                        users.add(user.pk)
            except models.Member.DoesNotExist:
                # The superuser does not have a .member object attached.
                pass
        return queryset.filter(pk__in=users)


59
60
61
62
63
class AgeListFilter(admin.SimpleListFilter):
    title = _('Age')
    parameter_name = 'birthday'

    def lookups(self, request, model_admin):
Joost Rijneveld's avatar
Joost Rijneveld committed
64
65
66
67
68
        return (
            ('18+', _('≥ 18')),
            ('18-', _('< 18')),
            ('unknown', _('Unknown')),
        )
69
70
71
72
73
74
75
76
77

    def queryset(self, request, queryset):
        if not self.value():
            return queryset
        users = set()
        for user in queryset:
            try:
                today = datetime.date.today()
                eightteen_years_ago = today.replace(year=today.year - 18)
Joost Rijneveld's avatar
Joost Rijneveld committed
78
79
80
81
                if user.member.birthday is None:
                    if self.value() == 'unknown':
                        users.add(user.pk)
                    continue
Thom Wiggers's avatar
Thom Wiggers committed
82
83
                elif (user.member.birthday <= eightteen_years_ago and
                      self.value() == '18+'):
84
                    users.add(user.pk)
Thom Wiggers's avatar
Thom Wiggers committed
85
86
                elif (user.member.birthday > eightteen_years_ago and
                      self.value() == '18-'):
87
88
89
90
91
92
93
                    users.add(user.pk)
            except models.Member.DoesNotExist:
                # The superuser does not have a .member object attached.
                pass
        return queryset.filter(pk__in=users)


94
class UserAdmin(BaseUserAdmin):
95
    form = forms.UserChangeForm
96
    add_form = forms.UserCreationForm
97

98
99
    actions = ['address_csv_export']

100
    inlines = (MemberInline, MembershipInline)
101
102
    # FIXME include proper filter for expiration
    # https://docs.djangoproject.com/en/1.9/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_filter
103
    list_filter = (MembershipTypeListFilter,
104
                   'is_superuser',
105
106
                   AgeListFilter,
                   'member__event_permissions',)
107
108
109
110
111

    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('first_name', 'last_name', 'username', 'email',
112
                       'send_welcome_email')
113
114
        }),
    )
115

116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
    def address_csv_export(self, request, queryset):
        response = HttpResponse(content_type='text/csv')
        response['Content-Disposition'] = 'attachment;\
                                           filename="addresses.csv"'
        writer = csv.writer(response)
        writer.writerow([t('First name'), t('Last name'), t('Address'),
                         t('Address line 2'), t('Postal code'), t('City')])
        for user in queryset.exclude(member=None):
            writer.writerow([user.first_name,
                             user.last_name,
                             user.member.address_street,
                             user.member.address_street2,
                             user.member.address_postal_code,
                             user.member.address_city,
                             ])
        return response
    address_csv_export.short_description = _('Download address label for '
                                             'selected users')

135
admin.site.register(models.BecomeAMemberDocument)
136
137
138
139

# re-register User admin
admin.site.unregister(User)
admin.site.register(User, UserAdmin)