I want to filter data in Django ManyToMany field.
The app creates Meetings that take place in some rooms which are located in some venues.
Many people can create Meetings, but a single person can just access to the venues and rooms that he created.
My models are (example):
class Room(models.Model):
name = models.CharField(max_length=100)
capacity = models.IntegerField()
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('venue:room_detail', kwargs={'pk':self.pk})
class Venue(models.Model):
creator = models.ForeignKey(User)
name = models.CharField(max_length=100)
rooms = models.ManyToManyField(Room)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('venue:venue_detail', kwargs={'pk':self.pk})
class Meeting(models.Model):
name = models.CharField(max_length=100)
venue = models.ForeignKey(Venue)
room = models.ForeignKey(Room)
I'm using Django generic views in my application.
My question is, how can I filter only the specific rooms created by a user "User A" in the form of Meeting. "User A" cannot see rooms created by "User B"
In the same way, how can I select just the rooms created in a specific venue without all the rooms? I don't want to use JavaScript please.
Many thanks for your responses.
You can override the queryset from the form
#constructor from form
def __init__(self, *args, **kwargs):
user = kwargs.pop('user', None)
super(ObjectForm, self).__init__(*args, **kwargs)
if user:
self.fields['rooms'].queryset = Room.objects.filter(room__venue_creator=user)
You need to change ObjectForm
with the name of your form
Something like that.
@angel
class Room(models.Model):
name = models.CharField(max_length=100)
class Venue(models.Model):
creator = models.ForeignKey(User)
name = models.CharField(max_length=100)
rooms = models.ManyToManyField(Room, through="VenueRooms")
class VenueRooms(models.Model):
venue = models.ForeignKey(Venue)
room = models.ForeignKey(Room)
class Meeting(models.Model):
name = models.CharField(max_length=100)
venue = models.ForeignKey(Venue)
room = models.ForeignKey(Room)
class MeetingForm(ModelForm):
class Meta:
model = Meeting
fields = ('name', 'venue', 'room',)
def __init__(self, *args, **kwargs):
user = kwargs.pop('user', None)
print(user) # it prints None
super(MeetingForm, self).__init__(*args, **kwargs)
That is the models and the ModelForm for MeetinfForm where I'm trying to get access to the queryset of rooms and venur created by a specific user. I suppose that user is refered to the autheticated user. It's like request.user; so by printing user un the shell, I should have the name of the authenticated user.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.