admin.py 6.78 KB
Newer Older
David Haynes's avatar
David Haynes committed
1
2
#!/usr/bin/env python
# -*- coding: utf-8 -*-
3
"""
4
5
api/admin.py

6
7
8
9
Django admin interface configuration.

https://docs.djangoproject.com/en/1.11/ref/contrib/admin/
"""
10
# Django Imports
11
from django.contrib import admin
12
from django.contrib import messages
David Haynes's avatar
David Haynes committed
13
from django.contrib.gis.admin import OSMGeoAdmin
14
15
from django.core.exceptions import ObjectDoesNotExist
from django.http import HttpResponseRedirect
16
from django.shortcuts import render
17
# App Imports
David Haynes's avatar
David Haynes committed
18
from .models import Facility, Schedule, OpenTime, Category, Location, Alert
19

20

David Haynes's avatar
David Haynes committed
21
@admin.register(Facility)
Ben Waters's avatar
Ben Waters committed
22
class FacilityAdmin(admin.ModelAdmin):
23
    """
David Haynes's avatar
David Haynes committed
24
25
26
    Custom Admin panel for the Facility model.

    Allows admins to create new facilities through the admin interface.
27
    """
28
29
    def drop_special_schedules(self, request, queryset):
        num = queryset.count()
30
31
        for facility in queryset:
            facility.special_schedules.clear()
32
33
        self.message_user(request,
                          "Successfully cleared all special schedules for %d facilities." % num)
34
    drop_special_schedules.short_description = 'Clear all special schedules for selected facilities'
35

36
    def assign_bulk_schedules(self, request, queryset):
37
        num = queryset.count()
38
39
        # all admin actions-related requests are post requests, so we're looking for
        # the one that has the associated value with our confirmation input button
40
41
42
43
44
45
46
        if 'bulk_schedule' in request.POST:
            try:
                new_schedule = Schedule.objects.get(pk=request.POST['schedule'])
                name = new_schedule.name
                for facility in queryset:
                   facility.main_schedule = new_schedule
                   facility.save()
47
48
                self.message_user(request,
                                  "Set %s as the main schedule for %d facilities." % (name, num))
49
            except ObjectDoesNotExist:
50
                self.message_user(request,
51
52
                                  "Unable to set a new main schedule for %d facilities." % num,
                                  level=messages.ERROR)
53
            return HttpResponseRedirect(request.get_full_path())
54
        return render(request,
Daniel W Bond's avatar
Daniel W Bond committed
55
                      'bulk_schedules.html',
56
57
                      context = {'facilities': queryset,
                                 'schedules': Schedule.objects.all()})
58
    assign_bulk_schedules.short_description = 'Set a main schedule for selected facilities'
59

60
61
62
63
64
65
66
67
68
    def assign_bulk_special_schedules(self, request, queryset):
        num = queryset.count()
        if 'bulk_special_schedule' in request.POST:
            try:
                new_special_schedule = Schedule.objects.get(pk=request.POST['special_schedule'])
                name = new_special_schedule.name
                for facility in queryset:
                   facility.special_schedules.add(new_special_schedule)
                   facility.save()
69
70
                self.message_user(request,
                                  "Added %s as a special schedule to %d facilities." % (name, num))
71
            except ObjectDoesNotExist:
72
                self.message_user(request,
73
74
                                  "Unable to add additional special schedule to %d facilities." % num,
                                  level=messages.ERROR)
75
76
            return HttpResponseRedirect(request.get_full_path())
        return render(request,
Daniel W Bond's avatar
Daniel W Bond committed
77
                      'bulk_special_schedules.html',
78
79
                      context = {'facilities': queryset,
                                 'schedules': Schedule.objects.all()})
80
    assign_bulk_special_schedules.short_description = 'Add a special schedule to selected facilities'
81

82
    # a list of all actions to be added
83
84
    actions = [drop_special_schedules,
               assign_bulk_schedules, assign_bulk_special_schedules ]
85

David Haynes's avatar
David Haynes committed
86
    # Allow filtering by the following fields
David Haynes's avatar
David Haynes committed
87
    list_filter = ['facility_category', 'facility_location']
David Haynes's avatar
David Haynes committed
88
89
    # Modify the rendered layout of the "create a new facility" page
    # We are basically reordering things to look nicer to the user here
90
91
    fieldsets = (
        (None, {
David Haynes's avatar
David Haynes committed
92
93
94
95
96
            'fields': ('facility_name', 'logo', 'facility_category',
                       'facility_location', 'main_schedule', 'special_schedules',
                       ('facility_product_tags', 'facility_labels',
                        'facility_classifier'),
                       'tapingo_url', 'phone_number', 'note', 'owners'),
97
        }),
98
    )
99
100
    autocomplete_fields = ['main_schedule', 'special_schedules', ]

101

102
103
104
105
106
107
108
    # despite the name of this method, ("change" seems to imply it would affect modify)
    # it is called only when initially creating a model
    def get_changeform_initial_data(self, request):
        initial_data = super(FacilityAdmin, self).get_changeform_initial_data(request)
        initial_data['owners'] = [request.user, ]
        return initial_data

109

110
111
112
113
114
115
116
117
118
119
class OpenTimeInline(admin.TabularInline):
    """
    A table of time periods that represent an "open time" for a Facility.

    https://docs.djangoproject.com/en/1.11/ref/contrib/admin/#django.contrib.admin.TabularInline
    """
    # Columns correspond to each attribute in the OpenTime table
    model = OpenTime
    # 7 days of the week, so only have 7 rows
    max_num = 7
120
121
122
123
124
125
126
127
128
129
    extra = 7
    # We are basically reordering things to look nicer to the user here
    fieldsets = (
        (None, {
            'fields': (
                ('start_day', 'start_time'),
                ('end_day', 'end_time')
            ),
        }),
    )
130

David Haynes's avatar
David Haynes committed
131
@admin.register(Schedule)
132
class ScheduleAdmin(admin.ModelAdmin):
133
    """
David Haynes's avatar
David Haynes committed
134
135
136
137
138
    Custom Admin panel for the Schedule model.

    Allows admins to create new schedules through the admin interface.
    Additionally, we append the OpenTimeInline table to allow for open times to
    be defined for the schedule we are creating.
139
    """
David Haynes's avatar
David Haynes committed
140
    # Allow filtering by the following fields
141
    list_display = ['name', 'modified']
David Haynes's avatar
David Haynes committed
142
    # Append the OpenTimeInline table to the end of our admin panel
143
    inlines = [OpenTimeInline, ]
David Haynes's avatar
David Haynes committed
144
    # Modify the rendered layout of the "create a new facility" page
145
146
    fieldsets = (
        (None, {
147
148
149
            'fields': ('name',
                       # Pair valid_start and valid_end together on the same
                       # line
David Haynes's avatar
David Haynes committed
150
                       ('valid_start', 'valid_end'),
151
                       'twenty_four_hours',
152
153
                       'schedule_for_removal',
                       'promote_to_main')
David Haynes's avatar
David Haynes committed
154
        }),
155
    )
156
157
    search_fields = ['name', ]  # search terms for autcomplete
    ordering = ['name', ]  # autocomplete ordering
158

David Haynes's avatar
David Haynes committed
159
# https://docs.djangoproject.com/en/1.11/ref/contrib/gis/admin/#osmgeoadmin
160
161
162
OSMGeoAdmin.default_lon = -8605757.16502
OSMGeoAdmin.default_lat = 4697457.00333
OSMGeoAdmin.default_zoom = 15
David Haynes's avatar
David Haynes committed
163
admin.site.register(Location, OSMGeoAdmin)
164
165
# Use the default ModelAdmin interface for these
admin.site.register(Category)
David Haynes's avatar
David Haynes committed
166
admin.site.register(Alert)