Menu
CoddyTech

A Note Has an Owner

Part of the Users and Accounts section of Coddy's Django journey. Lesson 8 of 16.

Every signed in user shares one pile of notes. To tell them apart, each note has to record who wrote it: a ForeignKey, like the one from a book to its author.

To link to a user, do not import User. Point the ForeignKey at the setting settings.AUTH_USER_MODEL (after from django.conf import settings), which names the user model, "auth.User" here. The code then stays right in a project with its own user model.

Who wrote a note is never a form field: a user who could pick it could write as someone else. The view fills it in. As in the Forms section, form.save(commit=False) builds the object without saving it, so the view can set a field the form does not have:

order = form.save(commit=False)
order.total = order.quantity * order.unit_price
order.save()

Run does makemigrations and migrate for the new field.

challenge icon

Challenge

Medium

Give each note an owner.

  1. In notes/models.py, add an owner field to Note: a ForeignKey to settings.AUTH_USER_MODEL with on_delete=models.CASCADE and related_name="notes". Import settings from django.conf.
  2. In note_create (views.py), replace note = form.save(). Build the note without saving it, set its owner to the signed in user, then save.

Write a note as ada, then open the Data tab: its owner is 1.

Try it yourself

from django.db import models


class Note(models.Model):
    title = models.CharField(max_length=100)
    body = models.TextField(blank=True)
    created = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["-created"]

    def __str__(self):
        return self.title

All lessons in Users and Accounts

Practice on your own: Django playground