【问题标题】:How to get an object after been created using CreateView inside django CBV如何在 django CBV 中使用 CreateView 创建对象后获取对象
【发布时间】:2021-04-25 10:26:14
【问题描述】:

我正在尝试创建一个通知系统来跟踪我的用户的所有活动。为了实现这一点,我创建了两个模型,贡献模型和通知模型

class Contribution(models.Model):
    slug            =   models.SlugField(unique=True, blank=True, null=True)
    user            =   models.ForeignKey(User, on_delete=models.PROTECT)
    amount          =   models.DecimalField(default=0.00, max_digits=6, decimal_places=2)
    zanaco_id       =   models.CharField(max_length=20, blank=True, unique=True, null=True)

class Notification(models.Model):
    slug        =   models.SlugField(unique=True, blank=True)
    content_type    =   models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id       =   models.PositiveIntegerField()
    content_object  =   GenericForeignKey('content_type', 'object_id')
    message         =   models.TextField(null=True)

每次用户在 Contribution 表中创建对象时,我都想创建一个 Notification 对象,但在从 CreateView 创建对象时遇到一些困难

class ContributionAdd(CreateView):
    model           =   Contribution
    fields          = ['user', 'amount', 'zanaco_id']
    template_name   =   'contribution_add.html'


    def form_valid(self, form, *args, **kwargs):
        activity_ct = ContentType.objects.get_for_model("????")
        Notification.objects.create(content_type=activity_ct, object_id="?????",content_object=???,)
        return super().form_valid(form)

我怎样才能完成上述任务? 他们是使用 mixins 的一种方式吗?

【问题讨论】:

    标签: python django mixins django-class-based-views django-generic-relations


    【解决方案1】:

    该对象是在超级form_valid 方法中创建的,因此在调用该方法之前,您无法访问它。而是先调用 super 方法并使用self.object 来引用创建的对象:

    class ContributionAdd(CreateView):
        model           =   Contribution
        fields          = ['user', 'amount', 'zanaco_id']
        template_name   =   'contribution_add.html'
    
    
        def form_valid(self, form):
            response = super().form_valid(form) # call super first
            Notification.objects.create(content_object=self.object) # Why even pass the other values just pass `content_object` only
            return response
    

    【讨论】:

      【解决方案2】:

      一个优雅的方法是使用保存后信号:

      from django.dispatch import receiver
      from django.db.models.signals import post_save
      
      @receiver(post_save, sender=Contribution)
      def createNotification(sender, instance, created, **kwargs):
          if created:
              Notification.objects.create(content_type=activity_ct, object_id="?????",content_object=???,)
      

      【讨论】:

        猜你喜欢
        • 2012-10-29
        • 2016-10-18
        • 2018-12-09
        • 1970-01-01
        • 1970-01-01
        • 2011-09-07
        • 1970-01-01
        • 2015-03-31
        • 1970-01-01
        相关资源
        最近更新 更多