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 probably want something along the lines of:
class InviteAdmin(admin.ModelAdmin):
def get_form(self, request, obj=None, **kwargs):
self.instance = obj # Capture instance before the form gets generated
return super(InviteAdmin, self).get_form(request, obj=obj, **kwargs)
def formfield_for_manytomany(self, db_field, request=None, **kwargs):
if db_field.name == 'role' and self.instance:
# restrict role queryset to those related to this instance:
kwargs['queryset'] = self.instance.event.roles.all()
return super(InviteAdmin, self).formfield_for_manytomany(
db_field, request=request, **kwargs)
Django documentation for formfield_for_manytomany
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With