Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django M2MFields 'through' widgets

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?

like image 579
svfat Avatar asked Feb 21 '16 09:02

svfat


1 Answers

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.

like image 183
Antoine Pinsard Avatar answered Nov 05 '22 07:11

Antoine Pinsard