Django形式不可见

时间:2015-06-28 10:43:14

标签: python django django-forms

只有按钮可见且标题可见,无法看到CharField

forms.py

from django import forms

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

views.py

from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from compare.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})

的index.htm

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

3 个答案:

答案 0 :(得分:3)

你应该给if if form.is_valid()部分,另外一个标签。

from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from compare.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})

答案 1 :(得分:1)

我还不允许在您的问题中添加评论,但您确实注意到,当您为提供代码时,您的视图会呈现 name.html index.htm的

基本上您的代码似乎有效,而且可以进一步优化:

<input type="hidden" name="check" value="false">
<input type="checkbox" name="check" value="true">

答案 2 :(得分:0)

 <form action="/your-name/" method="post">
            {% csrf_token %}
            {{ form.as_p }}
        <input type="submit" value="Submit" />
        </form>

这可以通过添加编辑{{form.as_p}}

来实现