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

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

    I had a similar situation and, when doing the accepted answer steps I encountered 2 errors (I'm using Python 2.7):

    1. object has no attribute 'fields' which was fixed by using answer to a similar question: https://stackoverflow.com/a/8928501/2097023 from @scotchandsoda:

    ...self.fields should be placed before calling super(...)

    def __init__(self, users_list, **kw):
        super(BaseWriteForm, self).__init__(**kw)
        self.fields['recipients'].queryset = User.objects.filter(pk__in=users_list)
    
    1. object has no attribute 'get' which was fixed using answer: https://stackoverflow.com/a/36951830/2097023 from @luke_dupin:

    ...this error can also be generated by incorrectly passing arguments in the init of a form, which is used for an admin model.

    Example:

    class MyForm(forms.ModelForm):
        def __init__(self, *args, **kwargs):
            super(MyForm, self).__init__(self, *args, **kwargs)
    

    Notice the double passing of self? It should be:

    class MyForm(forms.ModelForm):
        def __init__(self, *args, **kwargs):
            super(MyForm, self).__init__(*args, **kwargs)
    

提交回复
热议问题