跳转到主要内容

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

项目描述

这个库受到 django-chained-selectbox 的启发,该库来自 s-block (https://github.com/s-block/django-chained-selectbox)。

它使用AJAX请求为Django框架提供链式选择框小部件。值根据父值变化。

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

在Django 1.4.5上进行了测试。

要求

  • Django

  • jQuery

安装

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

  2. clever_selects 添加到您的Django设置文件中的 INSTALLED_APPS

  3. clever_selects_extras 添加到您的 {% load %} 语句中,并在关闭 </body> 元素之前放置 {% clever_selects_js_import %} 标签。将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 调用。您必须设置返回 json 列表的 ajax URL

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'),

作者

此库由 Erik Telepovsky 提供,来自 Pragmatic Mates。请参阅 我们的其他库

项目详情


下载文件

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

源分发

django-clever-selects-1.0.0.tar.gz (8.8 kB 查看哈希值

上传时间

支持者

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF 赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误日志 StatusPage StatusPage 状态页面