【问题标题】:django form pagination save in local storagedjango表单分页保存在本地存储中
【发布时间】:2018-09-24 09:05:20
【问题描述】:

我有一个表单分页,我想将用户的输入保存在本地存储中。我已经设法在我的 jquery 脚本中获取了这个变量:

var fields = [, , , , , , , ]

我的问题是我不知道如何将此字段对象的键/值保存到本地存储中。有大量页面,所以这是通用的,我不应该使用字段名称来访问字段值,只使用这个字段对象。

我能做些什么来实现这个目标?

【问题讨论】:

  • 这真的取决于您将如何使用放入本地存储的内容。您这样做是为了在用户向后退时重新填充表单吗?目前尚不清楚您需要什么样的键和值。但一般来说,BoundField 的属性 id_for_label 将为您提供 HTML 输入元素的 id,而方法 value() 将为您提供在 HTML 中呈现的字段值。因此,您可以创建一个字典,其中包含每个 BoundFieldidvalue,而不是将 BoundFields 列表传递给您的模板,然后您可以将其存储在本地。
  • 感谢您的回复。我这样做是为了在用户向后退时重新填充表单。
  • 我将尝试您的一般建议。为了其他人,我会发布结果。
  • 当您说:“但一般来说,BoundField 的属性 id_for_label 将为您提供 HTML 输入元素的 id,而方法 value() 将为您提供该字段的值以 HTML 呈现。”
  • 我没看懂...你指的是模板html代码吗?如果是这样,下面是我的 html 代码,其中从 paginator = Paginator(boundfield_list, 10); 视图中构造元素元素 = paginator.page(page);返回渲染(请求,'rsmgui_input.html',{'元素':元素})。这是 html 部分:
    {% for field in elements %}
    {% endfor %}
    解释你的一般评论这个上下文。

标签: jquery django pagination local-storage


【解决方案1】:
forms.py file
=============
class ControlElementForm(BaseForm):
    rundescriptor = forms.CharField(max_length=50, initial='rsmgui', label='Run Descriptor')
    typechoices = [(0, 'hour'), (1, 'minute'), (2, 'day')]
    tstype = forms.ChoiceField(choices=typechoices, label='Time Step',
                               widget=forms.Select())

    lenchoices = [(0, 24), ]
    tslen = forms.ChoiceField(choices=lenchoices, label='Time Length',
                              widget=forms.Select())

    svchoices = [(0, "PETSC"),]
    solver = forms.ChoiceField(choices=svchoices, label="Solver Package", help_text="Portable, Extensible Toolkit for Scientific Computation")
    mchoices = [(0, "gmres"),]
    method = forms.ChoiceField(choices=mchoices, label="Solver Method")
    alpha = forms.FloatField(max_value=1.0, min_value=0.0, initial=0.900)
    cchoices = [(0, "ilu"),]
    precond = forms.ChoiceField(choices=cchoices, label='Pre Condition') # TODO ask the meaning
    uchoices = [(0, "english"),]
    units = forms.ChoiceField(choices=uchoices)

views.py file
============
def rsminput(request):
    if request.POST:
        form = XMLElementsForm(request.POST)
        # process the data in form.cleaned_data as required
        if form.is_valid():
            # do something
            messages.success(request, 'Your data was saved successfully!')
            return render(request, 'rsmgui_home.html')
        else:
            messages.error(request, form.errors)

    boundfield_list = tuple(XMLElementsForm())  
    page = request.GET.get('page', 1)
    paginator = Paginator(boundfield_list, 10)

    try:
        elements = paginator.page(page)
    except PageNotAnInteger:
        elements = paginator.page(1)
    except EmptyPage:
        elements = paginator.page(paginator.num_pages)

    return render(request, 'rsmgui_input.html', {'elements': elements })


urls.py file
=============
from django.conf.urls import url, include
from django.views.decorators.cache import cache_page

from .views import rsminput

urlpatterns = [
    url(r'^input$', rsminput, name='rsminput'),
]

rsmgui_input.html file
==========================
{% extends "rsmgui_nav.html" %}
{% block title %}RSM Input{% endblock %}

<script src="{% static 'jquery/jquery-3.3.1.min.js' %}"></script>
<script src="{% static 'jquery/jquery-ui.min.js' %}"></script>

{% block center_menu %}

<form class="form-horizontal" id="input-form" role="form" action="" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    <div class="row">
        <div class="col col-sm-7">
        <p>Model Input:&nbsp;&lt;Control Elements&gt;</p>
        </div>
        <div class="col col-sm-5 text-right">
            <div class="btn-group" role="group" aria-label="input-xml">
                <button id="input-submit" type="submit" class="btn btn-default btn-trans" data-toggle="tooltip" data-placement="bottom" title="save">
                  <span class="glyphicon glyphicon-save"></span>
                </button>
                <button type="button" class="btn btn-default btn-trans" data-toggle="tooltip" data-placement="bottom" title="reset">
                  <span class="glyphicon glyphicon-minus"></span>
                </button>
                <button id="input-close" type="button" class="btn btn-default btn-trans"
                      data-toggle="tooltip" data-placement="bottom" title="close">
                  <span class="glyphicon glyphicon-remove"></span>
                </button>
            </div>
        </div>
    </div>

    <div >
        {% for boundfield in elements %}
            <div class="form-group">
              <label class="control-label col-sm-5" style="text-align:right;"
                    for="{{boundfield.id_for_label}}">{{ boundfield.label }}
              </label>
              <div class="col-sm-7" id="{{boundfield.id_for_label}}"
                    aria-describedby="{{boundfield.id_for_label}} | addstr:ex">{{ boundfield }}
              </div>
            </div>

            {% if boundfield.help_text %}
                <p class="col-sm-offset-5 col-sm-7"> <small style="color: grey">{{ boundfield.help_text|safe }}</small></p>
            {% endif %}

            {% for error in boundfield.errors %}
                <div class="col-sm-offset-2 col-sm-10"><span class="text-danger small">{{ error }}</span></div>
            {% endfor %}

        {% endfor %}
    </div>

    <!-- For pagination-->
    <div class="text-center">
        {% if elements.has_other_pages %}
            <ul class="pagination">
                {% if elements.has_previous %}
                    <li><a href="?page={{ elements.previous_page_number }}">&laquo;</a></li>
                {% else %}
                    <li class="disabled"><span>&laquo;</span></li>
                {% endif %}

                {% for i in elements.paginator.page_range %}
                    {% if elements.number == i %}
                        <li class="active"><span>{{ i }} <span class="sr-only">(current)</span></span></li>
                    {% else %}
                        <li><a href="?page={{ i }}">{{ i }}</a></li>
                    {% endif %}
                {% endfor %}

                {% if elements.has_next %}
                    <li><a href="?page={{ elements.next_page_number }}">&raquo;</a></li>
                {% else %}
                    <li class="disabled"><span>&raquo;</span></li>
                {% endif %}
            </ul>
        {% endif %}
    </div>
</form>

{% endblock %}

<script type="text/javascript">
    $(document).ready(function() {

        function loadInputLocalStorage(){
            $('#input-form :input').each(function(){
                var key = $(this).attr('id');
                if(localStorage.getItem(key)) {
                    var value = localStorage.getItem(key);
                    $(this).val(value);
                }
            });
        }
        loadInputLocalStorage();

        function saveInputLocalStorage() {
            $('#input-form :input').each(function(){
                var id = $(this).attr('id');
                var value = $(this).val();
                localStorage.setItem(id, value);

            });
        }
        $('#input-submit').on('click', function(){
            saveInputLocalStorage();
        });

    }); // end of document
</script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-13
    • 1970-01-01
    • 1970-01-01
    • 2011-11-24
    • 2018-03-06
    • 2018-10-02
    • 2014-10-31
    • 1970-01-01
    相关资源
    最近更新 更多