如何从 Django 中的 CreateView 获取 Id?

How to get the Id from CreateView in django?

我需要一些帮助从 django 中的对象获取 id

我有一个 createView,我想在创建新对象时向用户发送通知,我需要对象 ID...

    def form_valid(self, form):
        # setting fields that are not open to user
        form.instance.created_by = self.request.user
        form.instance.status = 'open'
        messages.success(self.request, 'Ticket Created Successfully!')
        Notification.objects.create(
            created_by=self.request.user,
            created_for=form.instance.responsible,
            title=f"New ticket from {self.request.user.first_name} {self.request.user.last_name} =====> {form.instance.id}",
            message=f"Hello",)
        return super().form_valid(form)

问题是 {form.instance.id} 总是 none。任何人都可以帮助我吗?提前致谢。

你必须首先调用super()方法,然后使用self.object来获取新创建的实例。

class MyCreateView(CreateView):

    def form_valid(self, form):
        result = super().form_valid(form)

        print("This is my newly created instance", self.object.pk)

        return result