荣誉墙项目day28 django常用函数

1、在网页上渲染字符串
from django.http import HttpResponse
return HttpResponse(u"hello world")

2、渲染网页
from django.shortcuts import render
return render(request,"index.html",{"username":"zhangsuosheng"})#带了一个username参数

3、获取post表单信息:
username=request.POST.get('username','')

4、在django自带的登陆数据库auth_user中查询用户:
from django.contrib import auth
user=auth.authenticate(username="zhangsuosheng",password="123456")
(如果没有这个用户,则返回值为None,可以用 if user is None判断)

5、在django自带的登陆数据库auth_user中添加用户:
from django.contrib.auth.models import User
new_user=User.objects.create_user(username="zhangsuosheng", password="123456")
new_user.first_name="zhang"
new_user.last_name="suosheng"
new_user.save()

6、在django登陆验证系统中设定某用户已登陆:
from django.contrib import auth
auth.login(request,user)
这里的user就是django自带的用户对象,如2、中的user和3、中的new_user

7、记录session
request.session['键']="值"

8、获取session

9、记录cookie
response=HttpResponseRedirect('/index') #先定义要记录cookie的请求
response.set_cookie('键',"值",保存的时间)
如:respon.set_cookie('username',"zhangsuosheng",3600)

10、获取cookie
def index(request)
username=request.COOKIES.get('username','')
return render(request,"index.html",{"username":username})

11、重定向
from django.http import HttpResponseRedirect
return HttpResponseRedirect('从项目根目录起完整的url')
如:return HttpResponseRedirect('/index/')

原文地址:https://www.cnblogs.com/zealousness/p/7396692.html