Ferid Rzayev
Ferid Rzayev

Reputation: 1

Django, How to get object instance(id) before creating it in form_valid function of generics view?

When i creating Post model object i need to get it ID instantly and create a second model User_permission , how in this case can i pass to post variable the ID data of newly created post

  class CreatePostView(LoginRequiredMixin, CreateView):
        model = Post
        form_class = PostForm

        def form_valid(self, form): 
                obj = User_permission.objects.create(post=post)
                obj.save()
            return super().form_valid(form)

Upvotes: 0

Views: 1629

Answers (1)

nigel222
nigel222

Reputation: 8222

Objects do not have ids until saved. You would need something like

    def form_valid(self, form): 
            response = super().form_valid(form) # saves object
            obj = User_permission.objects.create(post=self.object)
            obj.save()
            return response

This example in the documentation shows use of self.object

Upvotes: 2

Related Questions