Пример #1
0
 def set_ajax_form(self):
     self.ajax_fields = get_ajax_config_for_relation_fields(self.model_class)
     self.ajax_form = make_ajax_form(self.model_class, self.ajax_fields, self.get_contains_all_keyword_form())
     for field in self.ajax_form.declared_fields:
         self.ajax_form.declared_fields[field].required = False
     for field_name in self.ajax_form.base_fields:
         self.ajax_form.base_fields[field_name].required = False
Пример #2
0
class CommunicationPreferenceAdmin(AjaxSelectAdmin):
    form = make_ajax_form(CommunicationPreference, {'worker': 'workers'})
    formfield_overrides = {
        BitField: {
            'widget': BitFieldCheckboxSelectMultiple
        },
    }
    list_display = ('id', 'worker', 'methods', 'communication_type')
    search_fields = ('worker__user__username', 'methods', 'communication_type')
    list_filter = ('worker__user__username', ('methods', BitFieldListFilter))
Пример #3
0
class PayRateAdmin(AjaxSelectAdmin):
    form = make_ajax_form(PayRate, {'worker': 'workers'})
    list_display = ('id', 'edit_worker', 'hourly_rate', 'hourly_multiplier',
                    'start_date', 'end_date')
    search_fields = ('worker__user__username', )
    ordering = ('worker__user__username', )
    list_filter = ('worker', )

    def edit_worker(self, obj):
        return edit_link(obj.worker)
Пример #4
0
class PageAdmin(admin.ModelAdmin):
    form = make_ajax_form(
        Page,
        {
            "lock_user": "******",
            "owner_group": "groups",
            "edit_groups": "groups",
            "view_groups": "groups",
        },
    )
Пример #5
0
class ReleaseInline(AjaxSelectAdminStackedInline):
    # Example of the stacked inline

    model = Release
    form = make_ajax_form(Release, {
        'group': 'group',
        'label': 'label',
        'songs': 'song',
    })
    extra = 1
Пример #6
0
class MemberTrackingCodeAdmin(VersionAdmin):
    list_display = ('member', 'uuid', 'validated')
    list_display_links = list_display
    list_filter = ('validated', 'member__is_active')
    search_fields = ("member__name", "member__surname", "member__nickname",
                     "member__email")
    form = make_ajax_form(MemberTrackingCode, {'member': 'member'})

    def has_delete_permission(self, request, obj=None):
        return False
Пример #7
0
class TimeEntryAdmin(AjaxSelectAdmin):
    form = make_ajax_form(TimeEntry, {
        'worker': 'workers',
        'assignment': 'task_assignments',
    })
    list_display = ('id', 'date', 'worker', 'time_worked', 'assignment')
    search_fields = ('id', 'worker__user__username',
                     'assignment__task__step__name',
                     'assignment__task__project__short_description')
    list_filter = ('worker', )
Пример #8
0
class BookInline(AjaxSelectAdminTabularInline):
    # AjaxSelectAdminTabularInline enables the + add option

    model = Book
    form = make_ajax_form(Book, {
        'about_group': 'group',
        'mentions_persons': 'person'
    },
                          show_help_text=True)
    extra = 2
Пример #9
0
class ExcerptAdmin(AutoAuthoredModelAdmin):
    """ Administration des extraits de texte """
    list_select_related = True
    list_display = ['id', 'name', 'title', 'visible', 'level']
    list_editable = ['visible', 'level', 'title']
    search_fields = ['name', 'title', 'translations__text']
    list_filter = ['visible', 'level']
    fieldsets = ((_("Excerpt"), {'fields': ('name', 'title', 'author', 'format', 'visible', 'weight', 'level')}),)
    form = make_ajax_form(Excerpt, {'author': 'user'})
    inlines = [ExcerptTranslationInlineAdmin]
    change_form_template = 'admintools_bootstrap/tabbed_change_form.html'
Пример #10
0
class WorkerCertificationAdmin(AjaxSelectAdmin):
    form = make_ajax_form(WorkerCertification, {
        'worker': 'workers'
    })
    list_display = ('id', 'worker', 'certification', 'role', 'task_class')
    search_fields = (
        'worker__user__username', 'certification__slug', 'certification__name',
        'certification__workflow__slug', 'certification__workflow__name',
        'certification__workflow__description')
    ordering = ('-created_at',)
    list_filter = ('task_class', 'role')
Пример #11
0
class MatchSubstitutionInLine(AjaxSelectAdminTabularInline):
    model = MatchSubstitution
    extra = 0
    form = make_ajax_form(MatchSubstitution, {
        "player_in": "player",
        "player_out": "player"
    })

    def get_queryset(self, request):
        qs = AjaxSelectAdminTabularInline.get_queryset(self, request)
        return qs
Пример #12
0
class ProductAdmin(AjaxSelectAdmin):
    prepopulated_fields = {"slug": ('name', )}
    list_filter = ['status']
    list_display = ('id', 'name', 'short_description', 'status')
    inlines = (ProductImageInline, )
    form = make_ajax_form(
        Product,
        {
            'user': '******',
            # 'categories': 'categories'
        })
Пример #13
0
class StaffBotRequestAdmin(RelatedFieldAdmin, AjaxSelectAdmin):
    form = make_ajax_form(StaffBotRequest, {
        'task': 'tasks',
    })
    list_display = (
        'id',
        'task',
        'created_at',
        'project_description',
    )
    search_fields = ('project_description', 'task__id')
Пример #14
0
class PrestationAdmin(AjaxSelectAdmin):
    from invaction import create_invoice

    date_hierarchy = 'date'
    list_display = ('patient', 'carecode', 'date')
    search_fields = ['patient__name', 'patient__first_name']
    list_filter = ('patient__name', )
    actions = [create_invoice]
    form = make_ajax_form(Prestation, {
        'patient': 'patient',
        'carecode': 'carecode'
    })
Пример #15
0
class DestinationManipulationAdmin(admin.ModelAdmin):
    form = make_ajax_form(DestinationManipulation,
                          {'view_source': 'view_sources'})
    actions = ['export_as_csv']
    list_filter = [
        'action_type', ('action', MultiSearchFilter), BlankValue1ListFilter,
        BlankValue2ListFilter, ExcludedViewSourceFilter
    ]
    search_fields = ['=buid', '=view_source']
    list_display = [
        'buid', 'get_view_source_name', 'action_type', 'action', 'value_1',
        'value_2'
    ]

    def export_as_csv(self, request, queryset):
        """Gives the ability to save the queryset as a csv"""

        query = request.GET.get('q')
        # Older versions of Django are broken with respect to the
        # "Select all x destination manipulations" link in that regardless of
        # if it is chosen or not, you will always only get at most 100 records.
        # Thus, we manually run the filter and return all results if this
        # option is present.
        select_all = request.POST.get('select_across', '0') == '1'
        if query and select_all:
            result = queryset.filter(Q(buid=query) | Q(view_source=query))
        else:
            result = queryset

        fields = ("BUID", "View Source", "View Source Name", "Action Type",
                  "Action", "Value 1", "Value 2")
        output = StringIO()
        writer = csv.writer(output)
        writer.writerow(fields)

        for item in result:
            view_source = ViewSource.objects.filter(
                view_source_id=item.view_source).first()

            writer.writerow([
                item.buid, item.view_source,
                getattr(view_source, 'name', ''), item.action_type,
                item.action, item.value_1, item.value_2
            ])

        disposition = ("attachment; filename=destination_manipulations.csv")
        response = HttpResponse(content_type='text/csv')
        response['Content-Disposition'] = disposition
        response.write(output.getvalue())

        return response

    export_as_csv.short_description = "Save selected as CSV"
Пример #16
0
class IterationAdmin(AjaxSelectAdmin):
    form = make_ajax_form(Iteration, {'assignment': 'task_assignments'})
    list_display = ('id', 'edit_assignment', 'start_datetime', 'end_datetime',
                    'status')
    search_fields = ('assignment__task__step__name',
                     'assignment__task__project__short_description'
                     'assignment__worker__user__username')
    ordering = ('assignment__worker__user__username', )
    list_filter = ('status', 'assignment__worker__user__username')

    def edit_assignment(self, obj):
        return edit_link(obj.assignment)
Пример #17
0
class PrivateInvoiceItemAdmin(AjaxSelectAdmin):
    from action_private import pdf_private_invoice
    from action_private_with_recap import pdf_private_invoice_with_recap

    date_hierarchy = 'invoice_date'
    list_display = ('invoice_number', 'private_patient', 'invoice_month',
                    'prestations_invoiced', 'invoice_sent')
    list_filter = ['invoice_date', 'private_patient__name', 'invoice_sent']
    search_fields = ['private_patient']
    actions = [pdf_private_invoice, pdf_private_invoice_with_recap]
    form = make_ajax_form(PrivateInvoiceItem,
                          {'private_patient': 'private_patient_a_facturer'})
Пример #18
0
class PracticeAttendanceAdmin(admin.ModelAdmin):
    form = make_ajax_form(
        PracticeAttendance,
        {
            # fieldname: channel_name
            'daftar_orang': 'users'
        })
    list_display = [
        'kelas',
        'practice',
        'tutor',
    ]
Пример #19
0
class VolunteerAdmin(admin.ModelAdmin):
    form = make_ajax_form(Volunteer, dict(student='student'))
    list_display = ('student', 'hours_required', 'hours_completed')
    list_filter = [
        'sites',
        'student',
    ]
    search_fields = [
        'student__fname',
        'student__lname',
    ]
    inlines = [VolunteerSiteInline]
Пример #20
0
class AliasAdmin(admin.ModelAdmin):
    search_fields = ['alias', 'person__legal_name']
    list_filter = [
        'ignored',
        # AliasStatusListFilter,  # Django 1.4
    ]
    list_display = ['alias', 'person', 'ignored', 'created']
    form = make_ajax_form(models.Alias, {
        'person': 'person_name',
    })

    actions = [
        "ignore_aliases",
    ]

    def ignore_aliases(self, request, queryset):
        for alias in queryset:
            alias.ignored = True
            alias.save()

        self.message_user(request, "Ignored the aliases")

    ignore_aliases.short_description = "Ignore the selected aliases"

    def get_urls(self):
        urls = super(AliasAdmin, self).get_urls()
        # XXX: not sure if there URLs are in use
        my_urls = [
            url(r'^next_unassigned/$', self.next_unassigned),
        ]
        return my_urls + urls

    @method_decorator(staff_member_required)
    def next_unassigned(self, request):

        # Select the unassigned, and order so that most recently updated come
        # last. This prevents the same one coming back again and again if it
        # cannot be resolved (eg if it is ambiguous). Partial fix for that
        # problem - better would be a 'cant_be_done' flag or similar, or date
        # ranges so that 'Mr. Foo' from 1999 to 2003 is one person, and 2004
        # onwards another. Not implemented now as it is not certain that this
        # is actually a problem.
        unassigned = models.Alias.objects.all().unassigned().order_by(
            '-created')

        try:
            alias = unassigned[0]
            return redirect('/admin/hansard/alias/' + str(alias.id) + '/')
        except IndexError:
            messages.add_message(request, messages.INFO,
                                 'There are no more unassigned aliases.')
            return redirect('/admin/hansard/alias/')
Пример #21
0
class PageAdmin(AutoAuthoredModelAdmin):
    """ Administration des pages """
    list_select_related = True
    list_display = ['id', 'name', 'title', 'path', 'template', 'active', 'anonymous', 'authenticated', 'uuid']
    list_editable = ['active', 'anonymous', 'authenticated']
    list_filter = ['active', 'anonymous', 'authenticated']
    search_fields = []
    fieldsets = (
        (_("Page"), {'fields': ('path', 'name', 'title', 'description', 'author', 'template', 'parent', 'active',)}),
        ('Plus', {'fields': ('anonymous', 'authenticated', 'heading',)}))
    form = make_ajax_form(Page, {'author': 'user'})
    inlines = [ConfigurationInlineAdmin, ]
    change_form_template = 'admintools_bootstrap/tabbed_change_form.html'
Пример #22
0
class StudentCourseInline(admin.TabularInline):
    model = CourseEnrollment
    form = make_ajax_form(CourseEnrollment, {
        'course': 'course',
        'exclude_days': 'day'
    })
    raw_id_fields = ('course', )
    # define the autocomplete_lookup_fields
    autocomplete_lookup_fields = {
        'fk': ['course'],
    }
    fields = ['course', 'attendance_note', 'exclude_days']
    extra = 0
Пример #23
0
class ShareHolderModelAdmin(admin.ModelAdmin):
    search_fields = ('company_title', 'info')
    list_display = ('company_title', 'phone', 'role', 'view_share',
                    'is_contactor')
    list_filter = ('is_contactor', )
    form = make_ajax_form(ShareHolder, {
        'company': 'company',
    })

    def view_share(self, obj):
        return '{:.2f}%'.format(obj.share)

    view_share.short_description = '占比'
Пример #24
0
class EksponatAdmin(ajax_select.admin.AjaxSelectAdmin):
    inlines = [
        PrimerekInline,
    ]

    list_display = ('ime', 'tip', 'proizvajalec', 'leto_proizvodnje',
                    'st_primerkov')

    list_filter = ('kategorija', 'proizvajalec')

    search_fields = ('ime', 'tip')

    form = ajax_select.make_ajax_form(models.Eksponat,
                                      {'proizvajalec': 'proizvajalec'})
Пример #25
0
class StaffingRequestInquiryAdmin(RelatedFieldAdmin, AjaxSelectAdmin):
    form = make_ajax_form(StaffingRequestInquiry, {
        'communication_preference': 'communication_preferences',
    })
    list_display = (
        'id', 'communication_preference__worker', 'communication_method',
        'request',
        'created_at',
    )
    search_fields = (
        'communication_preference__worker__user__username',
        'communication_method', 'request__project_description',
        'request__task__id'
    )
Пример #26
0
class LabelAdmin(AjaxSelectAdmin):
    """ to get + popup buttons, subclass AjaxSelectAdmin

        multi-inheritance is also possible if you have an Admin class you want to inherit from:

        class PersonAdmin(YourAdminSuperclass, AjaxSelectAdmin):

        this acts as a MixIn to add the relevant methods
    """
    # this shows a ForeignKey field

    # create an ajax form class using the factory function
    #                     model, fieldlist,   [form superclass]
    form = make_ajax_form(Label, {'owner': 'person'})
class CategoryAdmin(AjaxSelectAdmin):
    # populado automaticamente
    prepopulated_fields = {
        # meu campo slug quando for chamado vai ser populado baseado no name
        "slug": ('name', )
    }
    # filtrar aos que estão escondido e não escondido
    list_filter = ['hidden']

    # quais itens trazer
    list_display = ('id', 'name', 'parent', 'hidden')

    # toda vez que aparecer "parent" era buscar o lookup com nome de categories
    form = make_ajax_form(Category, {'parent': 'categories'})
Пример #28
0
class ArticleAdmin(admin.ModelAdmin):
    list_display = ('id', 'get_title', 'source', 'category', 'cover_image',
                    'published_on')
    list_filter = ('source', 'category', 'published_on', ArticleEditedByFilter)
    exclude = ("hash_tags", )
    search_fields = ('title', )

    form = make_ajax_form(Article, {
        'category': 'category',
    })

    def get_title(self, obj):
        return mark_safe("<a href='{0}' target='_blank'>{1}</a>".format(
            obj.source_url, obj.title))

    get_title.admin_order_field = 'title'
    get_title.short_description = 'Title'

    def get_tags(self, tags):
        """
        this method will return tag name from tags objects
        """
        tag_list = []
        for tag in tags:
            tag_list.append(tag["name"])
        return tag_list

    def save_model(self, request, obj, form, change):
        if change:
            obj.edited_by = request.user
            obj.manually_edit = True
            serializer = ArticleSerializer(obj)
            json_data = serializer.data
            if json_data["hash_tags"]:
                tag_list = self.get_tags(json_data["hash_tags"])
                json_data["hash_tags"] = tag_list

            if not obj.spam:
                ingest_to_elastic([json_data], "article", "article", "id")
            else:
                delete_from_elastic([json_data], "article", "article", "id")
            super(ArticleAdmin, self).save_model(request, obj, form, change)

        super(ArticleAdmin, self).save_model(request, obj, form, change)
        serializer = ArticleSerializer(obj)
        json_data = serializer.data
        if json_data["hash_tags"]:
            tag_list = self.get_tags(json_data["hash_tags"])
            json_data["hash_tags"] = tag_list
        ingest_to_elastic([json_data], "article", "article", "id")
Пример #29
0
class StudentDisciplineAdmin(admin.ModelAdmin):
    form = make_ajax_form(StudentDiscipline, dict(students='discstudent'))

    list_per_page = 50
    fields = ['date', 'students', 'teacher', 'infraction', 'comments', 'private_note']
    list_display = ('show_students', 'date', 'comment_brief', 'infraction')
    list_filter = [('date',DateRangeFilter), 'infraction', 'action',]
    search_fields = ['comments', 'students__first_name', 'students__last_name']
    inlines = [DisciplineActionInstanceInline]
    
    def lookup_allowed(self, lookup, *args, **kwargs):
        if lookup in ('students','students__id__exact',):
            return True
        return super(StudentDisciplineAdmin, self).lookup_allowed(lookup, *args, **kwargs)
Пример #30
0
class ReferralFormAdmin(admin.ModelAdmin):
    list_display = ['classroom_teacher','date','referred_by','student']
    list_filer = ['classroom_teacher','date','referred_by','student']
    formfield_overrides = {
        models.ManyToManyField: {'widget': CheckboxSelectMultiple},
    }
    form = make_ajax_form(ReferralForm, dict(student='student'))
    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name in ['referred_by','classroom_teacher']:
            kwargs['initial'] = request.user.id
            return db_field.formfield(**kwargs)
        return super(ReferralFormAdmin, self).formfield_for_foreignkey(
            db_field, request, **kwargs
        )
Пример #31
0
class PolicyAdmin(MigasAdmin):
    form = make_ajax_form(Policy, {
        'included_attributes': 'attribute',
        'excluded_attributes': 'attribute'
    })
    form.declared_fields['included_attributes'].label = _(
        'included attributes')
    form.declared_fields['included_attributes'].help_text = ''
    form.declared_fields['excluded_attributes'].label = _(
        'excluded attributes')
    form.declared_fields['excluded_attributes'].help_text = ''

    list_display = ('name_link', 'my_enabled', 'my_exclusive',
                    'included_attributes_link', 'excluded_attributes_link')
    list_filter = ('enabled', 'exclusive')
    list_display_links = ('name_link', )
    search_fields = ('name', 'included_attributes__value',
                     'excluded_attributes__value')
    fieldsets = (
        (_('General'), {
            'fields': (
                'name',
                'comment',
                'enabled',
                'exclusive',
            )
        }),
        (_('Application Area'), {
            'fields': (
                'included_attributes',
                'excluded_attributes',
            )
        }),
    )
    inlines = [PolicyGroupLine]
    extra = 0

    name_link = MigasFields.link(model=Policy, name='name')
    included_attributes_link = MigasFields.objects_link(
        model=Policy,
        name='included_attributes',
        description=_('included attributes'))
    excluded_attributes_link = MigasFields.objects_link(
        model=Policy,
        name='excluded_attributes',
        description=_('excluded attributes'),
    )
    my_enabled = MigasFields.boolean(model=Policy, name='enabled')
    my_exclusive = MigasFields.boolean(model=Policy, name='exclusive')
Пример #32
0
from django import forms
from ajax_select import make_ajax_form, make_ajax_field
from lcavail.models import LcAvailed, LCCoverMovement

lcavail_form = make_ajax_form(
    LcAvailed,
    {'memo_acct': 'ledger_memo_cash',
     'nostro_acct': 'nostro_acct'}
)


class LcAvailedAjaxForm(forms.ModelForm):
    class Meta:
        model = LcAvailed
        exclude = ('avail_date', 'date_processed',)

    nostro_acct = make_ajax_field(LcAvailed, 'nostro_acct', 'nostro_acct', help_text=None)

    memo_acct = make_ajax_field(LcAvailed, 'memo_acct', 'ledger_memo_cash', help_text=None)

    drawn_amt_text = forms.CharField(
        label='Amount Drawn',
        required=False,
        widget=forms.TextInput(
            attrs={'readonly': 'true'}
        )
    )

    drawn_amt = forms.CharField(
        widget=forms.NumberInput(
            attrs={'type': 'hidden'}))
Пример #33
0
# from normal_admin.user_admin import UserAdminAuthenticationForm, get_admin_site
from obj_sys.models_ufs_obj import UfsObj


r = AdminRegister()
# f = ForeignKeyAutoCompleteFeature()
# # h = FilterHorizontalFeature(('descriptions', 'relations'))
# f.set_search_field_by_model({UfsObj: ("uuid", "ufs_url", "full_path")})
# r.add_feature(f)
# r.add_feature(h)
# h = AdminAttrFeature({"filter_horizontal": ("descriptions", )})
# raw = AdminAttrFeature({"raw_id_fields": ("relations",)})
# r.add_feature(raw)
# r.add_feature(h)
a = AdminAttrFeature({"form": make_ajax_form(UfsObj, {"relations": "ufs_obj",
                                                      "parent": "ufs_obj",
                                                      "descriptions": "description"}),
                      "list_filter": ('source', 'ufs_obj_type')
                      })

r.add_feature(a)
r.add_feature(ReversionFeature())
r.add_feature(AdminTaggingFeature())
r.register(UfsObj)


r = AdminRegister()
r.add_feature(ReversionFeature())
r.register_all_models(models)