简体   繁体   中英

django : How to use signals?

After creating a user account with this model:

class User(auth.models.User, auth.models.PermissionsMixin):

    def __str__(self):
        return "@{}".format(self.username)

The form:

class UserCreateForm(UserCreationForm):
    class Meta:
        fields = ("first_name", "last_name", 
                  "username", "email", "password1", "password2")
        model = get_user_model()

I want an default entry into another model from another application yet in the same project

class History(models.Model):
    name = models.CharField(max_length = 50)
    employee_ID = models.CharField(max_length = 20)
    earned_leave = models.IntegerField(default = 10)
    casual_leave = models.IntegerField(default = 10)
    sick_leave = models.IntegerField(default = 10)
    paid_leave =models.IntegerField(default = 10)

where employee_ID is the username and name is the first_name.

I have tried using a signal but I have no idea how to send the values into the database.

def send_data(sender, instance, created, **kwargs):
    print('data sent') 

post_save.connect(receiver = send_data, sender= User)

Instead of this print statement what should I write in order to send the code into History table in the database. I'm working on a human management system.

Its too simple. you can write your saving history code here:

def send_data(sender, instance, created, **kwargs):
    from your_app.models import History
    history = History()
    history.employee_ID = instance.username
    history.name = instance.first_name
    ....
    history.save()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM