我已按照以下说明向ModelForm添加了一个自定义字段,但是我无法在UpdateView中访问该字段。我曾尝试打印对象,但是字段device_circuit_subnet不在其中,而且在对象外部引用它也会引发错误。
是否有可能以模型形式获取自定义字段的值,以便在保存对象之前可以使用它?
谢谢
forms.py
class SiteServiceForm(forms.ModelForm):
class Meta:
model = DeviceCircuitSubnets
fields = ['device','circuit','subnet','monitored','interface_name','get_bgp','wb_bgp','db_bgp','get_interface','wb_interface','db_interface','get_aws','wb_aws','db_aws']
def __init__(self, *args, **kwargs):
self.is_add = kwargs.pop("is_add", False)
site_id = kwargs.pop("site_id")
super(SiteServiceForm, self).__init__(*args, **kwargs)
self.fields['device'].required = False
self.fields['circuit'].required = False
self.fields['subnet'].required = False
self.fields['device_circuit_subnet'] = DeviceCircuitSubnetField(
queryset=DeviceCircuitSubnets.objects.filter(device__site_id=site_id).select_related(
'device', 'circuit', 'subnet'
),
label='Device / Circuit / Subnet'
)
self.helper = FormHelper(self)
self.helper.form_id = 'site_service_form'
self.helper.form_method = 'POST'
self.helper.layout = Layout(
Div(
Div(
Div(HTML('<i class="fa fa-bolt fa-fw"></i> Service'), css_class='card-header'),
Div(
Div(
Div(
Field('device_circuit_subnet', css_class='chosen'),
css_class='col-lg-6'
),
Div(
...
views.py
class AddSiteService(PermissionRequiredMixin, CreateView):
form_class = SiteServiceForm
template_name = "app_settings/tabs_form.html"
permission_required = 'config.add_device_circuit_subnet'
def dispatch(self, *args, **kwargs):
self.site_id = self.kwargs['site_id']
return super(AddSiteService, self).dispatch(*args, **kwargs)
def get_success_url(self, **kwargs):
return reverse_lazy("config:site_services", args=(self.site_id))
def get_form_kwargs(self, *args, **kwargs):
kwargs = super().get_form_kwargs()
kwargs['is_add'] = True
kwargs['site_id'] = self.site_id
return kwargs
def form_valid(self, form):
self.object = form.save(commit=False)
print(vars(self.object))
dcs_id = self.device_circuit_subnet
print('ID: {}'.format(dcs_id))
self.object.save()
控制台输出表单打印对象
{'_state': <django.db.models.base.ModelState object at 0x7f31fedefcf8>, 'id': None, 'device_id': None, 'circuit_id': None, 'subnet_id': None, 'active_link': False, 'active_link_timestamp': None, 'monitored': False, 'interface_name': 'll', 'get_bgp': False, 'wb_bgp': False, 'db_bgp': False, 'get_interface': False, 'wb_interface': False, 'db_interface': False, 'get_aws': False, 'wb_aws': False, 'db_aws': False}
答案 0 :(得分:1)
该字段的格式为cleaned_data。
Error HDF5File::listChildren(const string &location) {
try {
Group group = _file.openGroup(location);