我的django ModelAdmin类中有一个过分的save_model()
方法。此模型具有ManyToMany
字段。
我的save_model
看起来像这样:
def save_model(self, request, obj, form, change):
creating = False
to_delete = False
if not obj.pk:
creating = True
obj.save()
form.save_m2m()
# DETECT SOMETHING (some complicated conditions) HERE ...
detected =True
if detected:
obj.delete() # --> here is my problem
Traceback:
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/Library/Python/2.7/site-packages/django/contrib/admin/options.py" in wrapper
366. return self.admin_site.admin_view(view)(*args, **kwargs)
File "/Library/Python/2.7/site-packages/django/utils/decorators.py" in _wrapped_view
91. response = view_func(request, *args, **kwargs)
File "/Library/Python/2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
89. response = view_func(request, *args, **kwargs)
File "/Library/Python/2.7/site-packages/django/contrib/admin/sites.py" in inner
196. return view(request, *args, **kwargs)
File "/Library/Python/2.7/site-packages/django/utils/decorators.py" in _wrapper
25. return bound_func(*args, **kwargs)
File "/Library/Python/2.7/site-packages/django/utils/decorators.py" in _wrapped_view
91. response = view_func(request, *args, **kwargs)
File "/Library/Python/2.7/site-packages/django/utils/decorators.py" in bound_func
21. return func(self, *args2, **kwargs2)
File "/Library/Python/2.7/site-packages/django/db/transaction.py" in inner
209. return func(*args, **kwargs)
File "/Library/Python/2.7/site-packages/django/contrib/admin/options.py" in add_view
956. self.save_related(request, form, formsets, False)
File "/Library/Python/2.7/site-packages/django/contrib/admin/options.py" in save_related
731. form.save_m2m()
File "/Library/Python/2.7/site-packages/django/forms/models.py" in save_m2m
83. f.save_form_data(instance, cleaned_data[f.name])
File "/Library/Python/2.7/site-packages/django/db/models/fields/related.py" in save_form_data
1273. setattr(instance, self.attname, data)
File "/Library/Python/2.7/site-packages/django/db/models/fields/related.py" in __set__
859. manager = self.__get__(instance)
File "/Library/Python/2.7/site-packages/django/db/models/fields/related.py" in __get__
846. through=self.field.rel.through,
File "/Library/Python/2.7/site-packages/django/db/models/fields/related.py" in __init__
538. (instance, source_field_name))
Exception Type: ValueError at /admin/lawis_core/invoice/add/
Exception Value: "<Invoice: 1301000>" needs to have a value for field "invoice" before this many-to-many relationship can be used.
答案 0 :(得分:1)
难道只是忘了打电话给超级班吗?像这样:
class YourAdmin(admin.ModelAdmin)
def save_model(self, request, obj, form, change):
super(YourAdmin, self).save_model(request, obj, form, change)
# Your code ...