Skip to content
This repository has been archived by the owner on Sep 17, 2023. It is now read-only.

07 Note owners

scotwk edited this page May 10, 2015 · 3 revisions

Modify the model and update the database

Currently notes are not associates with any specific users. Modify the Note model in note/models.py to add a field:

from django.contrib.auth.models import User

# Add this line in to your model
owner = models.ForeignKey(User)

Whenever a model is changed the database schema needs to be updated. To tell the database about new fields we create a migration. If you have any existing notes you will be asked to give a value for the new field in the existing notes. You can use 0 for this migration (this is not a good general purpose answer though).

$ ./manage.py makemigrations note
$ ./manage.py migrate

Let a user to view only their notes

Currently in the view we return the five newest notes, but there is no filtering done by owner. Modify note/views.py to restrict the notes returned to those owned by the current user by using a filter.

latest_note_list = Note.objects.filter(owner=request.user).order_by('-pub_date')[:5]

Update the admin

Improve your admin view. Modify note/admin.py to include the new ownerfield in the admin list. You can view this in the admin