【问题标题】:Passing jQuery slider value onto Django form将 jQuery 滑块值传递到 Django 表单
【发布时间】:2017-05-24 12:39:07
【问题描述】:

提交时,我很难在 Django 表单中提取 jQuery 滑块值。当页面被访问或刷新时,我可以通过外部和内部 urls.py 和 views.py 从 URL 向它传递一个值,但是我不能在提交时在表单中包含滑块值。不用说,我已经尝试了许多方法来提取值,包括 jQuery post 方法和 AJAX,但我没有尝试过任何方法。

首先,我创建了一个简单的表单(forms.Form),然后尝试使用模型表单,期望更多的控制,但返回到一个forms.Form。我的 form.py 是:

    class ChoiceForm(forms.Form):
        '''Checkboxes.'''
        GeoJunk = forms.BooleanField(required=False, initial=True)
        ...
        '''Field for jQuery slider widget value. I initially don’t care if it is hidden, especially during troubleshooting.'''
        slider_field = forms.CharField(max_length=4, required=False)

我的views.py很复杂,但本质是:

    def profile_list(request, sort_arg='default', latlonzoom='39.991622,-105.250098,15', choice='7', rangefactor='0'):

    request_user = request.user

    ''' Initialize slider value. '''
    slider_value = 0

    if request.method == 'POST':
    choice_form = ChoiceForm(request.POST, prefix="choice")
    if choice_form.is_valid(): 
        bit1 = choice_form.cleaned_data['GeoJunk']
        ...
        '''The slider value submitted from form.'''
        slider_state = choice_form.cleaned_data['slider_value']
    else:
        choice_form = ChoiceForm()

    …
    return render(request, "junkster/pages/home.html", add_csrf(request, MEDIA_URL=MEDIA_URL, STATIC_URL=STATIC_URL, request_user=request_user, waypoints=waypoints, librarypoints=librarypoints, gs_waypoints=gs_waypoints, search_flag=search_flag, lat=lat, lon=lon, zoom=zoom, waypoints_count=waypoints_count, librarypoints_count=librarypoints_count, gs_waypoints_count=gs_waypoints_count, choice_form=choice_form, sort_arg=sort_arg, latlonzoom=latlonzoom, choice=choice, rangefactor=rangefactor, slider_state=slider_state
    ))

模板很复杂,但本质上是从choice.html 开始并最终扩展到base-geomap.html:

base-geomap.html:

    <!doctype html>
    <html lang="{{ LANGUAGE_CODE }}"{% if LANGUAGE_BIDI %} dir="rtl"{% endif %}>
    {% load pages_tags mezzanine_tags i18n staticfiles %}

    <head>
    …
    <link rel="stylesheet" href="{% static "junkster/css/jquery-ui.css" %}">
    <link rel="stylesheet" href="{% static "junkster/css/jquery-ui.min.css" %}">
    <link rel="stylesheet" href="{% static "junkster/css/jquery-ui.theme.css" %}"> 
    <link rel="stylesheet" href="{% static "junkster/css/jquery-ui.theme.min.css" %}"> 
    <link rel="stylesheet" href="{% static "junkster/css/jquery-ui.slider.css" %}"> 
    <link rel="stylesheet" href="{% static "junkster/css/jquery-ui-timepicker-  addon.css" %}">
    <link rel="stylesheet" href="{% static "junkster/css/jquery.simple-dtpicker.css" %}">
    {% endcompress %}

    {% compress js %}
    <script src="{% static 'mezzanine/js/jquery-1.7.2.min.js' %}"></script>
    <script src="{% static "js/bootstrap.js" %}"></script>
    <script src="{% static "js/bootstrap-extras.js" %}"></script>

    <script type="text/javascript" language="javascript"    src="https://code.jquery.com/jquery-2.0.3.min.js"></script>
    <script type="text/javascript" src="{% static "junkster/js/jquery-ui.js" %}"></script> 
    <script type="text/javascript" src="{% static "junkster/js/jquery-min.js" %}"></script> 
    <script type="text/javascript" src="{% static "junkster/js/jquery-ui-min.js" %}"></script> 
    <script type="text/javascript" src="{% static "junkster/js/jquery-ui-sliderAccess.js" %}"></script> 
    <script type="text/javascript" src="{% static "junkster/js/jquery-ui-timepicker-addon.js" %}"></script> 
    {% endcompress %}
    …
    <script>
    //Follows: var URL = "{% url 'junkster:profile_list' default' latlonzoom choice rangefactor %}";
    var URL = "{% url 'junkster:profile_list' 'default' '39.99, -105.25,15' '7' '2' %}";
    </script>
    <script>
    $( function() {
    //Array of slider values.
    var valMap = ['1mi', '4mi', 'All'];
        $( "#slider_vertical" ).slider({
        orientation: "vertical",
        range: false,
        max: valMap.length - 1,
        //Set initial value to the URL rangefactor.
        // This will be a value of [0, 1, 2]. 
        value: {{rangefactor}},
        //"slide" or "change" work equally well.
        slide: function(event, ui) {
            //Index values of [0, 1, 2].
            $("#val").text(ui.value);
            //Mapped values of ['1mi', '4mi', 'All'].
            $("#nlVal").text(valMap[ui.value]);
            //Shows mapped value of slider on top, e.g., "1mi," 
            // rather than rangefactor value "0."
            $( "#amount" ).val( valMap[ui.value] );
            /Affects the HTML template "slider_value" input field.
            $('#id_slider_field').val(valMap[ui.value]);

            //Does not work.
            //$('#id_slider_field').attr('value', ui.value); 
        }
    });
    //Shows the mapped value of slider on top upon startup.
    $( "#amount" ).val( valMap[$( "#slider_vertical" ).slider( "value" )] );
    });
    </script>
    </head>
    …

choiceform.html:

    {% extends "junkster/pages/geolist.html" %}
    {% block choiceform %}
    <form action="" method="post">
        {% csrf_token %}
        <!--Keep checkboxes in list.-->
        {{ choice_form.as_ul }}
        <input type="submit" name="choicevalue" value="Submit" />
        <br><br>

        <!-- -----JQuery Slider.---- -->
        <b>Range of View:</b>
        <!--Mapped value display on top of slider.-->
        <input type="text" id="amount" readonly style="border:0;  color:#f6931f; font-weight:bold; margin-left:3em;">
        <!--Slider widget.-->
        <div id="slider_vertical" style="height:12em; margin-left:3em;"></div>
        <br>
        <!--For diagnostics.-->
        <!--”rangefactor” should assume the slider value.-->
        rangefactor = {{ rangefactor }}<br><br>
        <!--”slider_valuer” is the slider value from view.-->
        slider_value = {{ slider_value }}<br>
        <!--This html field does show the value of the slider.-->
        <input type="text" id="id_slider_field", name="slider_field">
        </form>
    {% endblock %}

choiceform.html 的最后一部分有一个输入文本字段,它确实显示了滑块的更改值,但我不能用 Django 表单字段提交它,除非我错了。

我希望 jQuery 函数可以在最终模板中实现一些东西,例如:

    rangefactor = slider_value
    a href="{% url 'junkster:profile_list' 'default' latlonzoom choice rangefactor %}">Wish this would happen!</a>

感谢任何提出建议的人,因为我尝试将滑块值与 Django 表单的其他复选框值一起提取但未成功。

沃尔特·戈德克

【问题讨论】:

  • 那是很多代码。请只发布最相关的位。即发出 ajax 请求的 javascript 代码和处理它的 python 视图。
  • 很多;我不确定我现在是否可以修剪代码。

标签: jquery django forms slider


【解决方案1】:

我确实找到了解决方案。必须使用表单 html 模板创建另一个隐藏文本字段;不是 Django 表单域。

再次,父模板中的滑块 jQuery 小部件:

    <script>
        $( function() {
            //Array of slider values.
            var valMap = ['1mi', '4mi', '16mi', 'All'];
            $( "#slider_vertical" ).slider({
            orientation: "vertical",
            range: false,
            max: valMap.length - 1,
            //Set initial value to the URL rangefactor.
            // This will be a value of [0, 1, 2, 3]. 
            value: {{rangefactor}},
            //"slide" or "change" work equally well.
            slide: function(event, ui) {
                //Index values of [0, 1, 2, 3].
                $("#val").text(ui.value);
                //Mapped values of ['1mi', '4mi', '16mi', 'All'].
                $("#nlVal").text(valMap[ui.value]);
                //Shows mapped values of slider on top.
                $( "#amount" ).val( valMap[ui.value] );
                $('#slider_field').val(ui.value);
                }
            });
            //Shows the mapped values on top upon startup.
            $( "#amount" ).val( valMap[$( "#slider_vertical" ).slider( "value" )] );
        });
    </script>

子模板 -choiceform.html:

    <form action="" method="post">
    {% csrf_token %}
    {{ choice_form.as_ul }}
    <!--This hidden html field captures the value of the slider.-->
    <input type="hidden" id="slider_field", name="slider_field">

    <!-- -----JQuery Slider.---- -->
    <div class=title7>Range of View:</div>
    <!--Mapped value display on top of slider.-->
    <input type="text" id="amount" readonly style=...">
    <!--Slider widget.-->
    <div id="slider_vertical" style=..."></div>

    <input type="submit" name="choicevalue" value="Submit" action="{% url 'junkster:profile_list' sort_arg latlonzoom choice rangefactor %}" />

特殊的“提交”按钮将焦点发送回视图,并带有适当的参数。

在视图中,获取滑块值的choiceform.html 字段是这样访问的:

    ...
    if request.method == 'POST':
        choice_form = ChoiceForm(request.POST, prefix="choice")
        #Check if form is valid:
        if choice_form.is_valid(): 
        #Get the slider value from the special form text field.
        try:
            slider_value = request.POST['slider_field']
            if str(slider_value) != '':
                rangefactor = slider_value
            if rangefactor == 'NaN' or numpy.isnan(int(rangefactor)):
                rangefactor = '0'
        except:
            rangefactor = '0'

“rangefactor”仅在滑块值“slider_value”更改时复制它,因此错误捕获例程,因为 NaN 值导致程序在choiceform.html 中的 URL 调用结束时再次调用查看。

【讨论】:

    猜你喜欢
    • 2020-08-31
    • 1970-01-01
    • 2013-11-19
    • 2012-04-28
    • 1970-01-01
    • 2012-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多