这是我的观点:
class EditInventoryView(UpdateView):
model = Inventory
form_class = InventoryForm
template_name = 'inventory/detail.html'
def get(self, request, **kwargs):
object = super(EditInventoryView, self).get_object()
formset = self.form_class(instance=object)
context = {
'form': formset,
'item': object,
}
return render(request, 'inventory/detail.html', context)
def post(self, request, **kwargs):
object = super(EditInventoryView, self).get_object()
form = self.form_class(request.POST, request.FILES, instance=object)
context = {
'form': form,
'item': object,
}
if form.is_valid():
object = form.save()
messages.success(request, "Saved %s!" % object)
return redirect(object.get_absolute_url())
else:
messages.error(request, 'Change a few things up and try submitting again. %s' % form.errors)
return render(request, 'inventory/detail.html', context)
当我提交时,这始终是错误消息:
更改一些内容并尝试重新提交。
<ul class="errorlist"><li>connections<ul class="errorlist"><li>This field is required.</li></ul></li></ul>
我知道这个用来工作的表单,但也许我在模型中改变了一些不起作用的东西。
模特:
class Inventory(MPTTModel):
type = models.ForeignKey('inventory_types.Type', db_column='type_id')
name = models.TextField(db_column='value')
asset_tag = models.IntegerField(db_column='asset_tag', unique=True, null=True, blank=True)
parent = TreeForeignKey('self', null=True, blank=True, related_name='children')
connections = models.ManyToManyField('self', related_name='connections')
objects = InventoryManager()
tree = TreeManager()
class Meta:
db_table = 'inventory'
verbose_name_plural = 'Inventory Items'
class MPTTMeta:
order_insertion_by = ['type']
def __unicode__(self):
return u'[%s] %s' % (self.type.name, self.name)
def get_related_descendants(self, include_self=False):
return self.get_descendants(include_self=include_self) \
.select_related('type', 'parent').prefetch_related('connections')
def get_related_ancestors(self, include_self=False):
return self.get_ancestors(include_self=include_self) \
.select_related('type', 'parent').prefetch_related('connections')
def get_absolute_url(self):
return reverse('inventory:view', args=(self.id,))
def add_anc_type(self, id, all_types, all_objects):
if id is not self.id: all_types.add(all_objects[id][1])
if all_objects[id][0] is not None:
self.add_anc_type(all_objects[id][0], all_types, all_objects)
def add_desc_type(self, id, all_types, all_objects):
if id not in all_objects: return
for child, type_id in all_objects[id].iteritems():
all_types.add(type_id)
self.add_desc_type(child, all_types, all_objects)
答案 0 :(得分:2)
在连接上设置blank=True
将删除表单的错误。如果您希望文件在数据库中可以为空,那么您可以设置null=True
或仅设置默认值。
要删除表单错误,您只需执行此操作:
connections = models.ManyToManyField('self', related_name='connections', blank=True)
希望这有帮助!