I know this is very simple but I've been at this for longer it should be and cannot find what I did wrong here.
I have a modelform where I want to include the primary key, and the name:
class ModbusDevice(models.Model):
ixModbusDevice = models.AutoField(primary_key=True)
sModbusName = models.CharField(verbose_name='Device Name',max_length=100)
class BACnetModbusDeviceForm(ModelForm):
class Meta:
model = ModbusDevice
fields = ['ixModbusDevice', 'sModbusName']
widgets = {
'ixModbusDevice' : TextInput(),
'sModbusName' : TextInput(attrs={'class': 'form-control', 'readonly': True}),
}
then in my view I have: (BACnetModbusContainer is a custom class)
class BACnetModbusContainer:
modbus_devices = None
bacnet_devices = None
method:
modbus_devices = ModbusDevice.objects.all()
devices = []
for idx,device in enumerate(modbus_devices):
container = BACnetModbusContainer()
container.bacnet_devices = BACnetDeviceForm(prefix="bacnet_" + str(idx))
container.modbus_devices = BACnetModbusDeviceForm(instance=device, prefix="modbus_" + str(idx))
devices.append(container)
return render(
request,
'app/create_bacnet.html',
context_instance = RequestContext(request,
{
'title':'Create BACnet Device',
'tag': 'create_bacnet',
'devices': devices
})
)
then in my template:
{% for device in devices %}
<tr>
<td>
{{ device.modbus_devices.sModbusName }}
{{ device.modbus_devices.ixModbusDevice }}
</td>
</tr>
{% endfor %}
Why is my ixModbusDevice
not showing?
Because it's an AutoField. Your can't set those; they are automatically assigned by the database, hence the name. Therefore there's no point in showing then on the form.
Try change the return
to :
return render(
request,
'app/create_bacnet.html',
{
'title':'Create BACnetDevice',
'tag':'create_bacnet',
'devices': devices
}
)
render() is the same as a call to render_to_response() with a context_instance argument that forces the use of a RequestContext.
managed to skip the rendering. I'm able to access the primary key via the "inital" attribute when I'm iterating all the devices:
{{ device.modbus_devices.initial.ixModbusDevice }}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.