Home > database >  How to get the Id from CreateView in django?
How to get the Id from CreateView in django?

Time:06-03

I need some help getting the id from an object in django.

I have a createView where I want to send an notification for the user when a new object is created, and I need the object 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)

The problem is that {form.instance.id} is always none. Anyone can help me with that? Thanks in advance.

CodePudding user response:

You have to call the super() method initially, and, then use the self.object to get the newly created instance.

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
  • Related