Skip to main content

使用 AJAX 请求的 Django 框架的链式选择框小部件。

项目描述

这个库的灵感来自s-block ( https://github.com/s-block/django-chained-selectbox ) 中的django-chained-selectbox 。

它使用 AJAX 请求为 Django 框架提供链接选择框小部件,以将选择框链接在一起。这些值会根据父值而变化。

前面提到的库仅用于 Django 管理员。新库具有前端功能、改进的现有实例数据初始化和新的ChainedModelChoiceField。它还使用自定义 TestClient ,如果用户登录,它能够将request.user变量传递到 AJAX 视图中。例如,如果您需要按用户权限过滤结果查询集,这非常有用。

在 Django 1.4.5 上测试。

要求

  • 姜戈

  • jQuery

安装

  1. 使用 pip 安装 python 库: pip install django-clever-selects

  2. 在你的 Django 设置文件中添加smart_selectsINSTALLED_APPS

  3. 在您的{% load %}语句中添加clever_selects_extras并在关闭</body>元素之前放置{% quiet_selects_js_import %}标记。在body内容之后加载clever-selects.js文件很重要,所以不要放在<head></head>中!

用法

形式

表单必须从ChainedChoicesMixin(或从ChainedChoicesForm / ChainedChoicesModelForm,取决于您的需要)继承,当已经存在实例或初始数据时加载选项:

from clever_selects.form_fields import ChainedChoiceField
from clever_selects.forms import ChainedChoicesForm


class SimpleChainForm(ChainedChoicesForm):
    first_field = ChoiceField(choices=(('', '------------'), (1, '1'), (2, '2'), (3, '3'), (4, '4'), (5, '5'), ))
    second_field = ChainedChoiceField(parent_field='first_field', ajax_url=reverse_lazy('ajax_chained_view'))


class MultipleChainForm(ChainedChoicesForm):
    first_field = ChoiceField(choices=(('', '------------'), (6, 6), (7, 7), (8, 8), (9, 9), (10, 10), ))
    second_field = ChainedChoiceField(parent_field='first_field', ajax_url=reverse_lazy('ajax_chained_view'))
    third_field = ChainedChoiceField(parent_field='second_field', ajax_url=reverse_lazy('ajax_chained_view'))
    fourth_field = ChainedChoiceField(parent_field='third_field', ajax_url=reverse_lazy('ajax_chained_view'))
    fifth_field = ChainedChoiceField(parent_field='fourth_field', ajax_url=reverse_lazy('ajax_chained_view'))


class ModelChainForm(ChainedChoicesModelForm):
    brand = forms.ModelChoiceField(queryset=CarBrand.objects.all(), required=True,
        empty_label=_(u'Select a car brand'))
    model = ChainedModelChoiceField(parent_field='brand', ajax_url=reverse_lazy('ajax_chained_models'),
        empty_label=_(u'Select a car model'), model=BrandModel, required=True)
    engine = forms.ChoiceField(choices=([('', _('All engine types'))] + Car.ENGINES), required=False)
    color = ChainedChoiceField(parent_field='model', ajax_url=reverse_lazy('ajax_chained_colors'),
        empty_label=_(u'Select a car model'), required=False)

    class Meta:
        model = Car

请注意,出于不同目的,每个字段的 ajax URL 可能不同。有关更多用例,请参阅示例项目。

为了预填充子字段,表单可能需要访问当前用户。这可以通过在表单视图中将用户传递给表单的 __init__() 方法的 kwargs 来完成。ChainedSelectFormViewMixin 会为您解决这个问题。:

class CreateCarView(ChainedSelectFormViewMixin, CreateView)
    template_name = "create_car.html"
    form_class = ModelChainForm
    model = Car

意见

每当更改父字段时都会进行 Ajax 调用。您必须设置 ajax URL 以返回列表的 json 列表:

class AjaxChainedView(BaseDetailView):
    """
    View to handle the ajax request for the field options.
    """

    def get(self, request, *args, **kwargs):
        field = request.GET.get('field')
        parent_value = request.GET.get("parent_value")

        vals_list = []
        for x in range(1, 6):
            vals_list.append(x*int(parent_value))

        choices = tuple(zip(vals_list, vals_list))

        response = HttpResponse(
            json.dumps(choices, cls=DjangoJSONEncoder),
            mimetype='application/javascript'
        )
        add_never_cache_headers(response)
        return response

或者您可以像这样使用ChainedSelectChoicesView类助手:

class AjaxChainedView(ChainedSelectChoicesView):
    def get_choices(self):
        vals_list = []
        for x in range(1, 6):
            vals_list.append(x*int(self.parent_value))
        return tuple(zip(vals_list, vals_list))

或像这样:

class AjaxChainedView(ChainedSelectChoicesView):
    def get_child_set(self):
        return ChildModel.object.filter(parent_id=self.parent_value)

不要忘记更新您的 urls.py:

url(r'^ajax/custom-chained-view-url/$', AjaxChainedView.as_view(), name='ajax_chained_view'),

作者

图书馆由Pragmatic Mates的Erik Telepovsky提供。请参阅我们的其他库

项目详情


下载文件

下载适用于您平台的文件。如果您不确定要选择哪个,请了解有关安装包的更多信息。

源分布

django-clever-selects-xadmin-0.8.8.4.tar.gz (9.7 kB 查看哈希)

已上传 source