美文网首页
Django08有趣的表单

Django08有趣的表单

作者: 忘川止 | 来源:发表于2017-07-04 19:41 被阅读0次

到目前为止我们仅仅是通过视图和模板来表现数据.在本章,我们将会学习如何通过web表单来获取数据.Django包含一些表单处理功能,它使在web上收集用户信息变得简单.通过Django’s documentation on forms我们知道表单处理功能包含以下:

  1. 显示一个HTML表单自动生成的窗体部件(比如一个文本字段或者日期选择器).
  2. 用一系列规则检查提交数据.
  3. 验证错误的情况下将会重新显示表单.
  4. 把提交的表单数据转化成相关的Python数据类型.

使用Django表单功能最大的好处就是它可以节省你的大量时间和HTML方面的麻烦.这部分我们将会注重如何通过表单让用户增加目录和页面.

基本流程

流程

页面和目录表单

首先,我们需要在rango应用目录里黄建叫做forms.py文件.尽管这步我们并不需要,我们可以把表单放在models.py里,但是这将会使我们的代码简单易懂.

1 创建ModelForm类

在rango的forms.py
模块里我们将会创建一些继承自ModelForm
的类.实际上,ModelForm是一个帮助函数,它允许你在一个已经存在的模型里创建Django表单.因为我们定义了两个模型(Category和Page),我们将会分别为它们创建ModelForms.
在rango/forms.py
添加下面代码:

from django import forms
from rango.models import Page, Category

class CategoryForm(forms.ModelForm):
    name = forms.CharField(max_length=128, help_text="Please enter the category name.")
    views = forms.IntegerField(widget=forms.HiddenInput(), initial=0)
    likes = forms.IntegerField(widget=forms.HiddenInput(), initial=0)
    slug = forms.CharField(widget=forms.HiddenInput(), required=False)

    # An inline class to provide additional information on the form.
    class Meta:
        # Provide an association between the ModelForm and a model
        model = Category
        fields = ('name',)


class PageForm(forms.ModelForm):
    title = forms.CharField(max_length=128, help_text="Please enter the title of the page.")
    url = forms.URLField(max_length=200, help_text="Please enter the URL of the page.")
    views = forms.IntegerField(widget=forms.HiddenInput(), initial=0)

    class Meta:
        # Provide an association between the ModelForm and a model
        model = Page

        # What fields do we want to include in our form?
        # This way we don't need every field in the model present.
        # Some fields may allow NULL values, so we may not want to include them...
        # Here, we are hiding the foreign key.
        # we can either exclude the category field from the form,
        exclude = ('category',)
        #or specify the fields to include (i.e. not include the category field)
        #fields = ('title', 'url', 'views')
Paste_Image.png

2 创建和增加目录视图

创建CategoryForm类以后,我们需要创建一个新的视图来展示表单并传递数据.在rango/views.py中增加如下代码.

from rango.forms import CategoryForm

def add_category(request):
    # A HTTP POST?
    if request.method == 'POST':
        form = CategoryForm(request.POST)

        # Have we been provided with a valid form?
        if form.is_valid():
            # Save the new category to the database.
            form.save(commit=True)

            # Now call the index() view.
            # The user will be shown the homepage.
            return index(request)
        else:
            # The supplied form contained errors - just print them to the terminal.
            print form.errors
    else:
        # If the request was not a POST, display the form to enter details.
        form = CategoryForm()

    # Bad form (or form details), no form supplied...
    # Render the form with error messages (if any).
    return render(request, 'rango/add_category.html', {'form': form})

新的add_category()视图增加几个表单的关键功能.首先,检查HTTP请求方法是GET还是POST.我们根据不同的方法来进行处理 - 例如展示一个表单(如果是GET)或者处理表单数据(如果是POST) -所有表单都是相同URL.add_category()视图处理以下三种不同情况:

为添加目录提供一个新的空白表单;
保存用户提交的数据给模型,并转向到Rango主页;
如果发生错误,在表单里展示错误信息.

3 创建增加目录模板

让我们创建templates/rango/add_category.html文件.

<!DOCTYPE html>
<html>
    <head>
        <title>Rango</title>
    </head>

    <body>
        <h1>Add a Category</h1>

        <form id="category_form" method="post" action="/rango/add_category/">

            {% csrf_token %}
            {% for hidden in form.hidden_fields %}
                {{ hidden }}
            {% endfor %}

            {% for field in form.visible_fields %}
                {{ field.errors }}
                {{ field.help_text }}
                {{ field }}
            {% endfor %}

            <input type="submit" name="submit" value="Create Category" />
        </form>
    </body>

</html>

4 映射增加目录视图

现在我们需要映射add_category()视图.在模板里我们使用/rango/add_category/URL来提交.所以我们需要修改rango/urls.py的urlpattterns.

urlpatterns = patterns('',
    url(r'^$', views.index, name='index'),
    url(r'^about/$', views.about, name='about'),
    url(r'^add_category/$', views.add_category, name='add_category'), # NEW MAPPING!
    url(r'^category/(?P<category_name_slug>[\w\-]+)/$', views.category, name='category'),)

5 修改主页内容

作为最后一步,让我们在首页里加入链接.修改rango/index.html文件,在</body>前添加如下代码.

<a href="/rango/add_category/">Add a New Category</a><br />

6. demo

练习

add_page.htnl

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Rango - Add Page</title>
</head>
<body>
{% if category %}
    <h1>Add a Page to {{ category.name }}</h1>
    <form id="page_form" method="post" action="/rango/category/{{ category.slug }}/add_page/">
        {% csrf_token %}
        {% for hidden in form.hidden_fields %}
            {{ hidden }}
        {% endfor %}
        {% for field in form.visible_fields %}
            {{ field.errors }}
            {{ field.help_text }}
            {{ field }}
        {% endfor %}
        <input type="submit" name="submit" value="Add Page">
    </form>
{% else %}
    The specified category does not exist!
{% endif %}
</body>
</html>

效果图


.

相关文章

  • Django08有趣的表单

    到目前为止我们仅仅是通过视图和模板来表现数据.在本章,我们将会学习如何通过web表单来获取数据.Django包含一...

  • 2017.9.1

    今天学习了比较有趣的表单 表单 input type text 文本框 password 密码框 sub...

  • Angular 14 新的 inject 函数介绍

    Angular 14 提供了一些非常有趣的特性:类型化表单(typed forms)、独立组件(standalon...

  • bootstrap之form表单

    表单布局 垂直表单(默认) 内联表单 水平表单 垂直表单或基本表单(display:block;) 创建基本表单的...

  • bootstrap表单

    表单布局 垂直表单(默认) 内联表单 水平表单 垂直表单或基本表单 基本的表单结构是 Bootstrap 自带的,...

  • 【读书笔记+思考】移动设备表单设计

    在移动界面中,常见的表单模式有:登录表单;注册表单;核对表单;计算表单;搜索表单;多步骤表单;长表单等 登录表单:...

  • bootstrap表单

    垂直表单(默认) 内联表单 水平表单 垂直表单 也称基本表单基本的表单结构是 bootstrap 自带的创建基本表...

  • 2019-04-09 表单(5)

    表单布局Bootstrap 提供了下列类型的表单布局: 垂直表单(默认) 内联表单 水平表单 1.垂直或基本表单 ...

  • 前端视频-day3(1)

    表单 表单不是表格,表单的核心是数据。 表单标签的构成和形式: 表单项 下面是我写的一个简单的注册表单 注意:表单...

  • 九、疯狂的表单

    疯狂的表单 新增表单控件 新增表单属性 表单验证反馈 关闭验证

网友评论

      本文标题:Django08有趣的表单

      本文链接:https://www.haomeiwen.com/subject/oguxhxtx.html