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
MediumGive each note an owner.
- In
notes/models.py, add anownerfield toNote: aForeignKeytosettings.AUTH_USER_MODELwithon_delete=models.CASCADEandrelated_name="notes". Importsettingsfromdjango.conf. - In
note_create(views.py), replacenote = 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