I have a model that looks like this:
class Invite(models.Model):
user = models.ForeignKey(User)
event = models.ForeignKey(Event)
roles = models.ManyToManyField(Role, blank=True, null=True)
sent = models.BooleanField("Invite Sent", default=False, editable=False)
created = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return u"%s" % self.user
class Meta:
unique_together =(('user','event'),)
class Role(models.Model):
"""
This associates a user's role to an event
"""
event = models.ForeignKey(Event, related_name="roles")
roletype = models.ForeignKey(RoleType)
profiles = models.ManyToManyField(Profile, related_name="roles",
blank=True, null=True)
modified = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
So whenever a new Event is created, a bunch of roles gets created along with it. In the Invite model, how can I only show the roles associated with the event I’ve selected in the change form within Django Admin instead of showing all the entries in the Role model?
You want to dynamically filter the choices of the
roleschoices, so you will needajaxto perform this task.Here’s how you can make this work..
1:
OnChangeof theeventsend theevent_idto your customviewthroughajax.2: From the
Rolesmodelfilterbased on theevent_idyou got from theajaxrequest and return the filteredrolesbyserializingintoJSON.3: Clear the existing
rolesand repopulate by parsing through theJSONresponse.Eg:
This a
jquerygetJSONexamplejavascript:
url’s:
views:
This just an example using
jqueryyou can use any type ofajaxand achieve this.