[Answered ]-Filterig initial data in Django ManyToMany field

1👍

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.

1👍

@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.

Leave a comment