Django: Overriding __init__ for Custom Forms

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)

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)

Don't modify the __init__() parameters. You may break compatibility with future versions of Django and make your code harder to maintain.

I suggest using the kwargs to pass your variables.

class TicketForm(forms.Form):
    type = Type.GetTicketTypeField()

    def __init__(self, *args, **kwargs):
        ticket = kwargs.pop('ticket')
        super().__init__(*args, **kwargs)
        if ticket:
            self.fields['state'] = State.GetTicketStateField(ticket.Type)

Tags:

Python

Django