《Django By Example》

Django表单

2019-07-31  本文已影响0人  Recalcitrant

Django表单

一、构建表单

1.直接构建表单

<form>
  <div class="form-group">
    <label for="username">用户名</label>
    <input type="text" class="form-control" name="username" id="username" placeholder="用户名">
  </div>
  <div class="form-group">
    <label for="Password">密码</label>
    <input type="password" class="form-control" name="pwd" id="Password" placeholder="密码">
  </div>
  <div class="form-group">
    <label for="confirm_pwd">确认密码</label>
    <input type="password" class="form-control" name="confirm_pwd" id="confirm_pwd" placeholder="确认密码">
  </div>
  <div class="form-group">
    <label for="email">邮箱</label>
    <input type="email" class="form-control" id="email" name="email" placeholder="电子邮箱">
  </div>
  <button type="submit" class="btn btn-primary pull-right">注册</button>
</form>

2.Django构建表单

(1)Form 类

forms.py

from django import forms
class RegisterForm(forms.Form):
    username = forms.CharField(label="用户名", required=True, min_length=4, max_length=100, error_messages={'required': "用户名不能为空!", 'min_length': "用户名最小为4个字符"})
    password = forms.CharField(widget=forms.PasswordInput, label="密码", required=True, min_length=6, max_length=200, error_messages={'required': "密码不能为空!", 'min_length': "用户名最小为6个字符"})
    email = forms.EmailField(label="邮箱", required=True, error_messages={'required': "邮箱不能为空!"})
    valid_code = forms.CharField(label="验证码", required=True, error_messages={'required': "验证码不能为空!"})

views.py

from django.shortcuts import render
from django.http import HttpResponse
from .forms import RegisterForm
from .models import User
def register(request):
    if request.method == 'GET':
        form = RegisterForm()
        return render(request, 'register.html', {'form': form})
    elif request.method == 'POST':
        form = RegisterForm(request.POST)
        if form.is_valid():
            user = User.objects.create(user_name=request.POST['username'], password=request.POST['password'], email=request.POST['email'])
            user.save()
            return HttpResponse("注册成功!")
        else:
            return render(request, 'register.html', {'form': form})
    else:
        pass

模板

<form action="{% url 'user:register' %}" method="POST">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit" class="btn btn-primary pull-right">注册</button>
</form>

(2)ModelForm类

forms.py

from django import forms
from .models import User
class RegisterForm(forms.ModelForm):
    user_name = forms.CharField(label="用户名", required=True, min_length=4, max_length=100,
                               error_messages={'required': "用户名不能为空!", 'min_length': "用户名最小为4个字符"})
    password = forms.CharField(widget=forms.PasswordInput, label="密码", required=True, min_length=6, max_length=200,
                               error_messages={'required': "密码不能为空!", 'min_length': "密码最小为6个字符"})
    re_password = forms.CharField(widget=forms.PasswordInput, label="确认密码", required=True, min_length=6, max_length=200,
                               error_messages={'required': "确认密码不能为空!", 'min_length': "确认密码最小为6个字符"})
    email = forms.EmailField(label="邮箱", required=True, error_messages={'required': "邮箱不能为空!"})
    valid_code = forms.CharField(label="验证码", required=True, error_messages={'required': "验证码不能为空!"})

    class Meta:
        model = User
        fields = ['user_name', 'password', 're_password', 'email', 'valid_code']

views.py

from django.shortcuts import render
from django.http import HttpResponse
from .forms import RegisterForm
def register(request):
    if request.method == 'GET':
        form = RegisterForm()
        return render(request, 'register.html', {'form': form})
    elif request.method == 'POST':
        form = RegisterForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponse("注册成功!")
        else:
            return render(request, 'register.html', {'form': form})
    else:
        pass

模板

<form id="register_form" action="{% url 'user:register' %}" method="POST">
    {% csrf_token %}
    {% for field in form %}
        <div class="form-group">
            {{ field.label_tag }}
            {% render_field field class='form-control' %}
        </div>
    {% endfor %}
    <button type="submit" class="btn btn-primary pull-right">注册</button>
</form>

二、表单模板

1.表单渲染选项

以上节Form类示例为例:

<form action="{% url 'user:register' %}" method="POST">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit" class="btn btn-primary pull-right">注册</button>
</form>

(1){{ form.as_table }}

将表单字段渲染为<tr>标签。


(2){{ form.as_p }}

将表单字段渲染为<p>标签。


(3){{ form.as_ul }}

将表单字段渲染为<li>标签。


2.手动渲染字段

{{ form.non_field_errors }}
<div class="fieldWrapper">
    {{ form.subject.errors }}
    <label for="{{ form.subject.id_for_label }}">Email subject:</label>
    {{ form.subject }}
</div>
<div class="fieldWrapper">
    {{ form.message.errors }}
    <label for="{{ form.message.id_for_label }}">Your message:</label>
    {{ form.message }}
</div>
<div class="fieldWrapper">
    {{ form.sender.errors }}
    <label for="{{ form.sender.id_for_label }}">Your email address:</label>
    {{ form.sender }}
</div>
<div class="fieldWrapper">
    {{ form.cc_myself.errors }}
    <label for="{{ form.cc_myself.id_for_label }}">CC yourself?</label>
    {{ form.cc_myself }}
</div>

3.遍历表单字段

以上节ModelForm类示例为例:

<form id="register_form" action="{% url 'user:register' %}" method="POST">
    {% csrf_token %}
    {% for field in form %}
        <div class="form-group">
            {{ field.label_tag }}
            {% render_field field class='form-control' %}
        </div>
    {% endfor %}
    <button type="submit" class="btn btn-primary pull-right">注册</button>
</form>

遍历模板

(1){{ field.label }}

字段的label,比如 Email address。

(2){{ field.label_tag }}

该字段的label封装在相应的HTML <label> 标签中。它包含表单的 label_suffix 。

(3){{ field.id_for_label }}

用于该字段的 ID(像上面的例子中的 id_email )。如果您要手动构建label,您可能要用这个来替换 label_tag 。例如,如果你有一些内嵌的JavaScript并且想要避免硬编码字段的ID,这也很有用。

(4){{ field.value }}

字段的值。

(5){{ field.html_name }}

字段名称:用于其输入元素的name属性中。如果设置了表单前缀,它也会被加进去。

(6){{ field.help_text }}

与该字段关联的帮助文本。

(7){{ field.errors }}

输出一个包含对应该字段所有验证错误信息的 <ul class="errorlist"> 。您可以用 {% for error in field.errors %} 循环来自定义错误信息的显示。这种情况下,循环中的每个对象只是一个包含错误信息的简单字符串。

(8){{ field.is_hidden }}

如果是隐藏字段,这个属性为 True ,否则为 False 。

(9){{ field.field }}

表单类中的 Field 实例由 BoundField 封装。您可以用它来访问 Field 的属性,比如 {{ char_field.field.max_length }} 。

上一篇下一篇

猜你喜欢

热点阅读