python - 在 Django 的引导模式中打开新视图
问题描述
我的情况是我有几个模式(确切地说是 4 个),应该可以在我的应用程序的每个视图中访问。我将仅使用一个作为示例。让我们看看我是如何在主屏幕视图上显示它的:
base.html
...abbreviated...
<a data-toggle="modal" href="#exampleModal">Shipment</buton>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Create Shipment</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form method="POST">
{% csrf_token %}
<div class="modal-body">
{{shipmentForm|crispy}}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" name="shipment" class="btn btn-primary">Save changes</button>
</form>
</div>
</div>
</div>
</div>
这是传递shipmentForm
给该模板的视图
视图.py
def HomeView(request):
if request.method == 'POST':
shipment_form = CreateShipmentForm(request.POST)
if shipment_form.is_valid():
new_shipment = shipment_form.save()the user to the success page
return redirect('ShipmentListView')
shipmentForm = CreateShipmentForm()
context = {
'shipmentForm': shipmentForm,
}
return render(request, 'home.html', context)
这工作得很好,但问题是,我需要在我的应用程序的每个视图中包含来自 HomeView 的这段代码。那将是我自己的很多重复。我已经在我的 base.html 中包含了模态的 html,这样我就不必重复了。但不是我上面所说的,我想让启动模式的按钮看起来/做这样的事情。
base.html
<a data-toggle="modal" href="{% url 'CreateShipmentView' %}>Shipment</buton>
将模态表单的 html 放在单独的文件中:
模态的.html
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Create Shipment</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form method="POST">
{% csrf_token %}
<div class="modal-body">
{{shipmentForm|crispy}}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" name="shipment" class="btn btn-primary">Save changes</button>
</form>
</div>
</div>
</div>
</div>
然后有这样的视图:
def CreateShipmentView(request):
if request.method == 'POST':
shipment_form = CreateShipmentForm(request.POST)
if shipment_form.is_valid():
new_shipment = shipment_form.save()the user to the success page
return redirect('ShipmentListView')
shipmentForm = CreateShipmentForm()
context = {
'shipmentForm': shipmentForm,
}
return render(request, 'modal.html', context)
如果不使用 django-modal-bootstrap 包,这怎么可能?我试过了,但它似乎非常敏感,我不喜欢它,所以宁愿避免这种情况。谁能指出我如何使这项工作的方向?