0

I have the models below, and I want to add a member to a group in a view. How could I do this, also adding the date_joined and invite_reason correctly. I am using forms without the generics views.

from django.db import models

class Person(models.Model):
    name = models.CharField(max_length=128)

    def __str__(self):
        return self.name

class Group(models.Model):
    name = models.CharField(max_length=128)
    members = models.ManyToManyField(Person, through='Membership')

    def __str__(self):
        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)

1 Answer 1

1
+50

To create the reltationship you have to base your form on the relationship model:

class MembershipForm(ModelForm):
    class Meta:
        fields = ['person', 'group', 'date_joined']
        model = Membership

This form will be composed of a select for the persons, a select for the group and a datefield for the date_joined

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.