Django -- Forms

2018-03-23  本文已影响0人  liaozb1996

HTML Forms

<form action="/login" method="post">
    <div>
        <label for="username">Username: </label>
        <input type="text" id="username" name="username" />
    </div>
    <div>
        <label for="password">Password: </label>
        <input type="password" id="password" name="password" />
    </div>
    <input type="submit" value="Login" />
</form>

GET & POST

工作过程
适用情形

GET:用于搜索内容(搜索的URL可以保存到书签中,便于分享)
POST:适用于上传大文件、二进制文件(图片)、提交敏感信息(密码)

Django Forms

Django Forms

Forms Class

DateField and a FileField


# myapp/forms.py
from django import forms

class NameForm(forms.Form):
    your_name = forms.CharField(label='Your name', max_length=100)

Views

Form
# myapp/views.py
from django.shortcuts import render
from django.http import HttpResponseRedirect

from .forms import NameForm

def get_name(request):
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = NameForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            # process the data in form.cleaned_data as required
            # ...
            # redirect to a new URL:
            return HttpResponseRedirect('/thanks/')

    # if a GET (or any other method) we'll create a blank form
    else:
        form = NameForm()

    return render(request, 'name.html', {'form': form})

模板

# myapp/templates/myapp/get_name.html
<form action="/your-name/" method="post">
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="Submit" />
</form>
在模板中使用 Django Forms

以下变量都需要自动添加 <form>, {% csrf_token %}, <input type="submit" />

手动渲染 Django Forms
{% for field in form %}
    <div class="fieldWrapper">
        {{ field.errors }}
        {{ field.label_tag }} {{ field }}
        {% if field.help_text %}
        <p class="help">{{ field.help_text|safe }}</p>
        {% endif %}
    </div>
{% endfor %}

https://docs.djangoproject.com/en/2.0/topics/forms/

上一篇 下一篇

猜你喜欢

热点阅读