Getting 'instance' in ModelForms

0 views
Skip to first unread message

Greg Taylor

unread,
May 16, 2008, 8:27:10 AM5/16/08
to Django users
Is there a way to get the value of the 'instance' keyword argument
from within a Form sub-classed by ModelForm? For example:

class CS_SKU(models.Model):
colors = models.ManyToManyField(Color, blank=True, null=True)
color_field = forms.ModelMultipleChoiceField(queryset=colors)

class Form_SKU(ModelForm):
"""
The form for updating SKUs.
"""
selected = self.instance.colors

def some_test_view():
Form_SKU(instance=<SOMECOLOR>)

Greg Taylor

unread,
May 16, 2008, 11:13:02 AM5/16/08
to Django users
To elaborate, I can't do a self.instance, as it errors saying "self is
not defined". For example:

color_field =
forms.ModelMultipleChoiceField(queryset=self.instance.colors)

I need to find the difference of two lists on a model to form the
queryset in my application.

Nathaniel Whiteinge

unread,
May 16, 2008, 11:40:07 AM5/16/08
to Django users
On May 16, 6:27 am, Greg Taylor <squishywaf...@gmail.com> wrote:
> class Form_SKU(ModelForm):
> """
> The form for updating SKUs.
> """
> selected = self.instance.colors

``self`` isn't in scope here, try the code below (and it wouldn't hurt
to read-up on Python OOP).

class Form_SKU(ModelForm):
def __init__(self, *args, **kwargs):
super(Form_SKU, self).__init__(*args, **kwargs)
if self.instance:
selected = self.instance.colors
Reply all
Reply to author
Forward
0 new messages