目前,我正在從事數學家庭作業項目。有三種類型的用戶。教授,學生和管理員。以下片段將拒絕用戶根據用戶的類型訪問網址。修改後,您必須將此方法裝飾器添加到服務於http請求的請求方法中。
def deny_a_thing(function):
def wrapper(request, *args, **kw):
try:
test = User.objects.get(username=request.user) # This will get the username
except ObjectDoesNotExist:
raise Http404 # return 404, if the user doesn't exist. You can change it to anything
if not request.user.is_authenticated(): # If the user is not authenticated, return to the rootm. You can also change this.
return HttpResponseRedirect("/")
try:
if test.groups.filter()[0].name != "professors": # Add your test here. E.g: If user saved A, don't go B.
raise Http404
except IndexError:
raise Http404
else:
return function(request, *args, **kw)
return wrapper
以下內容添加到您的方法
@deny_a_thing # This will deny the user from doing the thing you didn't want the user to do.
def some_page_request(request):
return HttpResponse("OMG")
檢查這個link一個簡單的裝飾
這有什麼不好使用會話? – 2014-10-17 17:18:53
你看過[django的表單嚮導](https://docs.djangoproject.com/en/dev/ref/contrib/formtools/form-wizard/)嗎? – dgel 2014-10-17 17:25:47