django-select2 不能在 django-admin 中使用内联

Posted

技术标签:

【中文标题】django-select2 不能在 django-admin 中使用内联【英文标题】:django-select2 not working with inlines in django-admin 【发布时间】:2014-10-23 02:58:12 【问题描述】:

这是我的模型和管理类:

---------------------Models-----------------------
from django.contrib.auth.models import User

class PurchaseOrder(models.Model):
    buyer = models.ForeignKey(User)
    is_debit = models.BooleanField(default = False)
    delivery_address = models.ForeignKey('useraccounts.Address')
    organisation = models.ForeignKey('useraccounts.AdminOrganisations')
    date_time = models.DateTimeField(auto_now_add=True)
    total_discount = models.IntegerField()
    tds = models.IntegerField()
    mode_of_payment = models.ForeignKey(ModeOfPayment)
    is_active = models.BooleanField(default = True)
    class Meta:
        verbose_name_plural = "Purchase Orders"

    def __unicode__(self):
        return '%s' % (self.id)

----------------------------------Admin----------------------------------------
"""
This class is used to add, edit or delete the details of item purchased
"""
class PurchasedItemInline(admin.StackedInline):
    form = ItemSelectForm
    model = PurchasedItem
    fields = ['parent_category', 'sub_category', 'item', 'qty', ]
    extra = 10

class BuyerChoices(AutoModelSelect2Field):
    queryset = User.objects.all()
    search_fields = ['username__icontains', ]

class BuyerForm(ModelForm):
    user_verbose_name = 'Buyer'
    buyer = BuyerChoices(
        label='Buyer',
        widget=AutoHeavySelect2Widget(
            select2_options=
            'width': '220px',
            'placeholder': 'Lookup %s ...' % user_verbose_name
            
        )
    )

    class Meta:
        model = PurchaseOrder
        fields = '__all__'

"""
This class is used to add, edit or delete the details of items
purchased but buyer has not confirmed the items purchased, this class
inherits the fields of PurchaseOrder derscribing the delivery address of
buyer , is_debit , total discount , tds and mode of payment
"""
class PurchaseOrderAdmin(admin.ModelAdmin):
    form = BuyerForm
   #list_display = ['id','buyer','delivery_address','date_time','is_active']
    inlines = [PurchasedItemInline]
  # model = PurchaseOrder
   #actions = [mark_active, mark_inactive]
   #list_filter = ['date_time']
   #search_fields = ['id']
    list_per_page = 20
    def response_add(self, request, obj, post_url_continue=None):
        request.session['old_post'] = request.POST
        request.session['purchase_order_id'] = obj.id
        return HttpResponseRedirect('/suspense/add_distance/')

我正在尝试实现django-select2,但是当我在 PurchaseOrderAdmin 它没有显示我实现的字段 django-select2:

但是当我删除内联时,它工作正常:

编辑

这里是 ItemSelectForm

class ItemSelectForm(forms.ModelForm):
    class Media:
        js = (
            'http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js',
            'js/ajax.js', 
        )

    try:
        parent_category = forms.ModelChoiceField(queryset=Category.objects.\
            filter(parent__parent__isnull=True).filter(parent__isnull=False))

        sub_category_id = Category.objects.values_list('id',flat=True)
        sub_category_name = Category.objects.values_list('name',flat=True)
        sub_category_choices = [('', '--------')] + [(id, name) for id, name in
        itertools.izip(sub_category_id, sub_category_name)]
        sub_category = forms.ChoiceField(sub_category_choices)
    except:
        pass

    item = forms.ModelChoiceField(queryset = Product.objects.all())

    def __init__(self, *args, **kwargs):
        super(ItemSelectForm, self).__init__(*args, **kwargs)
        self.fields['parent_category'].widget.attrs='class': 'parent_category'
        self.fields['sub_category'].widget.attrs='class': 'sub_category'
        self.fields['item'].widget.attrs='class': 'item'

【问题讨论】:

可以添加ItemSelectForm的代码吗? 我已经添加了ItemSelectForm的代码,请看。 好吧,似乎有些 js(也许是 js/ajax.js)正在破坏 select2 的魔力。也许您可以在这两种情况下发布来自开发工具或呈现的 html 的任何日志。 【参考方案1】:

通过在 static/suit/js/suit.js 中添加以下行对我有用

添加:

(function ($) 
    Suit.after_inline.register('init_select2', function(inline_prefix, row)
        $(row).find('select').select2(); 
    );

【讨论】:

以上是关于django-select2 不能在 django-admin 中使用内联的主要内容,如果未能解决你的问题,请参考以下文章

如何在django-select2中使用django-filter?

django-select2 基于类或基于函数的视图

Django-Select2 重型小部件

如何在 django 管理站点中使用 django-select2 小部件?

django-select2:如果没有选择国家,如何禁用城市选择? (django 2.2)

使用 django-select2 管理标签