Django's form form, cookie, session

form components

The main function of the form component as follows:

  • Render tag
  • Check data
  • Display information

Check data

The first step is to import the module forms, form and define a class

from django import forms

class MyForm(forms.Form):
    name = forms.CharField(max_length=6)
    password = forms.CharField(max_length=8, min_length=3)
    email = forms.EmailField(required=True)

The second step form objects instantiated

form_obj = MyForm({
'name': 'linwow',
'password': '123123'
'email': '[email protected]'
})

The third step is to view the data check is legitimate

form_obj.is_valid()  # 只有当所有的字段都校验通过才会返回True

The fourth step to see validation error message

form_obj.errors  # 这个里面放的是所有校验未通过的字段及错误提示
"""
{
'name': ['Ensure this value has at most 6 characters (it has 7).'], 
'password': ['Ensure this value has at least 3 characters (it has 2).'], 
'email': ['Enter a valid email address.']
}

"""

The fifth step is to view the data by check

form_obj.cleaned_data  # 符合校验规则数据都会被放到该对象中

ps: 
	form组件校验数据的规则从上往下依次取值校验
	校验通过的放到cleaned_data
	校验失败的放到errors

Note:
form all fields must pass all default values (required = True);
when the check data can pass multiple values, multi-pass data will not do any check, check will not affect form rule.

Render tag

form components can render the label to obtain user input, but does not render the submit button, add manually. If the data submitted to the form component is not legitimate, it will retain the information before the user enters the page.

The first rendering

<h1> 第一种渲染方式(可扩展性较差) </h1>
{{form_obj.as_p}}
{{form_obj.as_ul}}

The second rendering

<h1> 第二种渲染方式 </h1>
<form action = "">
<p> {{form_obj.name.label}} {{form_obj.name}} </p>
<p> {{form_obj.password.label}} {{form_obj.password}} </p>
<p> {{form_obj.email.label}} {{form_obj.email}} < / p >
<input type="submit"></form>

A third way of rendering the label

<h1> 第三种渲染标签的方式 </h1>
<form action="">
{% for foo in form_obj %}
<p> {{foo.label}} {{foo}} </p>
{ % endfor %}
</form>

Note: When using the model table form the component data validation, you only need to ensure consistent field, then you can use ** form_obj.cleaned_data directly in the database is created when an object

Settings tab style

from django import forms
from django.forms import widgets
password = forms.CharField(max_length=8,min_length=3,error_messages={
                    'max_length': '密码最长8位',
                    'required': '密码不能为空',
                    'min_length':'密码最少3位'
                    },widget=widgets.PasswordInput(attrs={'class':'c1 form-control'}))

Hook function

Clean_ defined field name () method in class Fom, it is possible to achieve a specific field of the checksum.

class MyForm(forms.Form):
    name = forms.CharField(max_length=6,label='用户名',error_messages={
        'max_length':'用户名最长6位',
        'required':'用户名不能为空'
    })
    password = forms.CharField(max_length=8,min_length=3,error_messages={
        'max_length': '密码最长8位',
        'required': '密码不能为空',
        'min_length':'密码最少3位'
    },widget=widgets.PasswordInput(attrs={'class':'c1 form-control'}))
    confirm_password = forms.CharField(max_length=8, min_length=3, error_messages={
        'max_length': '确认密码最长8位',
        'required': '确认密码不能为空',
        'min_length': '确认密码最少3位'
    },widget=widgets.PasswordInput())
    email = forms.EmailField(error_messages={
        'invalid':'邮箱格式不正确',
        'required':'邮箱不能为空'
    })

Local hook function (a single field using local parity hook function)

def clean_name(self):
    name = self.cleaned_data.get('name')
    if 'sb' in name:
        self.add_error('name', '用户名中不能包含敏感词汇!')
    return name  # return还是要加上的,兼容性考虑

Global hook function (by using a plurality of verification fields global hook function)

def clean(self):
    password = self.cleaned_data.get('password')
    confirm_password = self.cleaned_data.get('confirm_password')
    if not password == confirm_password:
        self.add_error('confirm_password', "两次密码不一致!")
    return self.cleaned_data

Common Fields and plug-ins

When creating Form class, mainly related to the field of [] and [] plug, field is used to authenticate the user requesting the data, for automatically generating the HTML plug;

initial

The initial value, the initial value input box inside.

class LoginForm(forms.Form):
    username = forms.CharField(
        min_length=8,
        label="用户名",
        initial="张三"  # 设置默认值
    )
    pwd = forms.CharField(min_length=6, label="密码")

error_messages

Rewrite error message.

class LoginForm(forms.Form):
    username = forms.CharField(
        min_length=8,
        label="用户名",
        initial="张三",
        error_messages={
            "required": "不能为空",
            "invalid": "格式错误",
            "min_length": "用户名最短8位"
        }
    )
    pwd = forms.CharField(min_length=6, label="密码")

password

class LoginForm(forms.Form):
    ...
    pwd = forms.CharField(
        min_length=6,
        label="密码",
        widget=forms.widgets.PasswordInput(attrs={'class': 'c1'}, render_value=True)
    )

radioSelect

Value is a string of single radio

class LoginForm(forms.Form):
    username = forms.CharField(
        min_length=8,
        label="用户名",
        initial="张三",
        error_messages={
            "required": "不能为空",
            "invalid": "格式错误",
            "min_length": "用户名最短8位"
        }
    )
    pwd = forms.CharField(min_length=6, label="密码")
    gender = forms.fields.ChoiceField(
        choices=((1, "男"), (2, "女"), (3, "保密")),
        label="性别",
        initial=3,
        widget=forms.widgets.RadioSelect()
    )

Radio Select

class LoginForm(forms.Form):
    ...
    hobby = forms.ChoiceField(
        choices=((1, "篮球"), (2, "足球"), (3, "双色球"), ),
        label="爱好",
        initial=3,
        widget=forms.widgets.Select()
    )

Select multiple choice

class LoginForm(forms.Form):
    ...
    hobby = forms.MultipleChoiceField(
        choices=((1, "篮球"), (2, "足球"), (3, "双色球"), ),
        label="爱好",
        initial=[1, 3],
        widget=forms.widgets.SelectMultiple()
    )

Radio checkbox

class LoginForm(forms.Form):
    ...
    keep = forms.ChoiceField(
        label="是否记住密码",
        initial="checked",
        widget=forms.widgets.CheckboxInput()
    )

Multi-select checkbox

class LoginForm(forms.Form):
    ...
    hobby = forms.MultipleChoiceField(
        choices=((1, "篮球"), (2, "足球"), (3, "双色球"),),
        label="爱好",
        initial=[1, 3],
        widget=forms.widgets.CheckboxSelectMultiple()
    )

cookie

Cookie specifically referring to was a little information, it is the server sends out a bundle of keys stored on the browser's right, next time you access the server browser will automatically carry these key-value pairs for the server to extract useful information.

Works cookie is: generated content from the server, the browser receives the request saved locally; when the browser visits, the browser will automatically bring the Cookie, so the server can be judged by the content of this Cookie "who "a.

Set cookie

obj.set_cookie()  # 给浏览器设置cookie

Get cookie

request.COOKIE.get('name')
request.COOKIE['name']

Examples

def login(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        if username == 'linwow' and password == '123':
            old_path = request.GET.get('next')
            if old_path:
                obj = redirect(old_path)
            else:
                obj = redirect('/home/')
            # 用户登录成功 朝浏览器设置一个cookie
            obj.set_cookie('name', 'linwow', expires=7 * 24 * 3600)
            return obj
    return render(request, 'login.html')
from functools import wraps

def login_auth(func):
    @wraps(func)
    def inner(request, *args, **kwargs):
        # 校验cookie
        # print(request.get_full_path())
        old_path = request.get_full_path()
        if request.COOKIES.get('name'):
            return func(request, *args, **kwargs)
        return redirect('/login/?next=%s' % old_path)
    return inner

def logout(request):
    rep = redirect("/login/")
    rep.delete_cookie("user")  # 删除用户浏览器上之前设置的usercookie值
    return rep

session

Set session

request.session['name'] = 'linwow'
  • First generates a random string
  • The random string and the recording data stored in django session table
  • Will send a random string to the client browser

Obtaining session

request.session.get('name')
  • django browser automatically obtain the session django random character strings inside the table (session set value browser to store a key for the sessionid) alignments
  • If the match succeeds, the data current corresponding random string assigned to request.session
  • (Data does not exist and will not affect our business logic) by operating the data request.session

Delete all data in the current session of the Session

request.session.delete()

Delete the current session data and delete the Cookie session.

request.session.flush()

This is used to ensure that the previous session data can not be accessed again the user's browser,
for example, django.contrib.auth.logout ()
function is called it.

Setting Session Session and Cookie timeout

request.session.set_expiry(value)
--如果value是个整数,session会在些秒数后失效。
--如果value是个datatime或timedelta,session就会在这个时间后失效。
--如果value是0, 用户关闭浏览器session就会失效。
--如果value是None, session会依赖全局session失效策略。

Guess you like

Origin blog.csdn.net/linwow/article/details/92709068