假设你想在你的网站上创建一个简单的表单,以获得用户的名字。你需要类似这样的模板:

<form action="/your-name/" method="post">
<label for="your_name">Your name: </label>
<input id="your_name" type="text" name="your_name" value="` current_name `">
<input type="submit" value="OK"></form>

我们已经计划好了我们的 HTML 表单应该呈现的样子。在Django 中,我们的起始点是这里:

forms.py

from django import formsclass NameForm(forms.Form):
your_name = forms.CharField(label='Your name', max_length=100)

views.py

from django.shortcuts import render
from django.http import HttpResponseRedirect
from .forms import NameForm

def get_name(request):
if request.method == "POST":
form = NameForm(request.POST)
if form.is_valid():
return HttpResponseRedirect("/thanks/')

else:
form = NameForm()

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

添加模块name.html文件

name.html

<form action='/your-name/' method="POST">
{% csrf_token %}
` form `
<input type="submit" value="Submit"/>
</form>