Skip to content Skip to sidebar Skip to footer

KeyError: 'manager' In Django Get_initial

I working on FormView, and I need to set initial from another object, an example in my case we use Question model to set an initial for QuestionSuggestedEditsForm. But we got an er

Solution 1:

It about m2m relationship, and solved with this;

def get_initial(self):
    initial = super(QuestionSuggestedEditsCreate, self).get_initial()
    for field, _cls in self.form_class.base_fields.items():
        value = getattr(self.get_object(), field)
        if field == 'tags':
            value = self.get_object().tags.all()
        initial.update({field: value})
    return initial

Or;

def get_initial(self):
    initial = super(QuestionSuggestedEditsCreate, self).get_initial()
    for field, _cls in self.form_class.base_fields.items():
        value = getattr(self.get_object(), field)
        if _cls.__class__.__name__ == 'ModelMultipleChoiceField':
            m2m_instance = getattr(self.get_object(), field)
            value = m2m_instance.all()
        initial.update({field: value})
    return initial

Post a Comment for "KeyError: 'manager' In Django Get_initial"