I created a custom user subclassed from AbstractUser and a post_save signal and a receiver that prints the new user's id.
@receiver(post_save, sender=CustomUser, dispatch_uid='members.models.customuser.post_save') def post_save_custom_user(sender, instance=None, created=False, **kwargs): if not created: return print('post_save_custom_user: {}'.format(instance.id))
When I create a new user via the admin interface the receiver is called once. When I import a user using
django-import-export
the receiver is called twice: once after the initialSubmit
of the import file and then again after theConfirm Import
. Browsing through the code I see it creates the user in dry_run, rolls back the transaction and creates it again. But how can I tell in my receiver if it's a dry run or not?I am using Python 3.6, Django 3.0.3, django-import-export 2.0.1
score:0
Thanks for this. Does anyone know why Django-import-export calls the save() method twice for a model during an import with confirm using dry_run = True ? As far as I can see the import data is only temp saved to a temp location in memory or disk and is not actually written to the DB.
To get my solution working I needed to use the solution above using after_save_instance on the Model Resource but... For single instance additions using a CreateView I needed to adjust my form_valid method to carry out an action when a new instance of the model is created:
class MyCreateView(CreateView):
model = MyModel
fields = [ 'email', 'name']
def form_valid(self, form):
self.object = form.save()
self.object.save()
## Perform action here like send email etc.
return HttpResponseRedirect(self.get_success_url())
score:0
I have fixed this issue by using the "dry-run" flag.
My Resource class is like:
class SentenceResource(resources.ModelResource):
def before_save_instance(self, instance, using_transactions, dry_run):
instance.dry_run = dry_run # set a temporal flag for dry-run mode
class Meta:
model = Sentence
And my signal is like:
@receiver(post_save, sender=Sentence)
def create_sentence(sender, instance=None, created=False, **kwargs):
if hasattr(instance, 'dry_run'):
if instance.dry_run:
return # not send to elastic search
else:
pass
if created:
...
else:
...
score:7
It appears that django-import-export triggers the post_save
on an import confirmation and then again after the import. Recommendations to use on_commit
didn't work for me, hence I had to stop using the signals. There's ModelResource.after_save_instace
method though:
class MyResource(ModelResource):
class Meta:
model = MyModel
def after_save_instance(
self, instance: MyModel, using_transactions: bool, dry_run: bool,
):
super().after_save_instance(instance, using_transactions, dry_run)
if dry_run is False:
my_model_on_save_action(instance)
Credit To: stackoverflow.com
Related Query
- Django post save signal getting called twice despite uid
- django session post save called twice
- Why is post_save being raised twice during the save of a Django model?
- Django import export - Unable to import model with BinaryField
- Create UUID on client and save primary key with Django REST Framework and using a POST
- Django Rest Framework view get_queryset is called twice
- Initiate post save on Django abstract parent model, when child model saved
- Using Django Server Sent Events with Database post save
- django view called twice
- Django Import Export - UNIQUE constraint failed
- Django import export Line number: 1 - u"Column 'id' not found
- jQuery AJAX request gets called twice when using Jquery, Django and Google App Engine
- How can I run some code when a Django modelβs save method is called for the first time?
- Is it okay to spawn a thread from django post save signal?
- Django view getting called twice (double GET request)
- Django model form saving simultaneously post request twice
- Manual Post Save Signal creation makes the application slow, Django
- How to access row data in before_save_instance for Django Import Export
- Update model fields based on POST data before save with Django Rest Framework
- Django import export has error "Tablib has no format 'None' or it is not registered"
- Import and save thumbnailphoto from ldap to django imagefield
- Django view seems to be called twice
- Django - Save modelForm even if no field are changed on POST
- Django custom context processor being called twice per request
- django import export app error: django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet
- Django admin.py: save_model() is not called by model.save() in save method of ModelForm
- How to save user when saving a form using post within Class-Based Views in Django
- how i save post with the current user without viewing all user list in the endpoint in django rest framework
- Django Model Override Only Works if I Save Twice
- How to save POST data with multiple checkboxes using Django ?
More Query from same tag
- how to include css in node_modules folder from Django project?
- Django order_by sum of fields
- The 'plan_image' attribute has no file associated with it
- Extending database-backed session engines
- Understanding the requirement for the related field to provide a queryset
- How can I delete form field data in django after submit
- Django : "TypeError: unsupported operand type(s) for +: 'FloatField' and 'FloatField'"
- How to filter object from model User into list
- File descriptor doesn't update for logging in Django
- django model formset update only
- How to assign Group permissions to individual records in Django
- How to add extra fields to a django model by extending it?
- Django management command doesn't flush stdout
- django.db.utils.OperationalError: my_table has no column id error?
- Django: form with fields for creating related objects