Django2.0中文(會話、用戶焰坪、注冊)

//cookie不安全
1某饰、讀寫cookie: request.COOKIES
def show_color(request):
if "favorite_color" in request.COOKIES:
return HttpResponse("Your favorite color is %s" % request.COOKIES["favorite_color"])
else:
return HttpResponse("You don't have a favorite color.")

//response.set_cookie:參數(shù)包括max_age,expires,path,domain,False
def set_color(request):
if "favorite_color" in request.GET:

    # Create an HttpResponse object...
    response = HttpResponse("Your favorite color is now %s" %             request.GET["favorite_color"])

    # ... and set a cookie on the response
    response.set_cookie("favorite_color",
                        request.GET["favorite_color"])

    return response

else:
    return HttpResponse("You didn't give a favorite color.")

2、使用session:
settings.py
編輯 MIDDLEWARE_CLASSES 配置诫尽,確保 MIDDLEWARE_CLASSES 中包含 'django.contrib.sessions.middleware.SessionMiddleware'炬守。
確認(rèn) INSTALLED_APPS 中有 'django.contrib.sessions' (同時需要同步數(shù)據(jù)庫)
--
request.session["fav_color"] = "blue"
fav_color = request.session["fav_color"]
del request.session["fav_color"]
if "fav_color" in request.session:
////使用
def post_comment(request):
if request.method != 'POST':
raise Http404('Only POSTs are allowed')

if 'comment' not in request.POST:
    raise Http404('Comment not submitted')

if request.session.get('has_commented', False):
    return HttpResponse("You've already commented.")

c = comments.Comment(comment=request.POST['comment'])
c.save()
request.session['has_commented'] = True
return HttpResponse('Thanks for your comment!')

3减途、測試對方是否支持cookie鳍置;request.session.test_cookie_worked()
def login(request):

# If we submitted the form...
if request.method == 'POST':

    # Check that the test cookie worked (we set it below):
    if request.session.test_cookie_worked():

        # The test cookie worked, so delete it.
        request.session.delete_test_cookie()

        # In practice, we'd need some logic to check username/password
        # here, but since this is an example...
        return HttpResponse("You're logged in.")

    # The test cookie failed, so display an error message. If this
    # were a real site, we'd want to display a friendlier message.
    else:
        return HttpResponse("Please enable cookies and try again.")

# If we didn't post, send the test cookie along with the login form.
request.session.set_test_cookie()
return render_to_response('foo/login_form.html')

4墓捻、session類:

from django.contrib.sessions.models import Session
s = Session.objects.get(pk='2b1189a188b44ad18c35e113ac6ceead')
s.expire_date
datetime.datetime(2005, 8, 20, 13, 35, 12)
s.session_data
'KGRwMQpTJ19hdXRoX3VzZXJfaWQnCnAyCkkxCnMuMTExY2ZjODI2Yj...'
s.get_decoded()
{'user_id': 42}
如果cookie沒有設(shè)置過期時間,當(dāng)用戶關(guān)閉瀏覽器的時候撤卢,cookie就自動過期了梧兼。 你可以改變 SESSION_EXPIRE_AT_BROWSER_CLOSE 的設(shè)置來控制session框架的這一行為。
缺省情況下渡紫, SESSION_EXPIRE_AT_BROWSER_CLOSE 設(shè)置為 False 考赛,這樣颜骤,會話cookie可以在用戶瀏覽器中保持有效達(dá) SESSION_COOKIE_AGE 秒(缺省設(shè)置是兩周,即1,209,600 秒)八孝。 如果你不想用戶每次打開瀏覽器都必須重新登陸的話,用這個參數(shù)來幫你子姜。
SESSION_COOKIE_DOMAIN 作用域
SESSION_COOKIE_NAME cookie名字
SESSION_COOKIE_SECURE 是否通過HTTPS傳輸
Session 數(shù)據(jù)存在數(shù)據(jù)庫表 django_session 中
5楼入、auth模塊
將 'django.contrib.auth' 放在你的 INSTALLED_APPS 設(shè)置中浅辙,然后運行 manage.py syncdb以創(chuàng)建對應(yīng)的數(shù)據(jù)庫表。
確認(rèn) SessionMiddleware 后面的 MIDDLEWARE_CLASSES 設(shè)置中包含 'django.contrib.auth.middleware.AuthenticationMiddleware' SessionMiddleware。
//調(diào)用:request.user
request.user.is_authenticated()
request.user對象的方法
username,first_name,last_name,email,password,is_staff,is_active,is_superuser,last_login,date_joined.
is_authenticated() is_anonymous() get_full_name() set_password() check_password()
get_group_permissions() get_all_permissions() has_perm() has_perms() has_module_perms() get_and_delete_messages() email_user()

Set a user's groups:

myuser.groups = group_list

Add a user to some groups:

myuser.groups.add(group1, group2,...)

Remove a user from some groups:

myuser.groups.remove(group1, group2,...)

Remove a user from all groups:

myuser.groups.clear()

Permissions work the same way

myuser.permissions = permission_list
myuser.permissions.add(permission1, permission2, ...)
myuser.permissions.remove(permission1, permission2, ...)
myuser.permissions.clear()

7\
from django.contrib import auth
user=auth.authenticate(username='',password='')
if user is not None:
8泽腮、login_view
from django.contrib import auth

def login_view(request):
username = request.POST.get('username', '')
password = request.POST.get('password', '')
user = auth.authenticate(username=username, password=password)
if user is not None and user.is_active:
# Correct password, and the user is marked "active"
auth.login(request, user)
# Redirect to a success page.
return HttpResponseRedirect("/account/loggedin/")
else:
# Show an error page
return HttpResponseRedirect("/account/invalid/")
9诊赊、logout_view
from django.contrib import auth

def logout_view(request):
auth.logout(request)
# Redirect to a success page.
return HttpResponseRedirect("/account/loggedout/")
10府瞄、 urls.py
from django.contrib.auth.views import login, logout

urlpatterns = patterns('',
# existing patterns here...
(r'^accounts/login/', login), (r'^accounts/logout/', logout),
)
11遵馆、registragiton/login.html login_out.html
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p class="error">Sorry, that's not a valid username or password</p>
{% endif %}

<form action="" method="post">
<label for="username">User name:</label>
<input type="text" name="username" value="" id="username">
<label for="password">Password:</label>
<input type="password" name="password" value="" id="password">

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next|escape }}" />

</form>

{% endblock %}
12 裝飾器
from django.contrib.auth.decorators import login_required

@login_required
13货邓、登錄與權(quán)限
def vote(request):
if request.user.is_authenticated() and request.user.has_perm('polls.can_vote')):
# vote here
else:
return HttpResponse("You can't vote in this poll.")
===@user_passes_test(user_can_vote,login_url="/login/")
def user_can_vote(user):
return user.is_authenticated() and user.has_perm("polls.can_vote")

@user_passes_test(user_can_vote, login_url="/login/")
def vote(request):
# Code here can assume a logged-in user with the correct permission.

14、權(quán)限:@permission_required
from django.contrib.auth.decorators import permission_required

@permission_required('polls.can_vote', login_url="/login/")
def vote(request):
# ...
15职辨、創(chuàng)建用戶:

from django.contrib.auth.models import User
user = User.objects.create_user(username='john',
... email='jlennon@beatles.com',
... password='glass onion')
user.is_staff = True
user.save()
修改密碼
user = User.objects.get(username='john')
user.set_password('goo goo goo joob')
user.save()
16舒裤、
{% if user.is_authenticated %}
<p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
<p>Welcome, new user. Please log in.</p>
{% endif %}
17觉吭、檢查權(quán)限
{% if perms.polls %}
<p>You have permission to do something in the polls app.</p>
{% if perms.polls.can_vote %}
<p>You can vote!</p>
{% endif %}
{% else %}
<p>You don't have permission to do anything in the polls app.</p>
{% endif %}
18、用戶消息
def create_playlist(request, songs):
# Create the playlist with the given songs.
# ...
request.user.message_set.create(
message="Your playlist was added successfully."
)
return render_to_response("playlists/create.html",
context_instance=RequestContext(request))

{% if messages %}
<ul>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末宏赘,一起剝皮案震驚了整個濱河市黎侈,隨后出現(xiàn)的幾起案子峻汉,更是在濱河造成了極大的恐慌,老刑警劉巖休吠,帶你破解...
    沈念sama閱讀 206,602評論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件瘤礁,死亡現(xiàn)場離奇詭異柜思,居然都是意外死亡,警方通過查閱死者的電腦和手機赡盘,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,442評論 2 382
  • 文/潘曉璐 我一進(jìn)店門陨享,熙熙樓的掌柜王于貴愁眉苦臉地迎上來抛姑,“玉大人,你說我怎么就攤上這事途戒∨缯” “怎么了?”我有些...
    開封第一講書人閱讀 152,878評論 0 344
  • 文/不壞的土叔 我叫張陵浆西,是天一觀的道長顽腾。 經(jīng)常有香客問我,道長久信,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 55,306評論 1 279
  • 正文 為了忘掉前任,我火速辦了婚禮腿椎,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘铆隘。我一直安慰自己南用,他們只是感情好裹虫,可當(dāng)我...
    茶點故事閱讀 64,330評論 5 373
  • 文/花漫 我一把揭開白布恒界。 她就那樣靜靜地躺著砚嘴,像睡著了一般。 火紅的嫁衣襯著肌膚如雪耸采。 梳的紋絲不亂的頭發(fā)上工育,一...
    開封第一講書人閱讀 49,071評論 1 285
  • 那天如绸,我揣著相機與錄音,去河邊找鬼搪泳。 笑死扼脐,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的艰赞。 我是一名探鬼主播,決...
    沈念sama閱讀 38,382評論 3 400
  • 文/蒼蘭香墨 我猛地睜開眼狭魂,長吁一口氣:“原來是場噩夢啊……” “哼吁断!你這毒婦竟也來了仔役?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 37,006評論 0 259
  • 序言:老撾萬榮一對情侶失蹤任柜,失蹤者是張志新(化名)和其女友劉穎宙地,沒想到半個月后逆皮,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 43,512評論 1 300
  • 正文 獨居荒郊野嶺守林人離奇死亡秽梅,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 35,965評論 2 325
  • 正文 我和宋清朗相戀三年企垦,在試婚紗的時候發(fā)現(xiàn)自己被綠了晒来。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 38,094評論 1 333
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖竹习,靈堂內(nèi)的尸體忽然破棺而出整陌,到底是詐尸還是另有隱情瞎领,我是刑警寧澤随夸,帶...
    沈念sama閱讀 33,732評論 4 323
  • 正文 年R本政府宣布,位于F島的核電站驼修,受9級特大地震影響诈铛,放射性物質(zhì)發(fā)生泄漏幢竹。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 39,283評論 3 307
  • 文/蒙蒙 一蹲坷、第九天 我趴在偏房一處隱蔽的房頂上張望邑飒。 院中可真熱鬧,春花似錦县匠、人聲如沸撒轮。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,286評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽扮惦。三九已至臀蛛,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間崖蜜,已是汗流浹背浊仆。 一陣腳步聲響...
    開封第一講書人閱讀 31,512評論 1 262
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留豫领,地道東北人抡柿。 一個月前我還...
    沈念sama閱讀 45,536評論 2 354
  • 正文 我出身青樓,卻偏偏與公主長得像等恐,于是被迫代替她去往敵國和親洲劣。 傳聞我的和親對象是個殘疾皇子备蚓,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 42,828評論 2 345

推薦閱讀更多精彩內(nèi)容