Sharing a Note
Part of the Users and Accounts section of Coddy's Django journey. Lesson 15 of 16.
Notes are private, and that is right for most of them. Sometimes you want to show one to a friend: a recipe, a reading list. Over this lesson and the next you add read-only sharing.
Sharing is a choice the owner makes, so the note stores it in a BooleanField, True or False. A new note must stay private unless the owner says otherwise, so its default is False. In a ModelForm a BooleanField becomes a checkbox.
Here the form may set the field, because it is the owner's choice about their own note. owner is different: no form may set it.
Challenge
EasyLet the owner share a note.
- In
notes/models.py, add asharedfield toNote: aBooleanFieldthat isFalsefor a new note. - In
notes/forms.py, add the field toNoteFormso the owner can tick it. - In
note_detail.html, showAnyone with the link can read this note.only when the note is shared.
Log in as ada (password coddy-pass-123), tick Shared on a note and save: its page says Anyone with the link can read this note.
Try it yourself
from django.conf import settings
from django.db import models
class Note(models.Model):
owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="notes")
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