Skip to content

Instantly share code, notes, and snippets.

@shaunagm
Created April 4, 2017 00:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shaunagm/a3e0fd55b9c3030e019071b75c0386ca to your computer and use it in GitHub Desktop.
Save shaunagm/a3e0fd55b9c3030e019071b75c0386ca to your computer and use it in GitHub Desktop.
form_init_example.py
# This alters initial, but initial isn't actually used in the form displayed
def __init__(self, *args, **kwargs):
super(UniversalForm, self).__init__(*args, **kwargs)
self.fields['always_reps'].widget = SelectMultiple(choices=[(i.pk, i.full_appellation()) for i in Legislator.objects.all()])
if self.instance.always_reps:
self.initial = {'always_reps': self.instance.get_always_reps()}
# This gives me an error because I don't have access to self.instance before calling super
def __init__(self, *args, **kwargs):
if self.instance.always_reps:
self.initial = {'always_reps': self.instance.get_always_reps()}
super(UniversalForm, self).__init__(*args, **kwargs)
self.fields['always_reps'].widget = SelectMultiple(choices=[(i.pk, i.full_appellation()) for i in Legislator.objects.all()])
@doctormo
Copy link

doctormo commented Apr 4, 2017

instance will usually be passed into kwargs, you should look for it there and if it's not there, you will be dealing with creation rather than editing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment