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

7
8
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
9
from django.contrib.auth.models import User
Tom van Bussel's avatar
Tom van Bussel committed
10
from django.db.models import Q
11
from django.http import HttpResponse
Tom van Bussel's avatar
Tom van Bussel committed
12
13
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
14

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
26
27
28
29
30
31
32
    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')
33
    model = models.Profile
34
    form = forms.ProfileForm
35
36
37
    can_delete = False


38
39
40
41
42
43
44
45
46
47
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
Tom van Bussel's avatar
Tom van Bussel committed
48
49
50
51
52
53

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


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

    def lookups(self, request, model_admin):
Joost Rijneveld's avatar
Joost Rijneveld committed
61
62
63
64
65
        return (
            ('18+', _('≥ 18')),
            ('18-', _('< 18')),
            ('unknown', _('Unknown')),
        )
66
67
68
69

    def queryset(self, request, queryset):
        if not self.value():
            return queryset
Tom van Bussel's avatar
Tom van Bussel committed
70
71
72
73
74

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

        if self.value() == 'unknown':
75
            return queryset.filter(profile__birthday__isnull=True)
Tom van Bussel's avatar
Tom van Bussel committed
76
        elif self.value() == '18+':
77
            return queryset.filter(profile__birthday__lte=eightteen_years_ago)
Tom van Bussel's avatar
Tom van Bussel committed
78
        elif self.value() == '18-':
79
            return queryset.filter(profile__birthday__gt=eightteen_years_ago)
Tom van Bussel's avatar
Tom van Bussel committed
80
81

        return queryset
82
83


84
class UserAdmin(BaseUserAdmin):
85
    change_list_template = 'admin/members/change_list.html'
86
    form = forms.UserChangeForm
87
    add_form = forms.UserCreationForm
88

89
    actions = ['address_csv_export', 'student_number_csv_export']
90

91
    inlines = (ProfileInline, MembershipInline,)
92
93
    # FIXME include proper filter for expiration
    # https://docs.djangoproject.com/en/1.9/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_filter
94
    list_filter = (MembershipTypeListFilter,
95
                   'is_superuser',
96
                   AgeListFilter,
97
                   'profile__event_permissions',)
98
99
100
101
102

    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('first_name', 'last_name', 'username', 'email',
103
                       'send_welcome_email')
104
105
        }),
    )
106

107
108
109
110
111
    def address_csv_export(self, request, queryset):
        response = HttpResponse(content_type='text/csv')
        response['Content-Disposition'] = 'attachment;\
                                           filename="addresses.csv"'
        writer = csv.writer(response)
112
113
        writer.writerow([_('First name'), _('Last name'), _('Address'),
                         _('Address line 2'), _('Postal code'), _('City')])
114
        for user in queryset.exclude(profile=None):
115
116
            writer.writerow([user.first_name,
                             user.last_name,
117
118
119
120
                             user.profile.address_street,
                             user.profile.address_street2,
                             user.profile.address_postal_code,
                             user.profile.address_city,
121
122
123
124
125
                             ])
        return response
    address_csv_export.short_description = _('Download address label for '
                                             'selected users')

126
127
128
129
130
131
    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')])
132
        for user in queryset.exclude(profile=None):
133
134
            writer.writerow([user.first_name,
                             user.last_name,
135
                             user.profile.student_number
136
137
138
139
140
                             ])
        return response
    student_number_csv_export.short_description = _('Download student number '
                                                    'label for selected users')

Thom Wiggers's avatar
Thom Wiggers committed
141

142
143
144
145
146
147
@admin.register(models.Member)
class MemberAdmin(UserAdmin):
    def has_module_permission(self, reuqest):
        return False


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