[Answer]-Django – assign m2m relationship in admin

1👍

If I’m not mistaken, it looks like you want to call a coder to a view, and then show all the assignments for an a user.

First, I might start by assigning a related_name to the coder and assignment models relationships with each other, so you can easily reference them later.

class Assignment(models.Model):
    coders = models.ManyToManyField(Coder, related_name='assignments')

class Coder(models.Model):
    user = models.OneToOneField(User, related_name="coder")

I’d then reference the user in a template as such using the one to one relationship:

    {% for assignment in user.coder.assignments.all %}

Also, looks like the problem is how you’ve got yout models setup. After reviewing the django.db.models.base for the “models.Model” class and “ModelBase” class, it looks like there is no “Admin” subclass. You’ll probably want to remove those to start with.

Next, the __unicode__ field shows the default visible value which represents the object on the screen. In this case, you’ve forced it to be “Coders”. If you had 5 coders to an assignment, you’d see “Coders, Coders, Coders, Coders, Coders” instead of “admin, user1, bob22, harry8, stadm1in”, etc. Let’s override the unicode to show something more meaningful. Since the coders field only has the user field, let’s reference that by self.user.username. We’ll change Assignment()‘s unicode to self.title as well.

ModelForm doesn’t have an ‘Admin’ subclass either, so let’s remove that.

MODELS:


class Coder(models.Model):
    """Every user can be a coder. Coders are assigned to Assignments"""
    user = models.OneToOneField(User, related_name='coder')

    def __unicode__(self):
        return self.user.username


class Assignment(models.Model):
    """(Assignment description)"""
    title = models.CharField(blank=True, max_length=100)
    start_year = models.IntegerField(blank=True, null=True)
    end_year = models.IntegerField(blank=True, null=True)
    country = models.IntegerField(blank=True, null=True)
    coders = models.ManyToManyField(Coder, related_name='assignments')

    def __unicode__(self):
        return self.title


ADMIN:

class AssignmentCoderInline(admin.StackedInline):
    model = Assignment.coders.through
    can_delete = False
 #   verbose_name_plural = 'coder'

class AssignmentAdmin(admin.ModelAdmin):
    fieldsets = [
        ('Assignment', {'fields': ['title', 'start_year', 'end_year']})
    ]
    inlines = (AssignmentCoderInline,)

Leave a comment