admin.py 1.81 KB
Newer Older
1
from django import forms
Arnaud Fabre's avatar
Arnaud Fabre committed
2
3
from django.contrib import admin

4
5
6
from dal.autocomplete import ModelSelect2Multiple

from representatives.models import Representative
Arnaud Fabre's avatar
Arnaud Fabre committed
7
8
9
10
from .models import Position


def publish_positions(modeladmin, request, queryset):
Jamesie Pic's avatar
Quality    
Jamesie Pic committed
11
    """Set published to True for the queryset"""
Arnaud Fabre's avatar
Arnaud Fabre committed
12
13
14
15
16
17
    queryset.update(published=True)

publish_positions.short_description = 'Publish selected positions'


def unpublish_positions(modeladmin, request, queryset):
Jamesie Pic's avatar
Quality    
Jamesie Pic committed
18
    """Set published to False for the queryset"""
Arnaud Fabre's avatar
Arnaud Fabre committed
19
20
21
22
23
    queryset.update(published=False)

unpublish_positions.short_description = 'Unpublish selected positions'


24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
class PositionAdminForm(forms.ModelForm):
    representatives = forms.ModelMultipleChoiceField(
        queryset=Representative.objects.all(),
        required=False,
        widget=ModelSelect2Multiple(
            url='representative-autocomplete',
        )
    )

    def __init__(self, *args, **kwargs):
        super(PositionAdminForm, self).__init__(*args, **kwargs)

        if self.instance and self.instance.pk:
            self.fields['representatives'].initial = \
                self.instance.representatives.all()

    def save(self, commit=True):
        item = super(PositionAdminForm, self).save(commit=False)
        item.save()

        item.representatives = self.cleaned_data['representatives']
        if commit:
            self.save_m2m()

        return item


Arnaud Fabre's avatar
Arnaud Fabre committed
51
class PositionAdmin(admin.ModelAdmin):
Jamesie Pic's avatar
Quality    
Jamesie Pic committed
52
    list_display = (
53
54
        'kind',
        'short_title',
Jamesie Pic's avatar
Quality    
Jamesie Pic committed
55
        'short_text',
56
        'score',
Jamesie Pic's avatar
Quality    
Jamesie Pic committed
57
58
59
        'datetime',
        'link',
        'published')
60
    list_display_links = ('short_title', 'short_text')
Arnaud Fabre's avatar
Arnaud Fabre committed
61
62
63
64
    list_editable = ('published',)
    list_filter = ('published',)
    actions = (publish_positions, unpublish_positions)

65
66
67
    form = PositionAdminForm


Arnaud Fabre's avatar
Arnaud Fabre committed
68
admin.site.register(Position, PositionAdmin)