这是我的看法:
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)