[Answered ]-In Django, how to implement a form to assign multiple users to an item?

2πŸ‘

βœ…

where a user can create a new item

So this would suggest an Item belongs to one user, one-to-one relationship. So lets start off with this…

def Item(models.Model):
    title = models.CharField()
    description = models.TextField()
    user = models.OneToOneField(User, related_name="item")

be able to add/remove multiple ItemUser

This would suggest a many-to-many relationship so you will need to add this also to item model…

def Item(models.Model):
    title = models.CharField()
    description = models.TextField()
    user = models.OneToOneField(User, related_name="item")
    item_users = models.ManyToManyField(ItemUser, related_name="item")

I need to make a form

So for this you create a model form, which you can filter on email, as you can see email is passed when you create the form init.

    class ItemForm(forms.ModelForm):
        class Meta:
            model = Item

          def __init__(self, email=None, *args, **kwargs):
          super(ItemForm, self).__init__(*args, **kwargs)

        # Representing the many to many related field in Item
        ItemUsers = forms.ModelMultipleChoiceField(queryset=ItemUser.objects.filter(user__email=email))
self.fields['item_users'] = forms.ModelChoiceField(queryset=ItemUsers)

Thats it, in your view just pass the email for filtering, form = itemForm(email=email)

Above was freehand so there could be a few mistakes in their, but it should give you the right idea, hope this helps.

πŸ‘€Glyn Jackson

0πŸ‘

The answer to the original question was to use formsets in Django. I ended up using an InlineFormset and writing a custom render method for the form. I also used JS to dynamically add/remove forms.

πŸ‘€maulik13

Leave a comment