53👍
✅
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)
6👍
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)
- [Django]-Restrict django FloatField to 2 decimal places
- [Django]-Error creating new content types. Please make sure contenttypes is migrated before trying to migrate apps individually
- [Django]-Identify the changed fields in django post_save signal
5👍
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)
- [Django]-Getting model ContentType in migration – Django 1.7
- [Django]-Django access the length of a list within a template
- [Django]-How can I call a custom Django manage.py command directly from a test driver?
Source:stackexchange.com