【问题标题】:Add divs with Django template tags on button press在按钮按下时添加带有 Django 模板标签的 div
【发布时间】:2021-04-28 13:12:20
【问题描述】:

我在 forms.py 中定义了一个简单的表单:

SAMPLE_STRINGS = [('','Select...'),'aa','ab','bb','c0']

class MyCustomForm(forms.Form):
    chosen_string = forms.ChoiceField(choices=SAMPLE_STRINGS, label='Please select a string', required=True)
    chosen_number = forms.IntegerField(label='Please select an integer', widget=forms.NumberInput(attrs={'placeholder': 0}))

我想允许用户添加包含上述表单的框(div)。一个带有 Django 模板标签的独立 div 如下所示:

<div class="box" style="height:auto; background-color: #eee;">
    <form method="POST" action="">
        {% csrf_token %}
        {{form.as_p}}
    </form>
</div>

我知道,如果有一个按钮&lt;button class="add_box"&gt;New Box&lt;/button&gt;,相应的添加新元素的jQuery脚本应该是这样的:

$('#button_id').click(function(){
    $('#canvas').append(' ...*HTML of element*... ');
});

但是,当要附加的元素不包含纯 HTML/CSS 以及 Django 模板时,此 jQuery 似乎不起作用。

我的意见.py:

def my_form_func(response):
    form = MyCustomForm(response.POST or None)
    return render(response, "main/my_custom_form.html", {"form": form})

my_custom_form.html:

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
    $( function() {
      $( ".box" ).draggable().resizable();
    } );
    
    // adding div and form on button click - this part causes error
    $('.add_box').click(function(){
        $('#canvas').append('<div class="box" style="height:auto; background-color: #eee;"><form method="get" action="">{% csrf_token %}{{form.as_p}}</form></div>');
    }); 
</script>

<html>
<button class="add_box">New Box</button>

<div id="canvas" style="background-color: #444; height: 90%">
<div class="box" style="height:auto; background-color: #eee;">
    <form method="POST" action="">
        {% csrf_token %}
        {{form.as_p}}
    </form>
</div>
</div>
</html>

当我不包含$('.add_box') 部分时,代码运行正常,一个深灰色的画布出现,左上角有一个框,表单在forms.py 中定义。在这种情况下,按钮按下当然不会做任何事情。当包含$('.add_box') 并省略&lt;div class="box" ... &gt; 部分时,按下按钮不会添加具有先前存在的表单的div。

这甚至可以使用 jQuery 以简单的方式完成吗?

【问题讨论】:

    标签: jquery django


    【解决方案1】:

    您收到错误是因为当您渲染 {{form.as_p}} 时,它包含换行符。如果您打开控制台并看到您会收到错误消息:

    Uncaught SyntaxError: '' string literal contains an unescaped line break
    

    从 Django 渲染到 javascript 并不是一个好主意,原因如下:

    1. 它允许潜在的 XSS 攻击。
    2. 它看起来不太好,而且是丑陋的 hack。

    那我们应该怎么做呢?那么为什么不简单地使用 HTML 作为两者之间的过渡呢?渲染一个额外的盒子,它将被隐藏。克隆它并删除隐藏的属性等并将其附加到您的 div:

    $( function() {
        $( ".box" ).draggable().resizable();
    } );
    
    // adding div and form on button click - this part causes error
    $('.add_box').click(function(){
        // Clone extra box, and remove duplicate ids
        let clone = $("#box-copy").clone().removeAttr("hidden").removeAttr("id");
        clone.find("*").removeAttr("id");
        // If it needs to be resizable and draggable, use below line.
        clone.draggable().resizable();
        // append it to div
        $('#canvas').append(clone);
    });
    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <button class="add_box">New Box</button>
    
    
    <!-- COPY OF BOX (HIDDEN) -->
    <div id="box-copy" class="box" style="height:auto; background-color: #eee;" hidden>
        <form id="test-id" method="get" action="">
            {% csrf_token %}
            {{form.as_p}}
        </form>
    </div>
    
    
    <div id="canvas" style="background-color: #444; height: 90%">
    <div class="box" style="height:auto; background-color: #eee;">
        <form method="POST" action="">
            {% csrf_token %}
            {{form.as_p}}
        </form>
    </div>
    </div>

    【讨论】:

    • 为什么要隐藏一个div?为什么不克隆已经存在于画布中的第一个 div 呢?
    • @Swati 出于某种原因在 OP 的 javascript 代码中,他们使用 GET 方法附加表单,而在 HTML 中,他们使用 POST 方法呈现表单。好吧,这很容易解决,但事实是,我们将不得不 1) 重置可能已在第一个 div 中输入的输入的表单。 2)动态添加也意味着人们可能想要动态删除等。所以只需将它作为隐藏元素添加一个额外的时间。
    猜你喜欢
    • 1970-01-01
    • 2013-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-06
    • 1970-01-01
    • 1970-01-01
    • 2016-10-06
    相关资源
    最近更新 更多