Form a component of django

A, model common operations

  1, 13 API query: all, filter, get, values, values_list, distinct, order_by, reverse, exclude (excluded), count, first, last, esits (to determine whether there is)

  Differences need to know all, values, values_list of

    all: QuerySet is a collection of print, a list of objects which put

    values: a dictionary form

    values_list: it is in the form of a tuple  

  Performance is the lowest of all

  2、only和defer

. datalist = models.Userinfo.objects.all () only ( "name", "email") # or get a QuerySet collection, just take the name and Email 
for in the DataList Item: 
    Print (item.id) 
    Print (Item .name) 
    Print (item.pwd) # long table has the fields, it would take the value of the additional request will Zaifayici 

datalist = models.Userinfo.objects.all (). defer ( "name", "email ") # stop, do not take the name and Email 
for in the DataList Item: 
    Print (item.id) 
    Print (item.pwd)

  Note: Use only if you pick only the inside of the field and other fields to take too inefficient, and as little as possible of the database connection

  3, routing system

  Reverse generate URL:

    There are two ways: {% url "a1"%}

          reverse("a1")

With reverse need to import from django.core.urlresolvers import reverse

/index/     func    name=a1
    {% url "a1"}
     reverse('a1')
                
/index/(\d+)/     func    name=a2
    {% url "a2" 11 %}
    reverse('a2',args=(11,))
                
/index/(?P<nid>\d+)/     func    name=a3
    {% url "a2" nid=11 %}
    reverse('a3',kwargs={'nid':11})

 

 4, Django's life cycle

               Web Server Gateway Interface (Python Web Server Gateway Interface, abbreviated as WSGI)

    1, first of all go wsgi module, which is a protocol, including wsgiref and uwsgi.

    2, then routing assignment ------- views view

    3, fetch data from the database to a rendering html -----------

    Note If you import js file is not rendered.

  5, HTTP protocol

    See the next blog post                                                                                                

Two, Form Components

A, Form Components Introduction

Form component can do several things:

  1, the user authentication data request

  2, an error message generated automatically    

  3, packing correct information submitted by the user

  4. If there is a mistake, correct it other, to retain the previous entry

  4, input tag is automatically created and can set style

Second, the use of Form components

  1, create a rule

class Foo (Form): # must inherit 
    username = xxx 
    password = xxx 
    Email = xxx 
Note field here must be consistent with the name field input

 

  2, data and rules matched

First import view.py

from django.forms import Form
from django.forms import fields
from django.forms import widgets

 

Import the render django.shortcuts from, redirect 
from app01 Import Models 
# the Create your views here Wallpaper. 
from `` django.forms`` Import Form 
from `` django.forms`` Import Fields 
from `` django.forms`` Import Widgets 
# 1, create a rule 
class TeacherForm (Form): # must inherit Form 
    # create fields, in essence, is a regular expression 
    username = fields.CharField ( 
        required = True # required fields 
        error_messages = { "required": "username can not be empty!"}, # display Chinese error 
        widget = widgets.TextInput (attrs = { "placeholder" : " user name", "class": "form -control"}) # automatically generated input block 
       ) '})) # Can not be empty 
    email = fields.EmailField ( 
    password = fields.CharField (required = True, error_messages, = { 'required': 'password can not be blank'},
                                widget = widgets.TextInput (attrs = { ' placeholder': ' password', 'class': 'form -control'})) # can not be empty 
        required = True, 
        error_messages, = { "required": "E-mail can not be empty! ! "," invalid ":" invalid mailbox "}, 
        the widget = widgets.EmailInput (attrs = {" placeholder ":" E-mail "," class ":" form -control "}) # automatically generated input box 
    ) not # empty mailbox format to be consistent and 

# 2, using the rule: the data and rules matched 
DEF teacherindex (Request): 
    teacher_obj models.UserInfo.objects.all = () 
    # Print (teacher_obj) 
    return the render (Request, "teacherindex.html ", {" teacher_obj ": teacher_obj}) 
DEF the Add (Request): 
    IF request.method ==" the GET ":
        form = TeacherForm () # just let input box to display a 
        return render (request, "add.html" , { "form": form})
    the else: 
        form = TeacherForm (= Data of request.POST)  
        # Print (form) # <QuerySet [<UserInfo: UserInfo object>, <UserInfo: UserInfo object>, <UserInfo:Object UserInfo>]> 
        IF form.is_valid (): # start the verification
            # Print ( 'executed successfully', form.cleaned_data) # all successful match, the dictionary 
            # { 'username': 'asd ', 'password': 'sdf', 'email ':' [email protected] ',' ut_id ':. 1} 
            form.cleaned_data [' ut_id '] = #. 1 min to clear a teacher or instructor 
            . models.UserInfo.objects.all () create (** form .cleaned_data) 
            return redirect ( "/ teacherindex /") 
        the else: 
            "? =====" # Print (, form.errors, of the type (form.errors)) # returns a failure result 
            # print (form.errors [ " username "] [0]) # get returns a failure result, rendering the page to 
            return render (request," add.html " , {" form ": form})

 

html.py

{% block right %}
    <h1>添加老师信息</h1>
    <hr>
    <form method="post" novalidate>
        {% csrf_token %}
        <p>姓名:{{ form.username }}</p>{{ form.errors.username.0 }}
        <p>密码:{{ form.password }}</p>{{ form.errors.password.0 }}
        <p>邮箱:{{ form.email }}</p>{{ form.errors.email.0 }}
        <p><input type="submit" value="提交"></p>
    </form>
{% endblock %}

If the access is a view of a GET request, it creates a blank form and place it into the context instance to render the template. This is what we expected to occur during the first visit that URL.

If you use a form to submit POST a request, then the view will again create a form instance and populate it with data in the request: form = NameForm(request.POST). This is called "bind data to the form" (it is now a binding form).

We call the form's is_valid()method; if it is not True, we will take this form to return to the template. In this case the data is no longer empty form (unbound), it will be submitted in HTML form before filling, then edited according to the requirements and correct it.

If is_valid()is True, we will be able to cleaned_data find all legitimate form data attribute. Sending an HTTP redirect to the browser to tell it before the next step is going, we can use this data to update the database or do other processing.

Note: form = TeacherForm () # no argument, just an input box

    form = TeacherForm (data = request.POST) # placement data and rules (added when used) with

    form = TeacherForm (initial = { 'username': obj.username, 'password': obj.password, 'email': obj.email}) # display input, and the default value database and fill in the input box (Edit when used)

 

Widgets

Each form field has a corresponding Widget class, which corresponds to an HTML form Widget, for example <input type="text">.

In most cases, the field has a reasonable default Widget. For example, by default, CharField has a TextInput Widget, it generates a in HTML <input type="text">.

Data fields

No matter what form submission data, by calling upon is_valid() successful verification ( is_valid() return True), the form data is verified, located in form.cleaned_data the dictionary. These data have been converted well for you to type Python.

Note: At this point, you still can from request.POST access directly to unverified data, but the data access authentication better.

In the contact form above example, is_married will be a boolean value. Similarly, IntegerField and FloatField field values are converted to the Python int and float.

Third, the database table design

Note that when a few design table:

  1, nid = models.AutoField (primary_key = True) # If you do not specify a default django will add the id

    nid = models.BigAutoField (primary_key = True) # int but those can not meet you, to use BigAutoField

  2, comments are typically added for the class in the class which

  3, verbose_name = "Title" field of Chinese Tips

  4, ForeignKey (to = "table name", tofield = "field") # can not write to these two, but be sure to write the name of the associated table

  5, releated_name = "uuu" reverse lookup. If there is a plurality of tables ManyTwoMany () or a ForeignKey () must be added releated_name 

  6, constantly changing field suitable for even the table

     Small field changes, becomes less suitable in a table, not even the table: choices to use

       It can be placed in a class and the teacher in the table, because they have the same properties, if the properties are all the same, can be placed on a table (recommended)

     Can be open-minded, teacher table is a table teacher, class teacher table is the table. This will be even operation table, even the performance table has consumed.

For example: article and article type

   Analysis: An article has a type, a type may correspond to multiple articles (articles and post types are so many relationship, associated field to put multi-party)

  A: even table design:

class News(models.Model):
    title = models.CharField(max_length=32)
    summary = models.CharField(max_length=255)
    news_type = models.ForeignKey(to="NewsType")
class NewsType(models.Model):
    type_title = models.CharField(max_length=32)

News:

  title the Summary news_type_id the above mentioned id
  1 t .... technology ... 2
  2 1 t .... technology ...
  3 ... 2 t .... Technology

NewsType:
 id title

  Picture 1
  2 kicked 1024
  3 piece

 

# 查看所有新闻
new_list = models.News.objects.all()
for row in new_list:
print(row.title,row.summary,row.news_type.title)

  II: Operation in a table: choices

class News2(models.Model):
    title = models.CharField(max_length=32)
    summary = models.CharField(max_length=255)
    news_type_chices = (
        (1, '图片'),
        (4, '挨踢1024'),
        (3, '段子'),
    )
    news_type = models.IntegerField(choices=news_type_chices)

# 查看所有新闻
new_list = News.objects.all()
for row in new_list:
print(row.title,row.summary, row.get_news_type_display() )

Example II: users and user types

  A: even table design

UserType class (models.Model): 
        "" " 
        user type table, the number of change frequently 
        " "" 
        title = models.CharField (MAX_LENGTH = 32) 

class the UserInfo (models.Model): 
        "" " 
        user table: Instructor and class 
        " "" 
        username = models.CharField (MAX_LENGTH = 32) 
        password = models.CharField (MAX_LENGTH = 64) 
        In Email = models.CharField (MAX_LENGTH = 32) 
        UT = models.ForeignKey (to = "UserType")

  Two: not even table design: choices

class UserInfo(models.Model):
#     """
#     用户表
#     """
    username = models.CharField(max_length=32)
    password = models.CharField(max_length=64)
    email = models.CharField(max_length=32,verbose_name="邮箱")
    user_type_choices = (
        (1, '班主任'),
        (2, '讲师'),
    )

    user_type_id = models.IntegerField(choices=user_type_choices)

Fourth, login

 May be provided a decorator

def auth(func):
    def inner(request,*args,**kwargs):
        is_login = request.session.get("is_login", None)
        if not is_login:
            return redirect("/login/")
        ret = func(*args,**kwargs)
        return ret
    return inner

 It should be noted:  

  1, action does not write path, submitted to the current default 

  2, to submit data to the background by post, get used to obtain data

  3, submit generally add value, some browsers may not recognize the

  4, the key general configuration files are in uppercase

 

 

A, model common operations

  1, 13 API query: all, filter, get, values, values_list, distinct, order_by, reverse, exclude (excluded), count, first, last, esits (to determine whether there is)

  Differences need to know all, values, values_list of

    all: QuerySet is a collection of print, a list of objects which put

    values: a dictionary form

    values_list: it is in the form of a tuple  

  Performance is the lowest of all

  2、only和defer

. datalist = models.Userinfo.objects.all () only ( "name", "email") # or get a QuerySet collection, just take the name and Email 
for in the DataList Item: 
    Print (item.id) 
    Print (Item .name) 
    Print (item.pwd) # long table has the fields, it would take the value of the additional request will Zaifayici 

datalist = models.Userinfo.objects.all (). defer ( "name", "email ") # stop, do not take the name and Email 
for in the DataList Item: 
    Print (item.id) 
    Print (item.pwd)

  Note: Use only if you pick only the inside of the field and other fields to take too inefficient, and as little as possible of the database connection

  3, routing system

  Reverse generate URL:

    There are two ways: {% url "a1"%}

          reverse("a1")

With reverse need to import from django.core.urlresolvers import reverse

/index/     func    name=a1
    {% url "a1"}
     reverse('a1')
                
/index/(\d+)/     func    name=a2
    {% url "a2" 11 %}
    reverse('a2',args=(11,))
                
/index/(?P<nid>\d+)/     func    name=a3
    {% url "a2" nid=11 %}
    reverse('a3',kwargs={'nid':11})

 

 4, Django's life cycle

               Web Server Gateway Interface (Python Web Server Gateway Interface, abbreviated as WSGI)

    1, first of all go wsgi module, which is a protocol, including wsgiref and uwsgi.

    2, then routing assignment ------- views view

    3, fetch data from the database to a rendering html -----------

    Note If you import js file is not rendered.

  5, HTTP protocol

    See the next blog post                                                                                                

Two, Form Components

A, Form Components Introduction

Form component can do several things:

  1, the user authentication data request

  2, an error message generated automatically    

  3, packing correct information submitted by the user

  4、如果其中有一个错误了,其他的正确这,保留上次输入的内容

  4、自动创建input标签并可以设置样式

二、Form组件的使用

  1、创建规则

class Foo(Form): #必须继承
    username = xxx
    password = xxx
    email = xxx
注意这里的字段必须和input的name字段一致

 

  2、数据和规则进行匹配

先导入view.py

from django.forms import Form
from django.forms import fields
from django.forms import widgets

 

from django.shortcuts import render,redirect
from app01 import models
# Create your views here.
from django.forms import Form
from django.forms import fields
from django.forms import widgets
# 1、创建规则
class TeacherForm(Form):  #必须继承Form
    # 创建字段,本质上是正则表达式
    username = fields.CharField(
        required=True,     #必填字段
        error_messages={"required":"用户名不能为空!!"},  #显示中文错误提示
        widget=widgets.TextInput(attrs={"placeholder":"用户名","class":"form-control"})  #自动生成input框
       )
    password = fields.CharField(required=True, error_messages={'required': '密码不能为空'},
                                widget=widgets.TextInput(attrs={'placeholder': '密码', 'class': 'form-control'}))  # 不能为空
    email = fields.EmailField(
        required=True,
        error_messages={"required":"邮箱不能为空!!","invalid":"无效的邮箱"},
        widget=widgets.EmailInput(attrs={"placeholder": "邮箱", "class": "form-control"})  # 自动生成input框
    ) #不能为空且邮箱格式要一致

# 2、使用规则:将数据和规则进行匹配
def teacherindex(request):
    teacher_obj = models.UserInfo.objects.all()
    # print(teacher_obj)
    return render(request,"teacherindex.html",{"teacher_obj":teacher_obj})
def add(request):
    if request.method=="GET":
        form = TeacherForm()  #只是让显示一个input框
        return render(request,"add.html",{"form":form })
    else:
        form = TeacherForm(data=request.POST)
        # print(form)  #<QuerySet [<UserInfo: UserInfo object>, <UserInfo: UserInfo object>, <UserInfo: UserInfo object>]>
        if form.is_valid():# 开始验证
            # print('执行成功',form.cleaned_data)          # 所有匹配成功,字典
            # {'username': 'asd', 'password': 'sdf', 'email': '[email protected]','ut_id':1}
            form.cleaned_data['ut_id'] = 1  #要分的清是班主任还是讲师
            models.UserInfo.objects.all().create(**form.cleaned_data)
            return redirect("/teacherindex/")
        else:
            # print("=====?",form.errors,type(form.errors))#返回失败的结果
            # print(form.errors["username"][0])   #拿到返回失败的结果,渲染到页面
            return render(request,"add.html",{"form":form})

 

html.py

{% block right %}
    <h1>添加老师信息</h1>
    <hr>
    <form method="post" novalidate>
        {% csrf_token %}
        <p>姓名:{{ form.username }}</p>{{ form.errors.username.0 }}
        <p>密码:{{ form.password }}</p>{{ form.errors.password.0 }}
        <p>邮箱:{{ form.email }}</p>{{ form.errors.email.0 }}
        <p><input type="submit" value="提交"></p>
    </form>
{% endblock %}

如果访问视图的是一个GET 请求,它将创建一个空的表单实例并将它放置到要渲染的模板的上下文中。这是我们在第一个访问该URL 时预期发生的情况。

如果表单的提交使用POST 请求,那么视图将再次创建一个表单实例并使用请求中的数据填充它:form = NameForm(request.POST)。这叫做”绑定数据至表单“(它现在是一个绑定的表单)。

我们调用表单的is_valid()方法;如果它不为True,我们将带着这个表单返回到模板。这时表单不再为空(未绑定),所以HTML 表单将用之前提交的数据填充,然后可以根据要求编辑并改正它。

如果is_valid()True,我们将能够在cleaned_data 属性中找到所有合法的表单数据。在发送HTTP 重定向给浏览器告诉它下一步的去向之前,我们可以用这个数据来更新数据库或者做其它处理。

注意: form = TeacherForm()  #没有参数,只是一个input框

    form = TeacherForm(data=request.POST) # 数据和规则放置一起 (添加的时候用)

    form = TeacherForm(initial={'username':obj.username,'password':obj.password,'email':obj.email})   # 显示input,并且将数据库中的默认值填写到input框中 (编辑的时候用)

 

Widgets

每个表单字段都有一个对应的Widget 类,它对应一个HTML 表单Widget,例如<input type="text">

在大部分情况下,字段都具有一个合理的默认Widget。例如,默认情况下,CharField 具有一个TextInput Widget,它在HTML 中生成一个<input type="text">

字段的数据

不管表单提交的是什么数据,一旦通过调用is_valid() 成功验证(is_valid() 返回True),验证后的表单数据将位于form.cleaned_data 字典中。这些数据已经为你转换好为Python 的类型。

注:此时,你依然可以从request.POST 中直接访问到未验证的数据,但是访问验证后的数据更好一些。

在上面的联系表单示例中,is_married将是一个布尔值。类似地,IntegerField 和FloatField 字段分别将值转换为Python 的int 和float

三、数据库表设计

设计表时注意的几点:

  1、 nid = models.AutoField(primary_key=True)        #如果不指定django会默认加上id的

    nid = models.BigAutoField(primary_key=True)   #但那些整型满足不了你的时候,就用BigAutoField

  2、对于类的注释一般加在类里面

  3、verbose_name=“标题”   字段的中文提示

  4、ForeignKey(to = "表名",tofield= "字段")    #这两个to可以不用写,但是关联的表名一定要写

  5、releated_name = "uuu"   反向查询。如果一个表中有多个ManyTwoMany()或者ForeignKey()必须加上releated_name 

  6、字段经常变动的适合连表

     字段变化小,不怎么变的适合在一个表中,不进行连表:就用choices

       吧班主任和老师可以放到一个表中、因为他们有相同的属性,如果属性全是一样的,可以放在一个表里(推荐)

     也可以分开放,老师表是老师表,班主任表是班主任表。这样就会进行连表操作,连表有性能消耗。

举例:文章和文章类型

   分析:一个文章有一个类型,一个类型可以对应多个文章(所以文章和文章类型是一对多的关系,关联字段要放在多的一方)

  一:连表设计:

class News(models.Model):
    title = models.CharField(max_length=32)
    summary = models.CharField(max_length=255)
    news_type = models.ForeignKey(to="NewsType")
class NewsType(models.Model):
    type_title = models.CharField(max_length=32)

News:

  id   title   summary  news_type_id
  1    t....    科技...     2
  2    t....    科技...     1
  3    t....    科技...     2

NewsType:
 id title

  1      图片
  2      挨踢1024
  3      段子

 

# 查看所有新闻
new_list = models.News.objects.all()
for row in new_list:
print(row.title,row.summary,row.news_type.title)

  二 :放在一个表中的操作:choices

class News2(models.Model):
    title = models.CharField(max_length=32)
    summary = models.CharField(max_length=255)
    news_type_chices = (
        (1, '图片'),
        (4, '挨踢1024'),
        (3, '段子'),
    )
    news_type = models.IntegerField(choices=news_type_chices)

# 查看所有新闻
new_list = News.objects.all()
for row in new_list:
print(row.title,row.summary, row.get_news_type_display() )

举例二:用户和用户类型

  一:连表设计

class UserType(models.Model):
        """
        用户类型表,个数经常变动
        """
        title = models.CharField(max_length=32)

class UserInfo(models.Model):
        """
        用户表:讲师和班主任
        """
        username = models.CharField(max_length=32)
        password = models.CharField(max_length=64)
        email = models.CharField(max_length=32)
        ut = models.ForeignKey(to="UserType")

  二:不连表设计:choices

class UserInfo(models.Model):
#     """
#     用户表
#     """
    username = models.CharField(max_length=32)
    password = models.CharField(max_length=64)
    email = models.CharField(max_length=32,verbose_name="邮箱")
    user_type_choices = (
        (1, '班主任'),
        (2, '讲师'),
    )

    user_type_id = models.IntegerField(choices=user_type_choices)

四、登录

 可设置一个装饰器

def auth(func):
    def inner(request,*args,**kwargs):
        is_login = request.session.get("is_login", None)
        if not is_login:
            return redirect("/login/")
        ret = func(*args,**kwargs)
        return ret
    return inner

 需要注意的:  

  1、action不写路径,默认提交到当前 

  2、向后台提交数据用post,获取数据用get

  3、submit一般加上value,有些浏览器可能会不识别

  4、一般配置文件的键都是大写的

 

Guess you like

Origin www.cnblogs.com/shangping/p/11565134.html