zoukankan      html  css  js  c++  java
  • 博客基础_django_python从入门到实践_匹配用户和数据

    内容

      限制未登录用户访问

      数据关联到用户/ django验证

      只允许用户访问自己的主题

      保护具体主题和编辑页面

      将新主题关联到当前用户

    代码

    views.py   learning_logs/

     1 --snip
     2 from django.contrib.auth.decorators import login_required
     3 
     4 @login_required
     5 def topics(request):
     6 ...
     7 
     8 @login_required
     9 def topics(request):
    10 ...
    11 
    12 @login_required
    13 def topics(request):
    14 ...
    15 
    16 @login_required
    17 def topics(request):
    18 ...
    19 
    20 @login_required
    21 def topics(request):
    22 ...
    View Code

    settings.py  learning_log/

    1 --snip
    2 
    3 LOGIN_URL = 'users/login/'
    View Code
    1 python manage.py makemigrations
    2 1
    3 1
    4 
    5 python manage.py migrate
    6 
    7 python manage.py runserver
    View Code

     

    models.py  learning_logs/models.py

    1 --snip
    2 from django.contrib.auth.models import User
    3 
    4 def Topic(models.Model):
    5     --snip
    6     owner = models.ForeignKey(User)
    View Code
     1 python manage.py shell
     2 
     3 from django.contrib. auth.models import User
     4 
     5 users = User.objects.all()
     6 for user in users:
     7     print(user.id, user.username)
     8 
     9 #
    10 topics = Topic.objects.all()
    11 for topic in topics:
    12     print(topic, topic.owner)
    View Code

    views.py  learning_logs/

    1 --snip
    2 def topics(request):
    3     topics = Topic.objects.filter(owner= request.user).order_by('date_added')
    View Code

    views.py   learning_logs/

     1 from django.http import Http404
     2 
     3 --snip
     4 def topic(request, topic_id):
     5     if topic.owner != request.user:
     6         raise Http404
     7 
     8 --snip
     9 def edit_entry(request, entry_id):
    10     if topic.owner != request.user:
    11         raise Http404
    View Code

    views.py   learning_logs/

    1 --snip
    2 def new_topic(request):
    3     ...
    4     if form.is_valid():
    5         new_topic = form.save(commit= false)
    6         new_topic.owner = request.user
    7         new_topic.save()
    View Code

  • 相关阅读:
    软件工程概论总结第三章
    软件工程概论总结第二章
    软件工程概论总结
    软件工程概论10-软件测试
    软件工程概论9-软件实现
    软件工程概论-8面向对象设计
    软件工程概论-7面向对象分析
    软件工程概论-6面向对象基础
    软件工程概论-5软件工程中的形式化方法
    软件工程概论-4需求过程
  • 原文地址:https://www.cnblogs.com/dignity/p/9851892.html
Copyright © 2011-2022 走看看