How do I pass a parent id as an fk to child object's ModelForm using generic class-based views in Django?

后端 未结 3 968
醉话见心
醉话见心 2020-12-20 07:56

I am trying to use Django Generic Class-Based Views to build a CRUD interface to a two-model database. I have a working CRUD interface to the parent model, and am stuck try

3条回答
  •  执笔经年
    2020-12-20 08:38

    You could pass the author id to the form, here's some directions:

    class BookForm(forms.Modelform):
        author = None
    
        class Meta:
            model = Book
    
        def __init__(self, *args, **kwargs):
            self.author = kwargs.pop('author')
            super(BookForm, self).__init__(*args, **kwargs)
    
        def save(self, commit=True):
            # your custom save (returns book)
    
    
    class BookCreate(CreateView):
        form_class = BookForm
    
        def get_form_kwargs(self):
            kwargs = super(BookCreate, self).get_form_kwargs()
            kwargs['author'] = # pass your author object
    
            return kwargs
    

提交回复
热议问题