Hi, thanks It is quite similar to what I was doing... I found another approach a lot more straightforward in an older post:
""" def event_add_view(request): """ add an event, it needs to set occurrences to appear in the calendar""" if request.method !='POST': form = EventForm() form.fields["room_calendar"].queryset = RoomCalendarModel.objects.filter( tenants__user=request.user) form.fields["client"].queryset = Client.objects.filter(user=request.user) """ The benefit I find is to intervene directly in the view of the query set. Thanks Gabriel On Friday, 6 December 2024 at 00:28:38 UTC Ryan Nowakowski wrote: > Add super at the top of your __init__ like this: > < > https://docs.djangoproject.com/en/5.1/topics/forms/modelforms/#changing-the-queryset > > > > > On December 5, 2024 5:24:07 AM CST, Gabriel Soler <[email protected]> > wrote: > >> Hi wise Django fellows >> >> I have been trying to create a field that refers to a Foreign Key, which >> needs to be filtered by the user. I feel this should be something common, >> and I cannot find a way through it. >> >> I found a solution in a forum and stack overflow and a tutorial that uses >> the __init__ and passes a value in the view, like Form(user=request.user), >> to then extract it. >> >> It worked to filter at some point but failed at the end of saving: >> >> Error in formatting: AttributeError: 'EventForm' object has no attribute >> '_errors' >> >> Sometimes, the problem seems to be the "user" field passed on. >> >> I am out of the depth of my knowledge in accessing the __init__ and >> super() here, so I do not know how to troubleshoot. >> """ >> >> class EventForm(forms.ModelForm): >> """Event form""" >> client = forms.ModelChoiceField(queryset=None,empty_label="no client?") >> room_calendar = forms.ModelChoiceField(queryset=None,empty_label="no >> room?") >> class Meta: >> model = Event >> fields = ("client","room_calendar", >> "title","description","event_type",) >> labels = { >> "client":"It there a client associated?(optional)", >> "room_calendar":"Which room it belongs to?", >> "title":"Give it a memorable title", >> "description":"What it is about?", >> "event_type":"Select a type of event", >> } >> >> def __init__(self, *args, **kwargs): >> # Extract the user from the view >> user = kwargs.pop('user') >> super(EventForm, self).__init__(*args, **kwargs) >> # Filter authors related to the logged-in user >> self.fields['client'].queryset = Client.objects.filter(user=user) >> self.fields['room_calendar'].queryset = RoomCalendarModel.objects.filter( >> Q(tenants__user=user)|Q(user=user)) >> >> >> """ >> Thanks >> >> Gabriel >> >> -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to [email protected]. To view this discussion visit https://groups.google.com/d/msgid/django-users/eb37b523-29fa-4bed-8a1a-56737e56cd5fn%40googlegroups.com.

