我有一个 ActionAdmin 模型,在 InvoiceAdmin 模型中用作 ActionAdminInline。
在 InvoiceModel 中,我覆盖了 save_formset,以自动设置一些值。为每个 Action 实例设置值没有问题,但我无法获取父 Invoice 的字段。
我认为它必须是self或self.project.pk 我还尝试通过在其他线程中看到的form.project.pk来获取它。
我得到的错误是关于 InvoiceAdmin 中没有这样的字段。这对我来说很有意义,self 是一个 InvoiceAdmin 对象,而不是一个 Invoice 对象。我想我必须获取 Invoice 对象字段来设置 Action instance.invoice 和 instance.project。
有人知道,如何获得这个父对象的值???
看起来像这样:
class ActionAdmin(admin.ModelAdmin):
...
class ActionInlineForm(ModelForm):
class Meta:
model = Action
fields = ['name','tax', 'price','duration_extern',]
class ActionInline(admin.TabularInline):
model = Action
form = ActionInlineForm
extra = 0
ordering = ('date_finished',)
can_delete=False
readonly_fields = ['non_editable_date_finished','non_editable_duration','get_remove_invoice_pos_link']
class InvoiceAdmin(admin.ModelAdmin):
...
...
...
inlines = [ActionInline,]
...
...
...
def save_formset(self, request, form, formset, change):
instances = formset.save(commit=False)
for instance in instances:
usr = User.objects.get(id=7)
try:
instance.created_by = instance.created_by
except:
instance.created_by = usr
try:
instance.owner = instance.owner
except:
instance.owner = usr
instance.modified_by = usr
try:
instance.date_created = instance.date_created
except:
instance.date_created = date.today
instance.date_modified = date.today:
### MAN, This WORKS NOW ###
try:
instance.project = instance.project
except:
pr = Project.objects.get(id=instance.invoice.project.id)
instance.project = pr
actstat = ActionStatus.objects.get(id=2)
instance.actionstatus = actstat
try:
instance.actioncategory = instance.actioncategory
except:
cat = ActionCategory.objects.get(id=9)
instance.actioncategory = cat
instance.done = True
instance.billed = True
instance.save()
formset.save_m2m()
这是错误消息:
AttributeError at /workflow/invoice/21/
...
Exception Type: AttributeError
Exception Value: 'InvoiceAdmin' object has no attribute 'id'
...
Traceback
form <django.forms.models.InvoiceForm object at 0x7f7f7421de10>
instances [<Action: aaaaa>]
self <workflow.admin.InvoiceAdmin object at 0x7f7f7421dad0>
问题是,self 对象是 InvoiveAdmin 而不是 Invoice?我的意思是实例对象是 Action 而不是 ActionAdmin?!