crucialfelix/django-ajax-selects — pull request #88 by ItsNotWorking (2014-08-15 18:42:58+00:00)
Title: Ability to define widget channel_options that get added as LookupChannel attributes

Sometimes it would be useful to be able to pass options through to the LookupChannel to affect the results based on the form being used, in particular when editing existing model instances. For example, consider the following setup:

class Event(models.Model):
users = models.ManyToManyField(settings.AUTH_USER_MODEL, through="EventMembership")

class EventMembership(models.Model):
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
related_name="memberships",
)
event = models.ForeignKey(
Event,
related_name="registrants",
)
status = models.CharField(
max_length=10,
choices=MEMBERSHIP_STATUS,
)

With the form as follows:

class EventForm(forms.ModelForm):
users = AutoCompleteSelectMultipleField('users')

class Meta:
model = Event

If you are editing an Event and you want to colour-code the users based on EventMembership.status, this is not currently possible as the data resides in the through table. Instead you would need to pass the Event instance pk through to the lookup channel so that format_item_display could retrieve the record and adjust the display as such. With the changes in this pull request this could be achieved simply as follows:

class EventForm(forms.ModelForm):
users = AutoCompleteSelectMultipleField('judges')

class Meta:
model = Event

def __init__(self, *args, **kwargs):
super(EventForm, self).__init__(*args, **kwargs)
self.fields['users'].widget.channel_options.update({'event_id': self.instance.pk})

The LookupChannel would then have the attribute "event_id" that could be used to retrieve the membership status within get_objects by doing EventMembership.objects.filter(user_id__in=ids, event_id=self.event_id)