save_model()
我的django ModelAdmin 类中有一个被覆盖的方法。这个模型有一个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.