简体   繁体   English

如何在 django CBV 中使用 CreateView 创建 object

[英]How to get an object after been created using CreateView inside django CBV

am trying to create a notification system that tracks all the activities of my users.我正在尝试创建一个通知系统来跟踪我的用户的所有活动。 to achieve this I have created two models, The Contribution model and Notifition model为了实现这一点,我创建了两个模型,贡献 model 和通知 model

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)

I want to create a Notification object each time a user creates an object in the Contribution table, but am having some difficulties in getting the object created from CreateView每次用户在贡献表中创建 object 时,我想创建一个通知 object,但是在获取从 CreateView 创建的 object 时遇到了一些困难

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)

how can I achieve the task above?我怎样才能完成上述任务? is their a way doing this using mixins?他们是使用mixins的一种方式吗?

The object is created in the super form_valid method so until that is called you cannot access it. object 是在 super form_valid方法中创建的,因此在调用之前您无法访问它。 Instead call the super method first and use self.object to refer to the created object:而是先调用 super 方法,使用self.object来引用创建的 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

An elegant way to do this would be using a post save signal:一种优雅的方法是使用后保存信号:

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=???,)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用Django CBV CreateView上传图片 - Upload image with Django CBV CreateView Django get_form 导致未绑定的表单(或者使用 CBV createview 将 url 参数获取到模型表单的最佳方法是什么?) - Django get_form results in unbound form (or what is the best way to get url parameters into a model form using CBV createview?) 如何从 Django 中的先前视图(CBV)中获取 object? - How to get object from previous view(CBV) in Django? Django CBV获取列表,获取对象 - Django CBV get list, get object 如何在 Django CreateView 中创建对象后添加指令? - How can I add an instruction after an object creation in Django CreateView? 使用Django createview创建相关对象 - Created related objects using django createview Django:如何使用通用CreateView在注册后直接登录用户 - Django: How to login user directly after registration using generic CreateView Django CreateView object.id in get_succes_url pk(id) is NONE 然后在重定向到另一个 URL 后打印出创建的条目 ID - Django CreateView object.id in get_succes_url pk(id) is NONE and then after redirecting to another URL it prints out created entry ID Django的。 在CreateView中获取ForeignKey对象的ID - Django. Get id of ForeignKey object in CreateView (Django CBV)需要将 object 附加到具有 CBV 的用户 - (Django CBV) Need object be attached to a user with CBV
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM