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/406b9d08-6473-4de6-9dab-eeee3eb5bec0n%40googlegroups.com.