Are there exists any examples of Django widgets which can be useful for ManyToManyFields with 'through' attributes? For example, i have these models (got the source from django documentation):
from django.db import models
class Person(models.Model):
name = models.CharField(max_length=128)
def __str__(self): # __unicode__ on Python 2
return self.name
class Group(models.Model):
name = models.CharField(max_length=128)
members = models.ManyToManyField(Person, through='Membership')
def __str__(self): # __unicode__ on Python 2
return self.name
class Membership(models.Model):
person = models.ForeignKey(Person, on_delete=models.CASCADE)
group = models.ForeignKey(Group, on_delete=models.CASCADE)
date_joined = models.DateField()
invite_reason = models.CharField(max_length=64)
Obvisously, standart ModelMultipleChoiceField won't work here. I need to populate 'date_joined' , and 'invite_reason' while adding. Which is the simpliest way to achieve this?
This is a bit too complex for a simple widget. I can't even imagine how it would look like. You will have to use inline formsets for that purpose.
This should give something like this:
from django.forms import inlineformset_factory
MembershipFormSet = inlineformset_factory(Group, Membership, fields=(
'person', 'date_joined', 'invite_reason'))
group = Group.objects.get(pk=group_id)
formset = MembershipFormSet(instance=group)
Within django.contrib.admin
, you can use inlines with InlineModelAdmin.
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