Django automatically set foreign key in form (with class based views)

前端 未结 2 913
孤城傲影
孤城傲影 2021-01-01 03:34

I want to use a form to generate a new object (say a Book) from a Person\'s page such that the new Book is automatically associated with that Person via a foreign key, but I

2条回答
  •  南笙
    南笙 (楼主)
    2021-01-01 04:29

    You're going at it the wrong way: the person is not user input, so this information should not reside in the form. You can override the form_valid method as follows:

    class AddBook(CreateView):
        model = Book
    
        def form_valid(self, form):
            form.instance.person_id = self.kwargs.get('pk')
            return super(AddBook, self).form_valid(form)
    

    This will set the person_id attribute on the instance used by the form to save the data, and then call the super method to save that instance and return a redirect.

提交回复
热议问题