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. 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
MediumNotegets a fieldownerthat links to a user. Deleting a user deletes their notes, anduser.notes.all()lists a user's notes.- A new note belongs to the signed in user who wrote it. The form keeps only
titleandbody.
Press Run, log in as ada (password coddy-pass-123), write a note, and open the Data tab.
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