'Filter Django ForeignKey Dropdown based on Current User

I am using django ClassBasedViews where I have a Project and Task Models. Each task is assigned to a project and both models register who created a recording in the created_by field.

class Project(models.Model):
    name = models.CharField(max_length=100)
    ...
    created_by = models.ForeignKey(User, on_delete=models.CASCADE)

and then for the Tasks, I have

class Task(models.Model):
    project = models.ForeignKey(Project, on_delete=models.CASCADE)
    task_name = models.CharField(max_length=200)
    ...
    created_by = models.ForeignKey(User, on_delete=models.CASCADE)

So the ClassBasedView to create the new task is like so,

class CreateTask(LoginRequiredMixin, CreateView):
    template_name = 'project/new _task.html'
    form_class = TaskCreationForm
    success_message = "New Task Created"

I need the dropdown in the form to Only show projects for the current logged-in user.

I have gone through this post but the author did not implement my use case for *the current logged-in user.

What can I do and how can I implement this?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source