我正在学习Django并且遇到一些形式问题。我尝试创建一个简单的表单,在其中键入名称并在另一页上显示。但是is_valid()总是返回false。请帮我查一下我的错误
forms.py
from django import forms
class OrderForm(forms.Form):
user=forms.CharField(max_length=100)
views.py
def order(request):
return render(request, 'myapp/order.html', {})
def contact(request):
username='not logged'
if request.method == 'POST' :
form=OrderForm(request.POST)
if form.is_valid():
username=form.cleaned_data['username']
else:
username='not worked'
else:
form=OrderForm()
return render(request, 'myapp/contacts.html', {'username':username})
order.html
<form name = "form" action = "{% url 'contact' %}" method = "POST" >
{% csrf_token %}
<input type="text" name="username" placeholder="Name">
<button type="submit">Login</button>
</form>
contacts.html
You are : <strong>{{ username }}</strong>
答案 0 :(得分:3)
您的表单控件在HTML中的名称为username
,而您的表单在Django中的名称为user
。因此,表单字段中没有设置任何内容。
通常,您将表单放入上下文中,然后将其呈现为{{ form }}
之类,或呈现每个字段,而不是构建自己的表单控件。文档显示了如何:https://docs.djangoproject.com/en/1.10/topics/forms/#working-with-form-templates
答案 1 :(得分:0)
from forms import OrderForm
def order(request):
form = OrderForm()
return render(request, 'myapp/order.html', {"form" : form})
<form name = "form" action = "{% url 'contact' %}" method = "POST" >
{% csrf_token %}
{{form.as_p}}
<button type="submit">Login</button>
</form>
在呈现模板时 {{form.as_p}} 看起来像
<p><label for="id_username">Username:</label>
<input id="id_username" type="text" name="username" maxlength="100" required /></p>