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.
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.
- [Answered ]-How to give {% url '' %} to a variable?
- [Answered ]-How to delete many to many when unassociated in Django?
- [Answered ]-When working with a settings directory, where should I import it?
- [Answered ]-BSON functions affecting performance β installation dependent