Groups keyboard shortcuts have been updated
Dismiss
See shortcuts

ModelChoiceField user filter

35 views
Skip to first unread message

Gabriel Soler

unread,
Dec 5, 2024, 6:24:07 AM12/5/24
to Django users
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

Ryan Nowakowski

unread,
Dec 5, 2024, 7:28:38 PM12/5/24
to django...@googlegroups.com

Gabriel Soler

unread,
Dec 6, 2024, 9:11:44 AM12/6/24
to Django users
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
Reply all
Reply to author
Forward
0 new messages