Django CreateView: How to perform action upon save

后端 未结 2 1121
小蘑菇
小蘑菇 2020-12-03 01:22

I\'m using a custom CreateView (CourseCreate) and UpdateView (CourseUpdate) to save and update a Course. I want to take an action when the Course is saved. I will create a n

2条回答
  •  难免孤独
    2020-12-03 01:39

    I would suggest to use Django's Signal. That is an action that gets triggered when something happens to a Model, like save or update. This way your code stays clean (no business logic in the form-handling), and you are sure that it only gets triggered after save.

    #views.py
    from django.dispatch import receiver
    ...
    
    @receiver(post_save, sender=Course)
    def post_save_course_dosomething(sender,instance, **kwargs):
        the_faculty = instance.faculty
        #...etc  
    

提交回复
热议问题