如何在 modelformset_factory 中设置每个表单的样式
How to style each form in modelformset_factory
我正在尝试为 modelformset_factory 中的每个表单设置样式。但是即使我使用table我也做不到,它无法保存最后一个(空表格)
这是我的视图函数
from django.shortcuts import render
from django.forms import modelformset_factory
from .models import Offer
def offer_forms(request):
OfferFormSet = modelformset_factory(Offer, fields=('name', 'url', 'image', 'active'))
formset = OfferFormSet()
if request.method == 'POST':
formset = OfferFormSet(request.POST, request.FILES)
if formset.is_valid():
instances = formset.save(commit=False)
for form in instances:
form.save()
formset = OfferFormSet()
context = {
'formset': formset,
}
return render(request, 'offers.html', context)
这是我的 Html 文件:
{% extends 'base.html' %}
<style media="screen">
*{
box-sizing: border-box;
}
</style>
{% block content %}
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ formset.management_form }}
<table class="table table-stripped">
{% for form in formset %}
<tr>
<td>
{{ form }}
</td>
</tr>
<td>
<input type="submit" value="Submit" class="btn btn-sm btn-primary">
</td>
{% endfor %}
</table>
</form>
{% endblock content %}
modelformset_factory 接受 form 作为 kwargs,因此您可以通过覆盖其 init 功能如 styling django ModelForm 中所述,并在 modelformset_factory
中使用该样式的形式
OfferFormSet = modelformset_factory(Offer, form=StyledOfferForm , fields=('name', 'url', 'image', 'active'))
我正在尝试为 modelformset_factory 中的每个表单设置样式。但是即使我使用table我也做不到,它无法保存最后一个(空表格)
这是我的视图函数
from django.shortcuts import render
from django.forms import modelformset_factory
from .models import Offer
def offer_forms(request):
OfferFormSet = modelformset_factory(Offer, fields=('name', 'url', 'image', 'active'))
formset = OfferFormSet()
if request.method == 'POST':
formset = OfferFormSet(request.POST, request.FILES)
if formset.is_valid():
instances = formset.save(commit=False)
for form in instances:
form.save()
formset = OfferFormSet()
context = {
'formset': formset,
}
return render(request, 'offers.html', context)
这是我的 Html 文件:
{% extends 'base.html' %}
<style media="screen">
*{
box-sizing: border-box;
}
</style>
{% block content %}
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ formset.management_form }}
<table class="table table-stripped">
{% for form in formset %}
<tr>
<td>
{{ form }}
</td>
</tr>
<td>
<input type="submit" value="Submit" class="btn btn-sm btn-primary">
</td>
{% endfor %}
</table>
</form>
{% endblock content %}
modelformset_factory 接受 form 作为 kwargs,因此您可以通过覆盖其 init 功能如 styling django ModelForm 中所述,并在 modelformset_factory
中使用该样式的形式OfferFormSet = modelformset_factory(Offer, form=StyledOfferForm , fields=('name', 'url', 'image', 'active'))