Django 如何添加 class 有条件的媒体

Django How to add class media with condition

如何添加 class 有条件的媒体,只在添加表单和更改表单,而不是在视图页面(字段是只读的)?

或按用户组 ID 添加媒体 class?

我的模型管理员



class CooperationBilateraleAdmin(ManyToManyAdmin):

    fieldsets = [
        ( '', {
            'fields': ['paysPartenaires', 'instrumentJuridique',('partenaire','gouvernement','paysP','etat','adefinir'),'objet', 'axeCooperation']
        }),
        ('Autres élements à rajouter ?', {
            'fields': ['infoPlus', ]
        }),
        ('', {
            'fields': [ 'acteJuridique',('dateSignature','dateEntreeVigueur' ),('duree','dureeplus5ans', 'renouvellement'), ('pays', 'villeSignature')]
        }),
        ('Base Documentaire', {
            'fields': [], 'description': 'Joindre le(s) fichier(s) '}),

    ]
    class Media:
        js = (
            '//ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js',  # jquery
            '/static/admin/js/CooperationBilaterale.js',  # project static folder
        )
        css = {
            'all': ('/static/admin/css/CooperationBilaterale.css',)
        }

    def render_change_form(self, request, context, *args, **kwargs):

        user = get_user_model()
        group = request.user.groups.values_list('id', flat=True).first()

        if request.user.has_perm('system.edit_CooperationBilaterale') or request.user.has_perm('system.add_CooperationBilaterale'):
            context['adminform'].form.fields['partenaire'].queryset = PartenaireInternational.objects.filter( caneva__contains=',2,')
            context['adminform'].form.fields['etat'].queryset = Etat.objects.filter(type__exact=3)
            context['adminform'].form.fields['duree'].queryset = DureeCooperation.objects.all().order_by('order')


        if group==2: 
            context['adminform'].form.fields['paysPartenaires'].queryset = Pays.objects.filter(Q(region=1) | Q(region=2)).distinct()
        if group==3: 
            context['adminform'].form.fields['paysPartenaires'].queryset = Pays.objects.filter(region=6).distinct()
        if group == 4: 
            context['adminform'].form.fields['paysPartenaires'].queryset = Pays.objects.filter(Q(region=3) | Q(region=4)).distinct()

        return super(CooperationBilateraleAdmin, self).render_change_form(request, context, *args, **kwargs)

您可以在render_change_view的相关部分添加如下内容:

if group == 2:
    context["media"] += forms.Media(
        css={"all": ("/static/admin/css/CooperationBilaterale.css",)},
        js=["/static/admin/js/CooperationBilaterale.js"],
    )

或您需要的任何内容。确保您已在页面顶部导入 form

from django import forms