admin.py 6.37 KB
Newer Older
1
2
3
"""
This module registers admin pages for the models
"""
4
import csv
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
Tom van Bussel's avatar
Tom van Bussel committed
9
from django.db.models import Q
10
from django.http import HttpResponse
Tom van Bussel's avatar
Tom van Bussel committed
11
12
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
13

14
from members.models import EmailChange
15
from . import forms, models
16
17


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


23
class ProfileInline(admin.StackedInline):
24
25
    fields = ('starting_year', 'programme', 'address_street',
              'address_street2', 'address_postal_code', 'address_city',
26
27
28
29
30
              'address_country', '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',
31
32
              'emergency_contact_phone_number', 'language',
              'event_permissions')
33
    model = models.Profile
34
    form = forms.ProfileForm
35
36
37
    can_delete = False


38
class MembershipTypeListFilter(admin.SimpleListFilter):
39
    title = _('current membership type')
40
41
42
    parameter_name = 'membership'

    def lookups(self, request, model_admin):
43
        return models.Membership.MEMBERSHIP_TYPES + (('none', _('None')),)
44
45
46
47

    def queryset(self, request, queryset):
        if not self.value():
            return queryset
48
49
50
51
52
53
        if self.value() == 'none':
            return queryset.exclude(
                ~Q(membership=None) & (
                    Q(membership__until__isnull=True) |
                    Q(membership__until__gt=timezone.now().date())
                ))
Tom van Bussel's avatar
Tom van Bussel committed
54
55
56
57
58
59

        return (queryset
                .exclude(membership=None)
                .filter(Q(membership__until__isnull=True) |
                        Q(membership__until__gt=timezone.now().date()),
                        membership__type=self.value()))
60
61


62
63
64
65
66
class AgeListFilter(admin.SimpleListFilter):
    title = _('Age')
    parameter_name = 'birthday'

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

    def queryset(self, request, queryset):
        if not self.value():
            return queryset
Tom van Bussel's avatar
Tom van Bussel committed
76
77
78
79
80

        today = datetime.date.today()
        eightteen_years_ago = today.replace(year=today.year - 18)

        if self.value() == 'unknown':
81
            return queryset.filter(profile__birthday__isnull=True)
Tom van Bussel's avatar
Tom van Bussel committed
82
        elif self.value() == '18+':
83
            return queryset.filter(profile__birthday__lte=eightteen_years_ago)
Tom van Bussel's avatar
Tom van Bussel committed
84
        elif self.value() == '18-':
85
            return queryset.filter(profile__birthday__gt=eightteen_years_ago)
Tom van Bussel's avatar
Tom van Bussel committed
86
87

        return queryset
88
89


90
class UserAdmin(BaseUserAdmin):
91
    change_list_template = 'admin/members/change_list.html'
92
    form = forms.UserChangeForm
93
    add_form = forms.UserCreationForm
94

95
96
    actions = ['address_csv_export', 'student_number_csv_export',
               'email_csv_export']
97

98
    inlines = (ProfileInline, MembershipInline,)
99
    list_filter = (MembershipTypeListFilter,
100
                   'is_superuser',
101
                   AgeListFilter,
102
103
                   'profile__event_permissions',
                   'profile__starting_year')
104
105
106
107
108

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

113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
    def email_csv_export(self, request, queryset):
        response = HttpResponse(content_type='text/csv')
        response['Content-Disposition'] = 'attachment;\
                                           filename="email.csv"'
        writer = csv.writer(response)
        writer.writerow([_('First name'), _('Last name'), _('Email')])
        for user in queryset:
            writer.writerow([user.first_name,
                             user.last_name,
                             user.email,
                             ])
        return response
    email_csv_export.short_description = _('Download email addresses for '
                                           'selected users')

128
129
130
131
132
    def address_csv_export(self, request, queryset):
        response = HttpResponse(content_type='text/csv')
        response['Content-Disposition'] = 'attachment;\
                                           filename="addresses.csv"'
        writer = csv.writer(response)
133
        writer.writerow([_('First name'), _('Last name'), _('Address'),
134
135
                         _('Address line 2'), _('Postal code'), _('City'),
                         _('Country')])
136
        for user in queryset.exclude(profile=None):
137
138
            writer.writerow([user.first_name,
                             user.last_name,
139
140
141
142
                             user.profile.address_street,
                             user.profile.address_street2,
                             user.profile.address_postal_code,
                             user.profile.address_city,
143
                             user.profile.get_address_country_display(),
144
145
146
147
148
                             ])
        return response
    address_csv_export.short_description = _('Download address label for '
                                             'selected users')

149
150
151
152
153
154
    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')])
155
        for user in queryset.exclude(profile=None):
156
157
            writer.writerow([user.first_name,
                             user.last_name,
158
                             user.profile.student_number
159
160
161
162
163
                             ])
        return response
    student_number_csv_export.short_description = _('Download student number '
                                                    'label for selected users')

Thom Wiggers's avatar
Thom Wiggers committed
164

165
166
167
168
169
170
@admin.register(models.Member)
class MemberAdmin(UserAdmin):
    def has_module_permission(self, reuqest):
        return False


171
172
admin.site.register(EmailChange)

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