'Django Form. View form with models of logged user

I'm doing simple to do app in django. I want user to have possibility to add boards and task (task is specified for board).

When user is adding task (form created with ModelForm ) there is possibility to choose from different boards but the form is showing all boards - for all users. I want it to show only boards of currently logged user. How can I do this? Would appreciate some help.

models.py:

class Board(models.Model):
    board_name = models.CharField(max_length=50)
    day = models.DateTimeField(default=timezone.now)
    board_user = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.board_name


class Task(models.Model):
    task_name = models.CharField(max_length=100)
    done = models.BooleanField(default=False)
    not_done = models.BooleanField(default=False)
    task_board = models.ForeignKey(Board, on_delete=models.CASCADE)

    def __str__(self):
        return self.task_name

forms.py:

class TaskForm(forms.ModelForm):

    class Meta:
        model = Task
        user = User.objects.get(username='admin')
        fields = ['task_name', 'task_board']

views.py

def add_task(request):
    if Board.objects.filter(board_user=request.user).exists():
        form = TaskForm(request.POST)
        # problem nadal nierozwiązany
        if request.method == "POST":
            form.instance.task_board.user = request.user
            if form.is_valid:
                form.save()
            return redirect('tasks-view')
    else:
        return redirect('tasks-view')
    return render(request, 'todo/task_form.html', {'form': form})


Solution 1:[1]

A super simple method of doing something like that would be to just use Django's built-in authenticated system.

If you want to show something only to logged in users (in views):

def view(request):
    if request.user.is_authenticated:
        # do something
    else:
        return login      # example

In templates:

{% if user.is_authenticated %}
    <p> logged in </p>
{% else %}
    <p> not logged in </p>
{% endif %}

Solution 2:[2]

I think Task Model should have a OneToOneField which in this case should be task_board as shown below

class Task(models.Model):
    task_name = models.CharField(max_length=100)
    done = models.BooleanField(default=False)
    not_done = models.BooleanField(default=False)
    task_board = models.OneToOneField(Board, on_delete=models.CASCADE)

    def __str__(self):
        return self.task_name

Sources

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

Source: Stack Overflow

Solution Source
Solution 1 Dharman
Solution 2 snakecharmerb