zoukankan      html  css  js  c++  java
  • Django之form组件加cookie,session

    ---恢复内容开始---

    多对表的三种创建

    一全自动(推荐使用)

      优点:不需要手动创建第三张表也就是我们之前一直用的,靠那个不会在数据库中显示的虚拟字段,告诉orm帮我们创建能够表示多对多关系的第三张表。

      缺点:因为都是orm帮我们完全创建好了,所以拓展性低,字段都已经固定死了。

      

    class Book(models.Model):
                title = models.CharField(max_length=32)
                    price = 
                  models.DecimalField(max_digits=8,decimal_places=2)
                    authors = 
                 models.ManyToManyField(to='Author')

    class Author(models.Model):
        name = models.CharField(max_length=32)

     纯手动(了解即可)

      自己创建第三张表

      优点:因为是自己创建的,所以拓展性高

      缺点:要自己手动,另外不能用正向查询了

    class Book(models.Model):
                    title = models.CharField(max_length=32)
                    price = models.DecimalField(max_digits=8,decimal_places=2)
    
    
                class Author(models.Model):
                    name = models.CharField(max_length=32)
                    
                    
                class Book2Author(models.Model):
                    book = models.ForeignKey(to='Book')
                    author = models.ForeignKey(to='Author')
                    create_time = models.DateField(auto_now_add=True)

    半自动(推荐使用)

    优点其结合了手动与全自动的优点

    class Book(models.Model):
                    title = models.CharField(max_length=32)
                    price = models.DecimalField(max_digits=8,decimal_places=2)
                    authors = models.ManyToManyField(to='Author',through='Book2Author',through_fields=('book','author'))
                    # through 告诉django orm 书籍表和作者表的多对多关系是通过Book2Author来记录的
                    # through_fields 告诉django orm记录关系时用过Book2Author表中的book字段和author字段来记录的
                    """
                    多对多字段的
                    add
                    set
                    remove
                    clear不支持
                    """
                    
                    
                class Author(models.Model):
                    name = models.CharField(max_length=32)
                    # books = models.ManyToManyField(to='Book', through='Book2Author', through_fields=('author', 'book'))
    
    
                class Book2Author(models.Model):
                    book = models.ForeignKey(to='Book')
                    author = models.ForeignKey(to='Author')
                    create_time = models.DateField(auto_now_add=True)

    Form组件

    用来渲染标签,校验数据和展示信息的。

    基础用法

    1.写一个基础了forms.Form的类
                    from django import forms
    
    
                    class LoginForm(forms.Form):
                        username = forms.CharField(max_length=8,min_length=3)  # 用户名最长八位最短三位
                        password = forms.CharField(max_length=8,min_length=5)  # 密码最长八位最短五位
                        email = forms.EmailField()  # email必须是邮箱格式
            

    基本使用

    from app01 import views
    1.将需要校验的数据 以字典的方式传递给自定义的类 实例化产生对象
    form_obj = views.LoginForm({'username':'jason','password':'123','email':'123'})
    2.如何查看数据是否全部合法
    form_obj.is_valid()  # 只有所有的数据都符合要求 才会是True,False
    3.如何查看错误原因form_obj.errors{
    'password': ['Ensure this value has at least 5 characters (it has 3).'], 
    'email': ['Enter a valid email address.']
                        }
    4.如何查看通过校验的数据
    form_obj.cleaned_data  
    {'username': 'jason'}

    注意:

    自定义的那些字段默认都必须是要传值的,因为每个字段内部的required默认都是true,也就是默认都是要传值的,要想不传值改为false就可以。

    另外可以额外传入类中没有的字段,其不会接收,只会接收内部有的,所以多传可以,但少接收不可。

    渲染标签(三种方式)

    <p>第一种渲染页面的方式(封装程度太高 一般只用于本地测试  通常不适用)</p>
    {{ form_obj.as_p }}
    {{ form_obj.as_ul }}
    {{ form_obj.as_table }}
    
    
    <p>第二种渲染页面的方式(可扩展性较高 书写麻烦)</p>
    <p>{{ form_obj.username.label }}{{ form_obj.username }}</p>
    <p>{{ form_obj.password.label }}{{ form_obj.password }}</p>
    <p>{{ form_obj.email.label }}{{ form_obj.email }}</p>
    
    
    
    <p>第三种渲染页面的方式(推荐)</p>
    {% for foo in form_obj %}
    <p>{{ foo.label }}{{ foo }}</p>
    {% endfor %}

    注意:form组件渲染标签只会渲染用户输入的标签,不会去渲染其他的。

    前端的校验可有可无,但后端的检验一定要有,取消前端自动校验,在form表单中加个参数即可,novalidate.

        <form action="" method='post' novalidate></form>

    展示错误信息

    前端代码
    {% for foo in form_obj %}
    <p>{{ foo.label }}:{{ foo }}
    <span>{{ foo.errors.0 }}</span>
    </p>
    {% endfor %}
    
    
    后端的
    password = forms.CharField(max_length=8,min_length=5,label='密码',error_messages={
                                       'max_length':'密码最大八位',
                                       'min_length':'密码最小五位',
                                       'required':'密码不能为空'
                                   },required=False,validators=[RegexValidator(r'^[0-9]+$', '请输入数字'), RegexValidator(r'^159[0-9]+$', '数字必须以159开头')])  # 密码最长八位最短五位
                        

    钩子函数(就是用来校验字段的)

    注意:钩子函数的执行时机是在所有的数据全部都检验合法之后,全部都放入到cleaned_data中后才会执行钩子函数。

    局部钩子(校验一个字段)

    固定语法:

    def clean_校验的字段名(self):
    username = self.cleaned_data.get('username')
    if '666' in username:
    self.add_error('username','光喊666是不行的 你得自己上')
    return username

    全局钩子函数(多个字段校验)

    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

    Form组件其他操作

    required  是否必填
    label         注释信息
    error_messages  报错信息        
    initial        默认值
    widget        控制标签属性和样
    radioSelect
    但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()
        )
    单选Select
    class LoginForm(forms.Form):
        ...
        hobby = forms.ChoiceField(
            choices=((1, "篮球"), (2, "足球"), (3, "双色球"), ),
            label="爱好",
            initial=3,
            widget=forms.widgets.Select()
        )

    多讯select

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

    单选checkbox

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

    多选checkbox

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

    cookie和session

    由于http协议是无状态的,所以不会保留客户端的状态,这个时候就要用到cookie和session了。

    cookie:就是保存在客户端浏览器的键对值

    工作原理:

    当你成功登录后,浏览器会保存一些信息,下次再访问的时候,浏览器会携带这些信息,发送给服务端,服务端拿着这些去识别身份。

    session是保存在服务端的特殊键对值,会发给浏览器一份,这样下次登录的话只要拿着这个session值来将可以,校验通过就过,没有就不过。

    session是依赖于cookie工作的。

     它是会返回浏览器一个随机的字符串,存放在cookie中

    浏览器以键对值存储

    sessionid: 随机字符串

     操作cookie:

    django返回给客户端浏览器的都必须是HttpResponse对象
    return HttpResponse()
    return render()
    return redirect()
    
    obj1 = HttpResponse()
    return obj1
    obj2 = render()
    return obj2
    obj3 = redirect()
    return obj3
    
    
    设置cookie就是利用的HttpResponse对象
    
    obj1.set_cookie('k1','v1')
    
    获取cookie对象
    request.COOKIE.get()
    删除cookie
    obj.delete_cookie('k1')
    设置超时时间
    
    max_age=None, 超时时间
    expires=None, 超时时间(IE requires expires, so set it if hasn't been already.)

    session

        设置session
                request.session['name'] = 'jason'
                """
                上面这一句话发生了三件事
                    1.django 内部自动生成一个随机字符串
                    2.将随机字符串和你要保存的数据 写入django_session表中(现在内存中生成一个缓存记录 等到经过中间件的时候才会执行)
                    3.将产生的随机字符串发送给浏览器写入cookie
                        sessionid:随机字符串
                """
    
    获取session
                request.session.get('name')
                """
                上面这一句话发生了三件事
                    1.django内部会自动从请求信息中获取到随机字符串
                    2.拿着随机字符串去django_session表中比对
                    3.一旦对应上了就将对应的数据解析出来放到request.session中
                
                """
    
    
    django_session默认超时时间是14天
    django_session表中的一条记录针对一个浏览器
    
    request.session.set_expiry(value)
                * 如果value是个整数,session会在些秒数后失效。
                * 如果value是个datatime或timedelta,session就会在这个时间后失效。
                * 如果value是0,用户关闭浏览器session就会失效。
                * 如果value是None,session会依赖全局session失效策略。
    
    总结:你在后期可以将一些数据保存到session表中,保存的数据 可以在后端任意位置获取到
  • 相关阅读:
    php pdf添加水印(中文水印,图片水印)
    论文阅读---Reducing the Dimensionality of Data with Neural Networks
    Deep Learning综述[下]
    Install-Package:QRCoder已拥有为System.Drawing.Common定义的依赖项
    linux和windows之间传递文件
    IPV6修复工具
    Deep Learning综述[上]
    novaclient开发中遇到的问题小结
    easybcd删除win10启动项如何恢复?
    uefi+gpt安装双系统
  • 原文地址:https://www.cnblogs.com/xinfan1/p/11580439.html
Copyright © 2011-2022 走看看