Django18初体验


1146 浏览 5 years, 11 months

11.15 视图中定制表单 (非modelForm)

版权声明: 转载请注明出处 http://www.codingsoho.com/

在forms.py中添加contactForm

class ContactForm(forms.Form):
    full_name = forms.CharField(required=False)
    email = forms.EmailField()
    message = forms.CharField()

在views.py中添加Contact函数

def contact(request):
    form = ContactForm(request.POST or None)
    if form.is_valid():
        # for key, value in form.cleaned_data.iteritems():
        #   print key, value
        #   #print form.cleaned_data.get(key)
    context = {
        "form": form,
    }
    return render(request, "forms.html", context)

在urls.py中添加入口

urlpatterns = patterns('',
    url(r'^$', 'newsletter.views.home', name='home'),
    url(r'^contact/$', 'newsletter.views.contact', name='contact'),
)

创建forms.html文件

<form method='POST' action=''>{% csrf_token %}
{{ form.as_p }}

<input type='submit' value='Submit' />
</form>