30
According to the latest Django documentation, pre_save
does NOT send a created
argument. Post_save
however does. I could not find any reference of the signal sending created
since version 1.0.
69
Primary key attribute usually assigned by the database when the instance saved first time. So you can use something like if instance.pk is None
- [Django]-Django: How to check if the user left all fields blank (or to initial values)?
- [Django]-Django – iterate number in for loop of a template
- [Django]-Are Django SECRET_KEY's per instance or per app?
24
I am not sure if this is the recommended way but @Radagast’s method didnt work for me(not sure if its because I use custom Pk’s).
I tried the following(not sure if this is the best way):
@receiver(pre_save, sender=YourModelName, weak=False, )
def presave_payment_model_check(sender, instance=None, created=False, **kwargs):
#Reference: https://stackoverflow.com/questions/11561722/django-what-is-the-role-of-modelstate
if instance._state.adding:
# we would need to create the object
print "Creating an object"
else:
#we are updating the object
print "Updating an object"
Reference: Django : What is the role of ModelState?
- [Django]-Django model manager objects.create where is the documentation?
- [Django]-AssertionError: database connection isn't set to UTC
- [Django]-Force django-admin startproject if project folder already exists
12
You can easily check if an instance is created or updated in pre_save in this way:
@receiver(pre_save, sender=MyModel)
def pre_save_user(sender, instance, **kwargs):
if instance._state.adding:
print ('Instance created!')
else:
print ('Instance updated!')
Tested with Django 3.0.
- [Django]-Django-rest-framework http put failing with 415 on django 1.5
- [Django]-Django: add image in an ImageField from image url
- [Django]-What is reverse()?
4
Using instance._state.adding is the most logical approach, as you will be able to tell the model state exists or is new, regardless whether the primary key as been assigned or not.
- [Django]-Pagination in Django-Rest-Framework using API-View
- [Django]-How to show ALL keys through redis-cli?
- [Django]-Django ModelForm with extra fields that are not in the model
- [Django]-Generating file to download with Django
- [Django]-How do I restart celery workers gracefully?
- [Django]-Django set DateTimeField to database server's current time
0
You can try this.
@receiver(pre_save, sender=User)
def user(instance, *args, **kwargs):
if instance.id != None:
- [Django]-Readonly models in Django admin interface?
- [Django]-Folder Structure for Python Django-REST-framework and Angularjs
- [Django]-Find Monday's date with Python