我有一个django视图如下:
@login_required(login_url="login/")
def review(request):
table = DummyTable(DummyModel.objects.all())
form = DummyForm()
return render(request, 'review.html', {'reviews': table, 'DummyForm': form})
我正在传递默认DummyForm
这是一个django-crispy-form
(虽然这与问题无关,我认为),我需要根据用户点击的记录来填充它。表单本身看起来像:
from .models import DummyModel
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Field, ButtonHolder, Submit
from django.forms import ModelForm
class DummyForm(ModelForm):
class Meta:
model = DummyModel
fields = ['name', 'description', 'time_points']
def __init__(self, *args, **kwargs):
super(DummyForm, self).__init__(*args, **kwargs)
self.helper = FormHelper(self)
self.helper.form_class = 'form-horizontal'
self.helper.label_class = 'col-sm-2'
self.helper.field_class = 'col-sm-10'
self.helper.layout = Layout(
Field('name'),
Field('description'),
Field('time_points'),
ButtonHolder(
Submit('submit', 'Submit', css_class='button white')
))
现在,我有一个javascript函数,当用户点击某些链接并收到我想在表单中呈现的记录的主键时,会调用该函数。目前,它如下:
<script>
function EditDialog(pk) {
// Currently doing nothing with the primary key
// Is there a way to initialise the form with data using this key?
$( "#dialog" ).modal({width: 500, height: 500});
return false;
}
</script>
这个JS函数启动表单:
<div id="dialog" class="modal" title="Edit" style="display:none">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
<!-- Can I pass the primary key variable here??? -->
{% crispy DummyForm %}
</div>
</div>
</div>
</div>
所有这一切都很好,除了我在屏幕上显示一个空表格。如何将表单绑定到JS函数中主键给出的记录。
通常,在视图中我可以执行以下操作:
# As an example, just bind to the record with primary key=1
rec = DummyModel.objects.filter(pk=1).first()
form = DummyForm(model_to_dict(rec))
所以,在某种程度上我需要在我的模板中做类似的事情。
答案 0 :(得分:3)
在你的JS中,你可以向Django视图发出一个AJAX请求,该视图将返回填充了值的表单。
JS看起来像:
<script>
function EditDialog(pk) {
//ajax request to retrieve the populated form
$.ajax({
url: '/url/to/the/view/which/returns/the/populated/form',
method: 'GET',
data: {
pk: pk
},
success: function(formHtml){
//place the populated form HTML in the modal body
$('.modal-body').html(formHtml);
$( "#dialog" ).modal({width: 500, height: 500});
},
dataType: 'html'
});
return false;
}
</script>
处理AJAX请求的视图如下所示:
@login_required(login_url="login/")
def populate_form(request):
pk = request.GET.get('pk')
rec = DummyModel.objects.get(pk=pk)
form = DummyForm(model_to_dict(rec))
return render(request, 'form.html', {'DummyForm': form})
form.html
模板是一个非常简单的模板,它不会扩展您的基本模板,只会包含:
{% crispy DummyForm %}
请注意我保持代码简单,你必须在populate_form
视图中为pk添加验证并处理对populate_form
的unauth AJAX调用(例如:拥有该代码的用户)页面打开很长时间,会话已过期,单击编辑按钮)