Django关联数据和用户

修改模型

models.py

1
2
3
4
5
from django.contrib.auth.models import User

class Topic(models.Model):
owner = models.ForeignKey(User, on_delete=models.CASCADE) # 新增
--snip--

迁移数据库

  1. 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    python manage.py makemigrations myapp

    You are trying to add a non-nullable field 'owner' to topic without a default; we can't do that (the database needs something to populate existing rows).

    Please select a fix:
    1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
    2) Quit, and let me add a default in models.py
    Select an option: 1

    Please enter the default value now, as valid Python
    The datetime and django.utils.timezone modules are available, so you can do e.g. timezone.now
    Type 'exit' to exit this prompt
    >>> 1

    Migrations for 'myapp':
    myapp\migrations\0003_topic_owner.py
    - Add field owner to topic
  2. 1
    2
    3
    4
    5
    6
    python manage.py migrate

    Operations to perform:
    Apply all migrations: admin, auth, contenttypes, myapp, sessions
    Running migrations:
    Applying myapp.0003_topic_owner... OK

注意

当前,不管你以哪个用户的身份登录,都能够看到所有的主题。

只向用户显示属于自己的主题

比如 /topics.html 页面在 views.py 函数中修改:

1
2
3
4
5
6
7
8
9
--snip--
@login_required
def topics(request):
"""所有"""
# topics = Topic.objects.order_by('date_added')
topics = Topic.objects.filter(owner=request.user).order_by('date_added')
context = {'topics': topics}
return render(request, 'myapp/topics.html', context)
--snip--

保护单个主题

1
2
3
4
5
6
7
8
9
10
@login_required
def topic(request, topic_id):
"""具体主题页面"""
topic = Topic.objects.get(id=topic_id) # 主题xx

# 确认请求的主题属于当前用户
if topic.owner != request.user:
raise Http404

--snip--

保护页面 edit_entry

1
2
3
4
5
6
7
8
9
@login_required
def edit_entry(request, entry_id):
"""编辑entry页面"""
entry = Entry.objects.get(id=entry_id)
topic = entry.topic

if topic.owner != request.user:
raise Http404
--snip--

修改“添加主题”页面

指定owner字段。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@login_required
def new_topic(request):
"""添加新主题"""
if request.method != 'POST':
form = TopicForm()
else:
form = TopicForm(request.POST)
if form.is_valid():
# form.save()

new_topic = form.save(commit=False)
new_topic.owner = request.user # 创建新主题时,你必须指定其owner字段的值。
new_topic.save()

return HttpResponseRedirect(reverse('myapp:topics'))

保护 new_entry 页面

1
2
3
4
5
6
7
@login_required
def new_entry(request,topic_id):
'''添加新条目'''
topic = Topic.objects.get(id=topic_id)
if topic.owner!=request.user:
raise Http404
--snip--
———— The End ————