Show only your data - 30 days of Django

Show only your data - 30 days of Django

/ #Django


Learn how to connect data in a model to the authenticated user.

Updating the task model

We made it possible to log in to the project, but there is a problem. Everyone sees the same data. So it's time to fix that. Open up task/models.py:

from django.contrib.auth.models import User # New, 1
...

Class Task(models.Model):
    user = models.ForeignKey(User, related_name='tasks', on_delete=models.CASCADE) # New, 2
    category = models.ForeignKey(Category, related_name='tasks', on_delete=models.CASCADE)
    title = models.CharField(max_length=255)
    description = models.TextField(blank=True, null=True)
    is_done = models.BooleanField(default=False)

1. First, we import the user model (The same we use for registering).
2. The, we add a new field to the model.

Next step then is to update the database again:

$ python3 manage.py makemigrations

And then run the migrations scripts:

$ python3 manage.py migrate

When this is done, the task table in the database should be updated. NB NB NB:
You might be asked to set a default user or similar here, just type 1 on your keyboard.

Get only your tasks

Next step is to update task/views.py:

from django.contrib.auth.models import User # New, 1
...

@login_required
def frontpage(request):
    if request.method == 'POST':
        form = TaskForm(request.POST)

        if form.is_valid():
            form.save()
    else:
        form = TaskForm()

    title = 'This is a variable'
    tasks = Task.objects.filter(user=request.user) # Change, 2
    categories = Category.objects.all()

    return render(request, 'task/frontpage.html', {'title': title, 'tasks': tasks, 'categories': categories, 'form': form})

@login_required
def search(request):
    query = request.GET.get('query', '')
    
    if query:
        tasks = Task.objects.filter(user=request.user).filter(Q(title__icontains=query) | Q(description__icontains=query)) # Change, 3
    else:
        tasks = []
    
    return render(request, 'task/search.html', {'query': query, 'tasks': tasks})

@login_required
def edit_task(request, pk):
    task = Task.objects.filter(user=request.user).get(pk=pk) # Change, 4

    if request.method == 'POST':
        form = TaskForm(request.POST, instance=task)

        if form.is_valid():
            form.save()

            return redirect('frontpage')
    else:
        form = TaskForm(instance=task)
    
    return render(request, 'task/edit_task.html', {'form': form})

@login_required
def mark_completed(request, pk):
    task = Task.objects.filter(user=request.user).get(pk=pk) # Change, 5
    task.is_done = True
    task.save()

    return redirect('frontpage')

@login_required
def delete_task(request, pk):
    task = Task.objects.filter(user=request.user).get(pk=pk) # Change, 6
    task.delete()

    return redirect('frontpage')

1. First, we import the user database model again.
2, 3, 4, 5, 6. Here, we add a new filter. To make sure that the user field matches the authenticated user.

Great, all of the get commands should now work. You should only see data connected to your user. Last step then is to make sure that when you create a new task, it's added to your user.

@login_required
def frontpage(request):
    if request.method == 'POST':
        form = TaskForm(request.POST)

        if form.is_valid():
            task = form.save(commit=False) # New
            task.user = request.user # New
            task.save() # New
    else:
        form = TaskForm()

    title = 'This is a variable'
    tasks = Task.objects.filter(user=request.user)
    categories = Category.objects.all()

    return render(request, 'task/frontpage.html', {'title': title, 'tasks': tasks, 'categories': categories, 'form': form})

We added three new lines here. Since we added a new field called user, we can't just run form.save(). Because this will lead to an error, since the user field isn't filled out. So we create a new variable called task, and assign all of the data to it. Next, we set the user field to the authenticated user and save()

Table of contents

Comments

No comments yet...

Add comment

Info

Please log in to comment!

Newsletter

Subscribe to my weekly newsletter. One time per week I will send you a short summary of the tutorials I have posted in the past week.