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.
- [Answered ]-'views' is not defined in Django 1.10
- [Answered ]-Django – Many-to-many with intermediate model – display in template with Generic DetailView
- [Answered ]-Django custom permissions not being recognized?
- [Answered ]-Django Split a charfield output which is seperated by ','(comma) into an array of strings.?
- [Answered ]-What internal tables are automatically created by Django?
Source:stackexchange.com