简体   繁体   English

ModelForm字段未显示

[英]ModelForm field not showing

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) 那么在我看来,我有:(BACnetModbusContainer是一个自定义类)

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? 为什么我的ixModbusDevice不显示?

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更改为:

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. render()与带有context_instance参数的render_to_response()调用相同,该参数强制使用RequestContext。

Render Shortcut 渲染快捷方式

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 }}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM