我正在构建一个具有嵌套模型formset的表单,用于为订阅者保存多个地址。我想指定controller
和region
字段的下拉列表。所以我在窗体集定义中添加了widgets属性。
city
这很好用,可以在下拉列表中选择值并将其保存到数据库中。当我再次访问AddressFormSet = modelformset_factory(
Address,
fields = (
'country',
'region',
'city',
'locality'
),
widgets = {
'region': Select(),
'city': Select()
},
extra=0
)
页面时,我发现subscriber_edit
和region
字段为空。
这是city
模型。
Address
这是class Address(models.Model):
subscriber = models.ForeignKey(SubscriberProfile, on_delete=models.CASCADE, related_name='address')
locality = models.CharField(max_length=100, blank=True, verbose_name="Locality")
city = models.CharField(max_length=40, verbose_name="City")
region = models.CharField(max_length=40, verbose_name="State")
country = models.CharField(max_length=200, verbose_name="Country")
视图。
subscriber_edit
当我在视图中def subscriber_edit(request, slug):
_subscriber = get_object_or_404(SubscriberProfile, slug=slug)
_address = Address.objects.filter(subscriber=_subscriber).all()
if request.method == 'POST':
subscriber_form = SubscriberForm(data=request.POST, instance=_subscriber, prefix='s')
addr_fmset = AddressFormSet(data=request.POST, prefix='addr')
if all([subscriber_form.is_valid(), addr_fmset.is_valid()]):
subscriber_form.save()
for form in addr_fmset:
addr = form.save(commit=False)
addr.subscriber = sub
addr.save()
return redirect('subscriber_preview', slug=_subscriber.slug)
else:
subscriber_form = SubscriberForm(instance=_subscriber, prefix='s')
addr_fmset = AddressFormSet(prefix='addr', queryset=_address)
return render(request, 'main/subscriber_edit.html', {
'sub_fm': subscriber_form,
'addr_fmset': addr_fmset
})
时,我发现print(addr_fmset)
和region
的值为空。
city
那么如何为formset中的字段指定select小部件?