我使用模型formset允许用户动态地向表中添加重复的表单(modbus寄存器,因为设备可以有多个寄存器)。
我遇到的问题是,只要我保存formset(存储到db),当我回到同一页面创建一个带寄存器的新设备时,django会渲染所有以前创建的表单只有一个空表格(然后能够添加表格)。
以下是在我的formset中创建3个表单(存储在db中)后的示例:
它应该只在我的formset中显示1个空表单,然后用户可以动态添加表单。
我的观点:
def create_modbus_view(request):
modbus_device = CreateModbusForm()
RegisterFormset = modelformset_factory(Register, form=ModbusRegistersForm)
register_forms = RegisterFormset()
return render(
request,
'app/create_modbus.html',
context_instance = RequestContext(request,
{
'title':'Create Modbus Device',
'tag': 'create_modbus',
'modbus_device': modbus_device,
'register_forms': register_forms
})
)
模型:
class Register(models.Model):
ixRegister = models.AutoField(primary_key=True)
sRegisterName = models.CharField(max_length=100)
iStartingAddr = models.IntegerField()
bRange = models.BooleanField(default=False)
ixRegisterType = models.ForeignKey(RegisterType)
iOffset = models.IntegerField(blank=True, null=True)
class Meta:
db_table = 'TRegister'
class ModbusDevice(models.Model):
ixModbusDevice = models.AutoField(primary_key=True)
sModbusName = models.CharField(verbose_name='Device Name',max_length=100)
iPort = models.IntegerField(verbose_name='Port')
iSlave = models.IntegerField(verbose_name='Slave ID')
sIP = models.GenericIPAddressField(verbose_name='IP Address')
class Meta:
db_table = 'TModbusDevice'
形式:
class ModbusRegistersForm(ModelForm):
ixRegisterType = ModelChoiceField(queryset=RegisterType.objects.all()),
bRange = BooleanField(required=False)
bRange.widget.attrs['data-form'] = 0
class Meta:
model = Register
fields = ['sRegisterName','iStartingAddr','bRange','ixRegisterType','iOffset']
widgets = {
'sRegisterName': TextInput(attrs={'placeholder': 'Register Name','class': 'form-control', 'data-form': '0'}),
'iStartingAddr': TextInput(attrs={'placeholder': 'Starting address','class': 'form-control','data-form': '0'}),
'iOffset': TextInput(attrs={'placeholder': 'Address offset','class': 'form-control','data-form': '0'}),
}
class CreateModbusForm(ModelForm):
class Meta:
model = ModbusDevice
fields = ['sModbusName','iPort', 'iSlave', 'sIP']
widgets = {
'sModbusName': TextInput(attrs={'placeholder': 'Device Name','class': 'form-control','id': 'device-name',}),
'iPort': TextInput(attrs={'placeholder': 'Port','class': 'form-control','id': 'port',}),
'iSlave': TextInput(attrs={'placeholder': 'Slave id','class': 'form-control','id': 'slave-id',}),
'sIP': TextInput(attrs={'placeholder': 'Modbus IP address','class': 'form-control','id': 'ip-address',})
}
答案 0 :(得分:1)