1、‘未經授權的訪問’如何控制?
<form class="form-signin" action="{% url 'account:login' %}" method="post"> {% csrf_token %} {% comment %}<label for="inputEmail" class="sr-only">Email address</label> <input type="email" id="inputEmail" class="form-control" placeholder="Email" required autofocus> <label for="inputPassword" class="sr-only">Password</label> <input type="password" id="inputPassword" class="form-control" placeholder="Password" required>{% endcomment %} {{ form.non_field_errors }} {% for field in form %} {{ field }} {{ field.errors }} {% endfor %} <input type="hidden" name="next" value="{{ redirect_to }}"> <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button> <div class="checkbox"> {% comment %}<a class="pull-right">Need help?</a>{% endcomment %} <label> <input type="checkbox" value="remember-me" name="remember"> Stay signed in </label> </div> {% load oauth_tags %} {% load_oauth_applications request%} </form>
在模板定義了一個表單form,實參action指定發送到視圖的login. 我們則使用 {% csrf_token%} 來防止攻擊者利用表單來獲得對服務器未經授權的訪問。攻擊稱爲跨站請求僞造。
2、如何讓用戶擁有自己的數據
django提供了裝飾器 @login_required 只允許已登錄用戶訪問某些頁面。裝飾器需要放到函數前面來修飾。
如下面限制只能是已登錄用戶查看所有主題。需要從django裏導入如下第4行。
讓用戶有自己的數據,首先就是在新建的數據中有當前的用戶信息。
owner = models.ForeignKey(User, on_delete=models.CASCADE)
想讓用戶只能訪問自己的數據就在查詢時過濾數據,數據=當前用戶。
topics = Topic.objects.filter(owner=request.user).order_by('date_added')
from django.db import models from django.contrib.auth.models import User # Create your models here. class Topic(models.Model): """ user learning topic""" text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) #數據中關聯用戶信息 def __str__(self): """return string of model""" return self.text
@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, 'learning_logs/topics.html', context)
保護非當前用戶不準修改數據。
if topic.owner != request.user:
@login_required def topic(request, topic_id): """顯示單個主題所有內容""" topic = Topic.objects.get(id=topic_id) #確認請求的主題是當前用戶 if topic.owner != request.user: #保護數據,操作用戶!=數據擁有者,報錯404 raise Http404 entries = topic.entry_set.order_by('-date_added') context = {'topic': topic, 'entries': entries} return render(request, 'learning_logs/topic.html', context)