博客基础_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 ...
settings.py learning_log/
1 --snip 2 3 LOGIN_URL = 'users/login/'
1 python manage.py makemigrations 2 1 3 1 4 5 python manage.py migrate 6 7 python manage.py runserver
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)
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)
views.py learning_logs/
1 --snip 2 def topics(request): 3 topics = Topic.objects.filter(owner= request.user).order_by('date_added')
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
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()