Django: Overriding __init__ for Custom Forms

前端 未结 2 453
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-29 04:58

I am making a custom form object in Django which has an overrided __init__ method. The purpose of overriding the method is to dynamically generate drop-down boxes based on t

相关标签:
2条回答
  • 2020-12-29 05:25

    You can dynamically modify your form by using the self.fields dict. Something like this may work for you:

    class TicketForm(forms.Form):
    
      Type = Type.GetTicketTypeField()
    
      def __init__(self, ticket, *args, **kwargs):
        super(TicketForm, self).__init__(*args, **kwargs)
        self.fields['state'] = State.GetTicketStateField(ticket.Type)
    
    0 讨论(0)
  • 2020-12-29 05:32

    I found a solution here. If there is a better solution, please post a reply.

    class TicketForm(forms.Form):
        Type = Type.GetTicketTypeField()
    
        def __init__(self, ticket=None, *args, **kwargs):   
            super(TicketForm, self ).__init__(*args, **kwargs)
            if ticket:
                self.fields['State'] = State.GetTicketStateField(ticket.Type)
    
    0 讨论(0)
提交回复
热议问题