问题描述
我是django(1.8)的新手,已经阅读了此问题,所有内容均指向根据此链接覆盖save_formset函数
I'm relatively new to django (1.8) and have read around this issue which all points to overriding the save_formset function as per this link
已添加到旧线程中( Django admin-如何保存内联吗?),但想作为一个单独的线程提出来获得更好的可见性,此外,这已经得到了解答.
Had added to an old thread (Django admin - how to save inlines?) but wanted to raise as a separate thread to get better visibility and besides this already been answered.
下面的函数在我试图在保存之前修改表单的地方起作用,即,将(创建/修改的)审核字段更新为USER,并将"enum_value_en"属性小写.当用户仅输入1个条目时所有方法都起作用,但是当添加更多条目时,它将使用SAME值(即数据库中的"enum_value_en")更新所有条目.
The function below works where I'm trying to amend the form before saving it, i.e. updating the audit fields (created/modified) to the USER and lowercase the 'enum_value_en' attribute. All works when user enters just 1 entry but when adding more it updates ALL entries with the SAME value (i.e. 'enum_value_en' in the database.
def save_formset(self, request, form, formset, change):
instances = formset.save(commit=False) # gets instance from memory and add to it before saving it
for obj in formset.deleted_objects:
obj.delete()
for instance in instances:
for form in formset: # cleaned_data is only available on the form, so you have to iterate over formset
instance.modified_by = request.user
instance.created_by = request.user
instance.lowercase_enum_value_en = form.cleaned_data['enum_value_en'].lower()
instance.save()
formset.save_m2m()
-
Ex.
Ex.
如果条目为'a'&'b',两个记录的小写属性都设置为'b'.
if entries are 'a' & 'b', the lowercase attributes are set to 'b' on both records.
PS .如果有人可以对他们的建议提出一些意见,以便我能理解每一行代码,也将不胜感激.
PS. Would also be grateful if anyone could offer some comments around their suggestions so that I can understand each line of code.
最感谢.
推荐答案
问题是您要遍历实例,然后遍历其中的表单集.说有5种形式,这意味着您将每个实例保存5次,每个实例一次.每个实例的最终表单集中的值都将相同.
The problem is that you are looping over the instances, and then looping over the formsets within that. Say there are 5 forms, that means you are saving each instance 5 times, once for each instance. Every instance will end up with the same value from the final formset.
在这种情况下,我认为您不需要访问表单的
cleaned_data
.只需访问实例的enum_value_en
属性即可.这意味着您不需要引起问题的内部循环.In this case, I don't think you need to access the form's
cleaned_data
. Just access the instance'senum_value_en
attribute. This means that you don't need the inner loop that is causing your problem.for instance in instances: instance.lowercase_enum_value_en = instance.enum_value_en.lower() instance.modified_by = request.user instance.created_by = request.user instance.save()
这篇关于Django Admin-保存内联覆盖save_formset的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!