Django framework 11- basics and forms to maintain session state

Browser stores the cookie way less secure, that there is no better to store login state the way it ???

While maintaining ---- cookie and session:

 

State remains:

1.http protocol is stateless: is a new request each time a request will not remember status before communication

A communication session is one way to achieve hold state 2. The client and server: the data relating to the client or the server stores session

3. The storage including cookie, session, the session generally refers to the session object

\ 4. Using cookie, all the data stored on the client, be careful not to store sensitive information

5. sesison embodiment, on the server side, the client all data stored in the cookie store session_id

The purpose is to keep track the status of state 6 requester over a period of time, data access across the page currently requester can be achieved

- Note: This data is not shared between different requesters, correspondence with the requestor

Enable session:

The default is has enabled the

In settings.py file

 

 

Note: you need to perform makemigrations, migrate the model mapping file commands before using the session, have generated django_session table in the database.

Use session:

After enabling session, each HttpRequest object will have a session attribute, which is a dictionary-like object

- get (key, default = None): Get value of the session key in accordance with

- clear (): Clear all sessions

- flush (): Delete the current session data and deletes the session Cookie

- del request.session['member_id']-:删除

Users logged example:

 

1. A subject can read but also write a dictionary-like, represents the current session.

2. Use the information request.session set up a login at the login.

3. Get the value set in the main page, and then passed to the template.

4. request.session.flush () clear the session data.

Examples of user login:

 

Session expiration:

  • set_expiry (value): Set session timeout

  • 如果没有指定,则两个星期后过期

  • 如果value是一个整数,会话将在values秒没有活动后过期

  • 若果value是一个timedelta对象,会话将在当前时间加上这个指定的日期/时间过期

  • 如果value为0,那么用户会话的Cookie将在用户的浏览器关闭时过期

  • 如果value为None,那么会话永不过期

 

 

可以不配置,那么都是默认的选项

我们实现了登录状态的保持了, 接下来,如果需要注册登录呢?

登录注册实现思路:

 

登录注册第一步--创建模型生成数据表:

 

执行映射文件生成数据表

 

 

form表单的引用:

登录页面和注册页面都会用到form表单来提交数据

 

当数据提交到后台后,需要在视图函数中去验证数据的合法性.

 

django中提供了一个form表单的功能,这个表单可以用来验证数据的合法性还可以用来生成HTML代码

 

今天的登录注册案例我们就来使用这个django自带的form来生成前端页面以及验证数据.

关于django form表单的使用:

  1. 创建一个forms.py的文件,放在指定的app当中,然后在里面写表单.

  2. 表单是通过类实现的,继承自forms.Form,然后在里面定义要验证的字段.

  3. 在表单中,创建字段跟模型是一模一样的,但是没有null=True或者blank=True等这几种参数了,有的参数是required=True/False.

  4. 使用is_valid()方法可以验证用户提交的数据是否合法,而且HTML表单元素的name必须和django中的表单的name保持一致,否则匹配不到.

  5. is_bound属性:用来表示form是否绑定了数据,如果绑定了,则返回True,否则返回False.

  6. cleaned_data:这个是在is_valid()返回True的时候,保存用户提交上来的数据.

form表单例子:

 

 

可以生成前端页面,也可以用来验证数据的合法性.

 

 

注册的form表单:

 

 

form表单中的一些参数说明:

max_length 最大长度

min_length 最小长度

widget 负责渲染网页上HTML 表单的输入元素和提取提交的原始数据

attrs 包含渲染后的Widget 将要设置的HTML 属性

error_messages 报错信息

注:虽然form可以生成前端页面,但这个功能实际用的少,主要是是用form表单的验证功能.

注册的视图函数:

from .forms import RegisterFrom

from .models import UserModel

def register(request):

if request.method == 'GET':

form = RegisterFrom()

return render(request,'ts22/register.html',

context={'form':form})

elif request.method == 'POST':

form = RegisterFrom(request.POST)

if form.is_valid():

username = form.cleaned_data.get('username')

password = form.cleaned_data.get('password')

password_repeat = form.cleaned_data.get('password_repeat')

email = form.cleaned_data.get('email')

if password == password_repeat:

user = UserModel.objects.create(username=username, password=password,email=email)

return HttpResponse('注册成功!')

else:

return HttpResponse('注册失败!')

else:

return HttpResponse('注册失败!')

将RegisterForm类生成实例,传入模板渲染前端页面d

将获取到的参数传入RegisterForm类,用is_valid()方法验证提交数据的合法性

用cleaned_data获取单个数据对象值

登录的form表单及模板:

 

 

登录视图函数:

 

form.as_p,加p标签

定义模型表单:

from teacher.models import Student,StudentDetails
class StudentForm(forms.ModelForm):
  class Meta:
      model = Students
      exclude = ['is_deleted']
      class StudentDetailForm(forms.ModelForm):
  class Meta:
      model = StudentDetails
      exclude = ['student']

也可以用fields方法指定想要的字段.列表格式.

detail_form = StudentDetailForm(request.POST)

student.detail = detail_form.save(commit=False)

这样就不会真的提交.因为还要加上外键关联对象.

 

form = StudentForm(instance=student)

说明这个表单是student实例的表单,如果没有实例,在执行save()的时候会创建.

括号中不写instance就会生成一个新的实例,写instance就会修改instance

Guess you like

Origin www.cnblogs.com/winfun/p/10968212.html