📜  FloatField – Django 表单

📅  最后修改于: 2022-05-13 01:55:08.117000             🧑  作者: Mango

FloatField – Django 表单

Django Forms 中的 FloatField 是一个整数字段,用于从用户那里输入浮点数。此输入的默认小部件是 NumberInput。它标准化为: Python float 。它验证给定的值是一个浮点数。如果提供了min_value max_value它将使用 MaxValueValidator 和 MinValueValidator。允许使用前导和尾随空格,如 Python 的 float()函数。

FloatField 具有以下可选参数:

  • max_lengthmin_length :- 如果提供,这些参数确保数据最多或至少是给定的长度。

句法

field_name = forms.FloatField(**options)

Django表单FloatField解释

使用示例的 FloatField 插图。考虑一个名为geeks的项目,它有一个名为geeksforgeeks的应用程序。

geeks app的forms.py文件中输入以下代码。

from django import forms
  
# creating a form 
class GeeksForm(forms.Form):
    geeks_field = forms.FloatField( )

将极客应用添加到INSTALLED_APPS

# Application definition
  
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'geeks',
]

现在要将这个表单渲染到一个视图中,我们需要一个视图和一个映射到该 URL 的 URL。我们先在geeks app的views.py中创建一个视图,

from django.shortcuts import render
from .forms import GeeksForm
  
# Create your views here.
def home_view(request):
    context = {}
    context['form'] = GeeksForm()
    return render( request, "home.html", context)

在这里,我们从 forms.py 导入该特定表单并在视图中创建它的对象,以便可以在模板中呈现它。
现在,要启动一个 Django 表单,您需要创建 home.html,在其中可以根据需要设计内容。让我们在home.html中创建一个表单。

    {% csrf_token %}     {{ form.as_p }}     

最后,在 urls.py 中映射到该视图的 URL

from django.urls import path
  
# importing views from views..py
from .views import home_view
  
urlpatterns = [
    path('', home_view ),
]

让我们运行服务器并检查实际发生了什么,运行

Python manage.py runserver

django-forms-floatfield

因此,通过将“_”替换为“”来创建geeks_field FloatField 。这是一个输入用户浮点数的字段。

如何使用 FloatField ?

FloatField 用于在数据库中输入浮点数。可以输入Marks、百分比等日期。到目前为止,我们已经讨论了如何实现FloatField,但是如何在视图中使用它来执行逻辑部分。为了执行一些逻辑,我们需要将输入到字段中的值放入Python字符串实例中。
在views.py中,

from django.shortcuts import render
from .forms import GeeksForm
  
# Create your views here.
def home_view(request):
    context = {}
    if request.method == "POST":
        form = GeeksForm(request.POST)
        if form.is_valid():
            temp = form.cleaned_data.get("geeks_field")
            print(type(temp))
    else:
        form = GeeksForm()
    context['form'] = form
    return render(request, "home.html", context)

让我们在 FloatField 中尝试除数字之外的其他内容。
django表单错误floatfield

所以它只接受一个有效的浮点数输入,否则会看到验证错误。现在让我们尝试在该字段中输入一个有效的浮点数。
django-forms-floatfield-1
可以使用相应的请求字典获取浮点数据。如果方法是 GET,则数据将在request.GET中可用,如果是 post,则相应的request.POST 。在上面的示例中,我们有 temp 中的值,我们可以将其用于任何目的。让我们检查一下临时变量是什么类型的?

django-forms-floatfield-2

核心字段参数

核心字段参数是赋予每个字段以应用某些约束或将特定特征赋予特定字段的参数。例如,向 FloatField 添加参数required = False将使用户可以将其留空。每个 Field 类构造函数至少采用这些参数。一些 Field 类采用额外的、特定于字段的参数,但应始终接受以下参数:

Field OptionsDescription
requiredBy default, each Field class assumes the value is required, so to make it not required you need to set required=False
labelThe label argument lets you specify the “human-friendly” label for this field. This is used when the Field is displayed in a Form.
label_suffixThe label_suffix argument lets you override the form’s label_suffix on a per-field basis.
widgetThe widget argument lets you specify a Widget class to use when rendering this Field. See Widgets for more information.
help_textThe help_text argument lets you specify descriptive text for this Field. If you provide help_text, it will be displayed next to the Field when the Field is rendered by one of the convenience Form methods.
error_messagesThe error_messages argument lets you override the default messages that the field will raise. Pass in a dictionary with keys matching the error messages you want to override.
validatorsThe validators argument lets you provide a list of validation functions for this field.
localizeThe localize argument enables the localization of form data input, as well as the rendered output.
disabled.The disabled boolean argument, when set to True, disables a form field using the disabled HTML attribute so that it won’t be editable by users.