django表格

In this tutorial, we’ll be discussing Forms in our Django Project. In the previous tutorials, we had discussed Django Templates and Django Models. Today, we’ll see how Django Forms work and use them with Templates as well.

在本教程中,我们将在Django项目中讨论Forms。 在先前的教程中,我们讨论了Django模板和Django模型 。 今天,我们将看到Django Forms的工作方式以及将它们与Templates一起使用。

Django表格 (Django Forms)

Forms are an essential part of any web application that requires user input. Be it login forms, entering survey details, writing blog posts and comments(like we do on JournalDev!).

表单是任何需要用户输入的Web应用程序的重要组成部分。 无论是登录表单,输入调查详细信息,撰写博客文章和评论(就像我们在JournalDev上所做的一样!)。

Django Forms basically does three simple things:

Django Forms基本上做了三件事:

  • Read user input读取用户输入
  • Validate it.验证它。
  • Convert it into Python data types/objects将其转换为Python数据类型/对象
Forms vs Models形式与模型

Models map fields into types for the database. Forms map fields into Python types.

模型将字段映射为数据库的类型。 表单将字段映射到Python类型。

Let’s first discuss HTML forms since those are what would be finally displayed on the screen.

让我们首先讨论HTML表单,因为这些表单最终将显示在屏幕上。

HTML表格 (HTML Forms)

To create a form in HTML, enclose it in the <form> ... <form/> tags

要使用HTML创建表单,请将其包含在<form> ... <form/>标记中

Example:

例:

<form action="/goto_url/" method="post"><label for="name">Enter name: </label><input id="name" type="text" name="name_field" value="."><input type="submit" value="OK">
</form>

The form tag consists of an action which takes you to the mentioned url path when submit input type is clicked.

表单标签包含一个操作,单击submit输入类型后,该操作会将您带到提到的url路径。

In the method, we set it to GET or POST normally. The label acts as a hint for the id of the input tag it is linked to.

在该方法中,我们通常将其设置为GETPOST 。 该标签用作与其链接的输入标签的ID的提示。

Note: There are several other fields such as DateField, BooleanField and many more that can be used inside forms.

注意:还有其他几个字段,例如DateField,BooleanField和许多其他可在表单内部使用的字段。

GET vs POSTGET vs POST

GET is used to send the data in the form of a string which gets appended to the URL. This doesn’t change anything in the database.

GET用于以字符串形式发送数据,该字符串将附加到URL。 这不会更改数据库中的任何内容。

POST method is used to bundle up the data and send it to the server. It gets a response back. This is normally used to update the database.

POST方法用于捆绑数据并将其发送到服务器。 它得到了回应。 通常用于更新数据库。

GET is vulnerable to cross forgery site attacks since the data is available in the url itself.

GET容易受到跨伪造站点的攻击,因为数据本身在url中可用。

GET shouldn’t be used in cases such as password forms. A POST is more resistant to attacks.

在诸如密码形式的情况下,不应使用GET。 POST对攻击更具抵抗力。

Django Form类 (Django Form class)

Django makes our lives easier by handling the tiny details such as creating and re-creating the forms in the HTML page, validating the data entered and performing any actions set upon the forms.

Django通过处理微小的细节(例如在HTML页面中创建和重新创建表单,验证输入的数据并执行对表单设置的任何操作)来使我们的生活更轻松。

Just like HTML has the form tag, Django has a Form class.
The Form class is defined as:

就像HTML具有form标签一样,Django也具有Form类。
Form类定义为:

from django import formsclass FirstForm(forms.Form):name = forms.CharField(label='Your name', max_length=100)

We can render this class using Django Templates in the HTML page.
When the Submit button is clicked, the Form class would do the validation check using the is_valid() method on the instance of the above class.

我们可以使用HTML页面中的Django模板来呈现此类。
单击“提交”按钮后,Form类将使用上述类的实例上的is_valid()方法进行验证检查。

Once the validation is cleared the form data is available in the Form class’s cleaned_data attribute.

清除验证后,表单数据将在Form类的cleaned_data属性中提供。

Django Forms can be of two types:

Django表单可以有两种类型:

unbound – No data is present in the forms. They are empty.

unbound -表单中没有数据。 他们是空的。

bound – Data is filled in these types of forms.

bound –数据以这些类型的形式填充。

The above concepts may be difficult to digest. The best possible way is to learn by example.

以上概念可能难以理解。 最好的方法是通过榜样学习。

In the next section, we’ll create a basic Django Web Application with Forms implemented.

在下一节中,我们将创建一个实现了Forms的基本Django Web应用程序。

Our application would take responses and show it on the next screen.

我们的应用程序将获取响应并将其显示在下一个屏幕上。

快速设置 (Quick Setup)

Let’s create a new Django Project and start a new app inside it named responseapp.

让我们创建一个新的Django Project并在其中启动一个名为responseapp的新应用。

Following is the ordered list of commands we’d entered in the terminal. To know the details visit our First Django Tutorial.

以下是我们在终端中输入的命令的有序列表。 要了解详细信息,请访问我们的第一本Django教程 。

mkdir DjangoForms
cd DjangoForms
virtualenv -p /usr/local/bin/python3 env
source env/bin/activate
pip3 install django
django-admin startproject DjangoFormsBasics
cd DjangoFormsBasics
python3 manage.py runserver
django-admin startapp responseapp
cd responseapp
mkdir templates
cd templates
touch responseform.html
touch thankyou.html

Inside the responseapp, we’ve created a templates folder which will hold the html files.
Inside the templates folder, add two html files for the two paged web application we’ll build next.

responseapp ,我们创建了一个模板文件夹,其中包含html文件。
在模板文件夹内,为接下来将要构建的两个页面化的Web应用程序添加两个html文件。

Create two new python files: forms.py and urls.py:

创建两个新的python文件: forms.pyurls.py

cd ..
touch forms.py
touch urls.py

项目结构 (Project Structure)

Don’t forget to add the Django app in the settings.py file:

不要忘记将Django应用添加到settings.py文件中:

码 (Code)

Add the following code in your forms.py file:

在Forms.py文件中添加以下代码:

from django import formsclass MyForm(forms.Form):name = forms.CharField(label='Enter your name', max_length=100)email = forms.EmailField(label='Enter your email', max_length=100)feedback = forms.CharField(widget=forms.Textarea(attrs={'width':"100%", 'cols' : "80", 'rows': "20", }))

We’ve added three fields: CharFields, EmailFields, and a CharField with TextArea width and height specified.

我们添加了三个字段:CharFields,EmailFields和一个指定了TextArea宽度和高度的CharField。

The code for views.py file is given below:

views.py文件的代码如下:

from django.shortcuts import render
from responseapp.forms import MyFormdef responseform(request):form = MyForm()return render(request, 'responseform.html', {'form':form});

You must use csrf(Cross Site Request Forgeries) for Django Forms which have the method POST.

对于具有POST方法的Django表单,必须使用csrf(跨站点请求伪造)。

This renders the Django Form and uses the template language by passing the complete form instance to the HTML.

这将通过将完整的表单实例传递给HTML来呈现Django表单并使用模板语言。

The code for our initial responseform.html class is given below:

下面给出了我们最初的responseform.html类的代码:

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Django Forms Tutorial</title>
</head>
<body>
<h2>Django Forms Tutorial</h2><form>{% csrf_token %}{{form}}
<input type="submit" value="Submit" />
</form>
</body>
</html>

Run the following commands on your terminal on the inner DjangoFormBasics folder:

在内部DjangoFormBasics文件夹的终端上运行以下命令:

python3 manage.py migrate
python3 manage.py runserver

Note: You must specify the url patterns. Check out the urls.py files defined later in this tutorial.

注意:您必须指定url模式。 查看本教程后面定义的urls.py文件。

Following is the output of the application in action.

以下是实际应用程序的输出。

WHOOPS! It looks ugly horizontally. We can arrange the Forms in the following orders:

哇! 水平看起来很难看。 我们可以按照以下顺序安排表格:

  • form.as_ul: Display fields as unordered listform.as_ul :将字段显示为无序列表
  • form.as_p: Display fields as paragraph in separate lineform.as_p :在单独的行form.as_p字段显示为段落
  • form.as_table: Display fields as table elementsform.as_table :将字段显示为表元素
<table>{{form.as_table}}</table>

For form_as_ul you must enclose it in the ul tag.

对于form_as_ul您必须将其包含在ul标记中。

Also, the submit button doesn’t work, let’s add another html page which will catch the form responses and display there.

另外,“提交”按钮不起作用,让我们添加另一个html页面,该页面将捕获表单响应并显示在那里。

The updated code for the responseform.html is given below:

下面给出了responseform.html的更新代码:

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Django Forms Tutorial</title>
</head>
<body>
<h2>Django Forms Tutorial</h2><form action="/thankyou/" method="post">{% csrf_token %}<table>{{form.as_table}}</table>
<input type="submit" value="Submit" />
</form>
</body>
</html>

In the above code, we’ve added a method and action. When submit is clicked the user would be taken to the /thankyou/ page with the form data POSTed.

在上面的代码中,我们添加了一个方法和操作。 单击提交时,将使用表单数据POST ed将用户带到/ thankyou /页面。

The code for the views.py file is given below:

views.py文件的代码如下:

from django.shortcuts import render
from responseapp.forms import MyForm
from django.template import loader
from django.http import HttpResponsedef responseform(request):#if form is submittedif request.method == 'POST':myForm = MyForm(request.POST)if myForm.is_valid():name = myForm.cleaned_data['name']email = myForm.cleaned_data['email']feedback = myForm.cleaned_data['feedback']context = {'name': name,'email': email,'feedback': feedback}template = loader.get_template('thankyou.html')return HttpResponse(template.render(context, request))else:form = MyForm()return render(request, 'responseform.html', {'form':form});

Initially, the else statement will execute and create an empty form.

最初, else语句将执行并创建一个空表格。

Later when submit is clicked, if block is executed and if the form is validated we load the thankyou.html page using Loaders with Django Templates.

稍后,当单击Submit时, if执行了block并验证了表单,我们将使用带有Django模板的Loaders加载thankyou.html页面。

The form data is passed to the thankyou.html class as:

表单数据通过以下方式传递给thankyou.html类:

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Thank You</title>
</head>
<body>
<h2>Response Entered by you:</h2>
<form method="post"><ul><li>Name: <strong>{{ name }}</strong></li><li>Email: <strong>{{ email }}</strong></li><li>Feedback: <strong>{{ feedback }}</strong></li></ul>
</form>
</body>
</html>

The code for the urls.py created inside the responseapp folder is:

responseapp文件夹中创建的urls.py的代码是:

from django.urls import path
from django.contrib import adminfrom responseapp import views as responseapp_viewsurlpatterns = [path('response/', responseapp_views.responseform),path('thankyou/', responseapp_views.responseform),path('', admin.site.urls),
]

responseapp_views is same as responseapp.views. It calls the views.py file from where the application starts.

responseapp_viewsresponseapp.views相同。 它从应用程序启动的地方调用views.py文件。

The below urls.py file must be included in the outer urls.py file defined in the DjangoForm project:

以下urls.py文件必须包含在DjangoForm项目中定义的外部urls.py文件中:

from django.contrib import admin
from django.urls import path, includeurlpatterns = [path('admin/', admin.site.urls),path('', include('responseapp.urls'))
]

The output of the application in action is:

实际应用程序的输出为:

This brings an end to this tutorial. You can download the project from below:

本教程到此结束。 您可以从下面下载项目:

DjangoFormsDjango表单

翻译自: https://www.journaldev.com/22424/django-forms

django表格

django表格_Django表格相关推荐

  1. wordpress自适应表格_给WordPress添加自适应表格 让表格自适应屏幕

    wordpress自带的表格不能自适应屏幕宽带,每次新建了表格,电脑上显示正常的,结果换到手机上就超出屏幕宽度了,很麻烦,更重要的是很不美观,本次我就问为大家带来一个添加自适应表格的教程. 案列分析 ...

  2. python处理表格数据-python读取word 中指定位置的表格及表格数据

    1.Word文档如下: 2.代码 # -*- coding: UTF-8 -*- from docx import Document def readSpecTable(filename, specT ...

  3. HTML之表格篇——表格的嵌套

    表格的嵌套一方面是为使页面(贴子)的外观更为漂亮,利用表格嵌套来编辑出复杂而精美的效果,另一方面是出于布局需要,用一些嵌套方式的表格来做精确的编排,或者二者兼而有之.熟练地掌握表格的嵌套技巧并不是很困 ...

  4. Js操作表格-对表格单元格的添加删除修改

    动态表格 动态表格彻底研究 对表格单元格的添加删除修改并对其进行移动以及拷贝等操作,是目前应用开发中常用的技术 1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 5 55 5 6 6 6 ...

  5. 切片器可以设置日期格式?_Excel智能表格——套用表格格式,“一键变身”

    大家好,我是执着于研究Office小技巧的Angie-- Excel表格堪称职场达人必做项,为了追求美观可视化,每次都要手动操作对表格边框.单元格填充.字体大小进行设置,重点是每次自定义设置完,不仅没 ...

  6. JavaScript学习笔记07【6个经典案例——电灯开关、轮播图、自动跳转首页、动态表格、表格全选、表单验证】

    Java后端 学习路线 笔记汇总表[黑马程序员] w3school 在线教程:https://www.w3school.com.cn JavaScript学习笔记01[基础--简介.基础语法.运算符. ...

  7. html 表格套表格_HTML表格

    html 表格套表格 A table is a set of rows and columns, which could be created on a webpage in HTML, by < ...

  8. python读取word指定内容_python读取word 中指定位置的表格及表格数据

    1.Word文档如下: 2.代码 # -*- coding: UTF-8 -*- from docx import Document def readSpecTable(filename, specT ...

  9. html表格上只有竖边框,html中画表格让表格只有横边框没有竖边框.doc

    test { } table.tab td {height:30px; border-bottom:2px solid #6AB2E7; border-left:0px ;border-right:0 ...

最新文章

  1. VS快速注释多行 以及 取消
  2. java -d32_java11教程--JDK 10删除和不推荐的功能和选项-2
  3. 如何导入nod32企业版的授权文件.lic,并制作镜像服务器?
  4. [转]Javascript的IE和Firefox(火狐)兼容性
  5. lt;xliff:ggt;标签
  6. 用java程序将GBK字符转成UTF-8编码格式(转)
  7. js对象序列化为json字符串
  8. java开源播放器_JavaFX/Java8开发的开源音乐播放器
  9. python函数库 阶跃 信号函数 调用_有没有大神知道 step2 阶跃响应函数的 里面的T的怎么定义...
  10. npm时需要python
  11. Python中文本文件的读取(包含指针移动)
  12. Don't Make Me Think
  13. 【原】Web Polygraph 安装
  14. java 字符串去重排序
  15. u盘在计算机上不显示错误,u盘为什么在电脑上不显示
  16. 色彩空间和色彩域互相转换及转化目的
  17. dnf时装补丁教程_【时装补丁制作】消灭伸手党!最详细的图文教程~
  18. 关于php网络爬虫phpspider
  19. oracle的档案软件,思源档案管理系统(WEB版)
  20. 双十一,咪蒙广告位为何供不应求?

热门文章

  1. 最大似然估计、MAP、贝叶斯估计
  2. NSString NSURL
  3. 木其工作室(专业程序代写服务)[转]学写块设备驱动(三)----踢开IO调度器,自己处理bio(下)...
  4. python - Flask 基础(1)
  5. jQueryEasyUI应用 – datagrid之CRUD应用
  6. 面向对象 之重写重载
  7. Android ClassLoader笔记(二)
  8. thinkphp的find()方法获取结果
  9. C语言八进制和十六进制数
  10. WCF入门(八)---WCF服务绑定