admin.py 5.65 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_lazy as _
10
11
from django.http import HttpResponse
import csv
12

13
from . import forms, models
14
15


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


21
class MemberInline(admin.StackedInline):
22
23
24
25
26
27
28
29
30
    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')
31
32
33
34
    model = models.Member
    can_delete = False


35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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)


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

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

    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
77
78
79
80
                if user.member.birthday is None:
                    if self.value() == 'unknown':
                        users.add(user.pk)
                    continue
Thom Wiggers's avatar
Thom Wiggers committed
81
82
                elif (user.member.birthday <= eightteen_years_ago and
                      self.value() == '18+'):
83
                    users.add(user.pk)
Thom Wiggers's avatar
Thom Wiggers committed
84
85
                elif (user.member.birthday > eightteen_years_ago and
                      self.value() == '18-'):
86
87
88
89
90
91
92
                    users.add(user.pk)
            except models.Member.DoesNotExist:
                # The superuser does not have a .member object attached.
                pass
        return queryset.filter(pk__in=users)


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

97
    actions = ['address_csv_export', 'student_number_csv_export']
98

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

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

115
116
117
118
119
    def address_csv_export(self, request, queryset):
        response = HttpResponse(content_type='text/csv')
        response['Content-Disposition'] = 'attachment;\
                                           filename="addresses.csv"'
        writer = csv.writer(response)
120
121
        writer.writerow([_('First name'), _('Last name'), _('Address'),
                         _('Address line 2'), _('Postal code'), _('City')])
122
123
124
125
126
127
128
129
130
131
132
133
        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')

134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
    def student_number_csv_export(self, request, queryset):
        response = HttpResponse(content_type='text/csv')
        response['Content-Disposition'] = 'attachment;\
                                           filename="student_numbers.csv"'
        writer = csv.writer(response)
        writer.writerow([_('First name'), _('Last name'), _('Student number')])
        for user in queryset.exclude(member=None):
            writer.writerow([user.first_name,
                             user.last_name,
                             user.member.student_number
                             ])
        return response
    student_number_csv_export.short_description = _('Download student number '
                                                    'label for selected users')

149
admin.site.register(models.BecomeAMemberDocument)
150
151
152
153

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