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:参数包括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'。
确认 INSTALLED_APPS 中有 'django.contrib.sessions' (同时需要同步数据库)
--
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没有设置过期时间,当用户关闭浏览器的时候,cookie就自动过期了。 你可以改变 SESSION_EXPIRE_AT_BROWSER_CLOSE 的设置来控制session框架的这一行为。
缺省情况下, SESSION_EXPIRE_AT_BROWSER_CLOSE 设置为 False ,这样,会话cookie可以在用户浏览器中保持有效达 SESSION_COOKIE_AGE 秒(缺省设置是两周,即1,209,600 秒)。 如果你不想用户每次打开浏览器都必须重新登陆的话,用这个参数来帮你。
SESSION_COOKIE_DOMAIN 作用域
SESSION_COOKIE_NAME cookie名字
SESSION_COOKIE_SECURE 是否通过HTTPS传输
Session 数据存在数据库表 django_session 中
5、auth模块
将 'django.contrib.auth' 放在你的 INSTALLED_APPS 设置中,然后运行 manage.py syncdb以创建对应的数据库表。
确认 SessionMiddleware 后面的 MIDDLEWARE_CLASSES 设置中包含 'django.contrib.auth.middleware.AuthenticationMiddleware' SessionMiddleware。
//调用: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/', logout),
)
11、registragiton/login.html login_out.html
{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Sorry, that's not a valid username or password


{% endif %}







{% endblock %}
12 装饰器
from django.contrib.auth.decorators import login_required

@login_required
13、登录与权限
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、权限:@permission_required
from django.contrib.auth.decorators import permission_required

@permission_required('polls.can_vote', login_url="/login/")
def vote(request):
# ...
15、创建用户:

from django.contrib.auth.models import User
user = User.objects.create_user(username='john',
... email='[email protected]',
... 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 %}

Welcome, {{ user.username }}. Thanks for logging in.


{% else %}

Welcome, new user. Please log in.


{% endif %}
17、检查权限
{% if perms.polls %}

You have permission to do something in the polls app.


{% if perms.polls.can_vote %}

You can vote!


{% endif %}
{% else %}

You don't have permission to do anything in the polls app.


{% 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 %}


    {% for message in messages %}
  • {{ message }}

  • {% endfor %}

{% endif %}

你可能感兴趣的:(Django2.0中文(会话、用户、注册))