【发布时间】: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>
我知道,如果有一个按钮<button class="add_box">New Box</button>,相应的添加新元素的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') 并省略<div class="box" ... > 部分时,按下按钮不会添加具有先前存在的表单的div。
这甚至可以使用 jQuery 以简单的方式完成吗?
【问题讨论】: