[Fixed]-How can I create initial values for a model in django?

1๐Ÿ‘

โœ…

You can use django signals to automatically create those by listening in on the signal for the user model.

Below is an example that run a few functions to recalculate stuff when an item is saved/deleted from an order.

from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver

@receiver((post_save, post_delete), sender='main.OrderItem')
def update_order_when_items_changed(sender, instance, **kwargs):
    order = instance.order
    order.set_weight()
    order.set_total_price()
    order.save()

So yours might look something like this (not tested):

@receiver((post_save,), sender='User')
def create_user_folders(sender, instance, created, **kwargs):
   if not created: return
   # generate MessageFolder && UserFolder
๐Ÿ‘คJared Mackey

0๐Ÿ‘

One issue I have realized over the years with signals is
they are neat to implement however they are synchronous.

Personally I would use subprocess or would suggest using thread to overcome the limitation of making it feel like asynchronous.
Or best you can have a cron job which queries the database and creates the folders.

๐Ÿ‘คPranav Garg

0๐Ÿ‘

Thanks @electrometro for pointing me in the right direction. This is my final working result:

class UserFolder(models.Model):
user          = models.ForeignKey(settings.AUTH_USER_MODEL, null = True, blank = True)
name          = models.CharField(max_length = 100)

@receiver((post_save), sender=User)
def create_user_folders(sender, instance, created, **kwargs):
    if not created: 
        return
    else:
        # generate MessageFolder && UserFolder
        draft_folder = UserFolder(None,instance.pk,"Draft")
        draft_folder.save()

        deleted_folder = UserFolder(None,instance.pk,"Deleted")
        deleted_folder.save()
        return
๐Ÿ‘คGustavo Reyes

Leave a comment