Querying a foreign key field in creation form django
i have 3 models, the first one is user a custom user model to handle permissions with two boolean fields, the second is lead with a foreign key of user , the third is event with date and lead foreign key fields, when creating an instance of event i want to see only leads related to the logged in user within the creation form. I tried some solutions like passing the query in the init function with user=None in parameters with an if user: condition, defining a function that returns the queryset that didn’t work it popped out the error« function object has no attribute » and this where i got with getting the error « View.init() takes 1 positional argument but 2 were given », any help will be appreciated
#models
class Lead(models.Model):
User = models.ForeignKey(settings.AUTH_USER_MODEL,null=True, blank=True, on_delete=models.SET_NULL)
class Event(models.Model):
Lead = models.ForeignKey(Lead,null=True, on_delete=models.CASCADE)
#views
class EventCreateForUser(LoginRequiredMixin,CreateView):
template_name = "leads/event_create.html"
form_class = EventForm
def get_form_kwargs(self):
kwargs = super(EventForm, self).get_form_kwargs()
kwargs['user'] = self.request.user
return kwargs
def get_success_url(self):
return reverse("leads:lead_list")
def form_valid(self, form):
event = form.save(commit=False)
event.Lead.User = self.request.user
form.save()
messages.success(self.request, "You have successfully created a lead")
return super(EventCreateForUser, self).form_valid(form)
#forms
class EventForm(ModelForm):
class Meta:
model = Event
widgets = {
'start_time': DateInput(attrs={'type': 'datetime-local'}, format='%Y-%m-%dT%H:%M'),
'end_time': DateInput(attrs={'type': 'datetime-local'}, format='%Y-%m-%dT%H:%M'),
}
fields = '__all__'
def __init__(self,**kwargs):
user = kwargs.pop('user')
super(EventForm, self).__init__(**kwargs)
self.fields['Lead'].queryset = Lead.objects.filter(User = user)
self.fields['start_time'].input_formats = ('%Y-%m-%dT%H:%M',)
self.fields['end_time'].input_formats = ('%Y-%m-%dT%H:%M',)