[英]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.