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
Jamesie Pic committed
11
    """Set published to True for the queryset"""
Arnaud Fabre's avatar
Arnaud Fabre committed
12 13
    queryset.update(published=True)

alexandre.jauneau's avatar
alexandre.jauneau committed
14

Arnaud Fabre's avatar
Arnaud Fabre committed
15 16 17 18
publish_positions.short_description = 'Publish selected positions'


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

alexandre.jauneau's avatar
alexandre.jauneau committed
22

Arnaud Fabre's avatar
Arnaud Fabre committed
23 24 25
unpublish_positions.short_description = 'Unpublish selected positions'


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

67 68 69
    form = PositionAdminForm


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