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

后端 未结 3 973
醉话见心
醉话见心 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:18

    With the url that you defined in author_detail.html the author_id variable will be accessible in the view as self.kwargs['author_id']

    # views.py
    class BookCreate(CreateView):
    ...
    def form_valid(self, form):
        book = form.save(commit=False)
        author_id = form.data['author_id']
        author = get_object_or_404(Author, id=author_id)
        book.author = author
        return super(BookCreate, self).form_valid(form)
    ...
    def get_context_data(self, **kwargs):
        context = super(BookCreate, self).get_context_data(**kwargs)
        context['a_id'] = self.kwargs['author_id']
        return context
    

    Then in your form you can add:

    class BookForm(forms.Modelform):
        ...
        def __init__(self, *args, **kwargs):
            self.fields["author_id"] = forms.CharField(widget=forms.HiddenInput())
            super(BookForm, self).__init__(self, *args, **kwargs)
    

    Then in the template:

      
    

    The form_valid in the view should retrieve the id, get the appropriate author and set that author as the books author. The commit=False prevents the model getting saved at first while you set the author and calling super will result in form.save(commit=True) being called.

提交回复
热议问题