django表格_Django表格

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 POST
GET 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 forms

class 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 forms

class 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 MyForm

def 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 list

    form.as_ul :将字段显示为无序列表

  • form.as_p: Display fields as paragraph in separate line

    form.as_p :在单独的行form.as_p字段显示为段落

  • form.as_table: Display fields as table elements

    form.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 HttpResponse


def responseform(request):
 #if form is submitted
     if 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 admin

from responseapp import views as responseapp_views

urlpatterns = [
 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, include

urlpatterns = [
    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:

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

DjangoForms
Django表单

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

django表格

    原文作者:cunchi4221
    原文地址: https://blog.csdn.net/cunchi4221/article/details/107475620
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞