【问题标题】:django - change list in POST requestdjango - POST 请求中的更改列表
【发布时间】:2019-05-31 02:01:21
【问题描述】:

我有一个元组列表,想根据按下的按钮在其中删除或添加元组。添加 tubles 运行良好,但我的问题是,由于某种原因,如果我单击按钮删除元组,列表会将时间重置为删除发生之前的状态。

例如我有一个列表:

ctestformat = [('sung', 4, 15), ('ren', 3, 27), ('lexe', 4, 39)]

删除数字 15 后我得到:

ctestformat = [('ren', 3, 27), ('lexe', 4, 39)]

但是在收到另一个删除或添加的 POST 请求后,列表会重置为第一个状态,就好像什么都没有删除一样

这是我根据单击的按钮添加和删除元组的视图:

def editorstart(request, ctestformat=[]):
    if request.method == 'POST':

    """If clicked on create gap button, create a new gap and put it in ctestformat"""
    if 'create_gap' in request.POST:
        selectedgap = request.POST['sendgap']
        startindex = int(request.POST['startpoint'])-13

        ctestformat.append((selectedgap, len(selectedgap), startindex))
        ctestformat.sort(key=operator.itemgetter(2))

        """if clicked on deletegap, delete the gap from ctestformat"""
    elif 'deletegap' in request.POST:

        deleteindex = request.POST['deletegap']
        test = [t for t in ctestformat if t[2] != int(deleteindex)]
        ctestformat = test
    # This function doesnt change anything to ctestformat
    modifiedtext = createmodifiedtext(ctestformat)
    return render(request, 'editor_gapcreate.html', {"text": modifiedtext, 'ctestformat': ctestformat})

如果您有任何其他问题,尽管问:)

编辑:

在我看来添加了回报

我的模板:

{% extends "base_generic2.html" %}

{% block content %}

  <form action="editorgapcreate" id=create method="POST">
    <input type="hidden" name="sendgap" id="sendgap">
    <input type="hidden" name="startpoint" id="startpoint">

    <script src="../static/textselector.js"></script>

    <div id="thetext" onmouseup="getSelectionText()">
        <h1>{{ text|safe }}</h1>
    </div>

    {% csrf_token %}
    <p></p>
    <b>Your current selected gap:</b>
    <p id="currentgap"></p>

    <input type="hidden" name="text" id="text" value="{{ text }}">

    <button type="submit" name="create_gap" id="gapcreate">Create gap</button>
  </form>
{% endblock %}

【问题讨论】:

    标签: html django post django-forms django-views


    【解决方案1】:

    在 Python 中为默认参数(在本例中为列表)使用可变值是 not normally a good idea。该列表在定义函数时创建一次,这意味着您对其所做的任何更改在后续函数调用中都是可见的。但是,这似乎是针对您的情况。

    您没有看到列表更改的原因是您在过滤掉一个项目后所做的分配ctestformat = test 没有效果。您需要改变原始列表而不是重新分配,首先在该列表中查找项目的索引,然后使用pop() 将其删除。例如:

    elif 'deletegap' in request.POST:
    
        deleteindex = request.POST['deletegap']
    
         for i, t in enumerate(ctestformat): 
            if t[2] == int(deleteindex): 
                ctestformat.pop(i)  # Modify original list
                break   
        ...
    

    我仍然建议不要使用可变的默认参数来实现这一点。如果您需要跨请求共享数据,您最好使用缓存或数据库,或者可能是会话状态,具体取决于您的应用程序要求。

    【讨论】:

    • 是的,我现在更改了我的代码,以便在每次调用我的视图后重置我的 ctestformat 列表,然后根据 POST 请求或 GET 填充,但感谢您的回答:)
    猜你喜欢
    • 2016-11-13
    • 2020-07-10
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 2021-01-05
    • 2020-01-31
    • 2016-10-18
    相关资源
    最近更新 更多