我有Bootstrap Modal包含表单。当验证表单失败时,将重定向到原始表单页面。问题是如何使服务器发送我的响应与错误在我的引导模式?
urls . py
url(r'^add/$', CreateCarView.as_view(), name='add_auto'),
views.py
class CreateCarView(CreateView):
model = Car
template_name = 'automobiles/automobiles_add.html'
fields = '__all__'
def get_success_url(self):
messages.success(self.request, 'Авто успішно додано')
return reverse('home')
def post(self, request, *args, **kwargs):
if request.POST.get('cancel_button'):
messages.info(self.request, 'Додавання відмінено')
return HttpResponseRedirect(reverse('home'))
else:
return super(CreateCarView, self).post(request, *args, **kwargs)
base.html
<div class="row">
<div class="col-xs-4">
<button type="button" class="btn btn-warning" data-toggle="modal" data-target="#myModal"
data-remote="{% url 'add_auto' %}">
Open Modal
</button>
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog modal-sm">
<!-- Modal content-->
<div class="modal-content">
</div>
</div>
</div>
</div>
</div>
automobiles_add.html
<form id="add_item" class="form" role="form" action="{% url 'add_auto' %}" method="post">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Додати авто</h4>
</div>
<div class="modal-body">
{% csrf_token %}
{{ form.as_p }}
</div>
<div class="modal-footer">
<input class="btn btn-success" type="submit" value="Додати тачку" name="add_button">
<input class="btn btn-danger" type="submit" value="Відмінити" name="cancel_button">
</div>
这可能看起来像一个hack,但如果表单上有错误,你可以手动启动模态,如
<form id="add_item" class="form" role="form" action="{% url 'add_auto' %}" method="post">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Додати авто</h4>
</div>
<div class="modal-body">
{% csrf_token %}
{{ form.as_p }}
</div>
<div class="modal-footer">
<input class="btn btn-success" type="submit" value="Додати тачку" name="add_button">
<input class="btn btn-danger" type="submit" value="Відмінити" name="cancel_button">
</div>
{% if form.errors %}
<script>
$(function() {
$('#myModal').modal({show: true});
});
</script>
{% endif %}
之类的
希望能有所帮助
当你提交时,正常形式的提交正在发生,而不是你可以使用ajax发布,这是一个示例ajax代码。
$(document).on('submit', '#add_item', function() {
$.ajax({
type: $(this).attr('method'),
url: this.action,
data: $(this).serialize(),
context: this,
success: function(data, status) {
location.reload();
},
error: function (request, type, errorThrown) {
$('#add_item').html(request.responseText);
}
});
return false;
})