1、项目结构:
$ tree form_pj/ form_pj/ ├── blog │ ├── admin.py │ ├── admin.pyc │ ├── __init__.py │ ├── __init__.pyc │ ├── models.py │ ├── models.pyc │ ├── templates │ │ └── register.html │ ├── tests.py │ ├── views.py │ └── views.pyc ├── form_pj │ ├── __init__.py │ ├── __init__.pyc │ ├── settings.py │ ├── settings.pyc │ ├── urls.py │ ├── urls.pyc │ ├── wsgi.py │ └── wsgi.pyc └── manage.py 3 directories, 19 files
2、关键代码:
form_pj.settings.py:
INSTALLED_APPS = ( ‘django.contrib.admin‘, ‘django.contrib.auth‘, ‘django.contrib.contenttypes‘, ‘django.contrib.sessions‘, ‘django.contrib.messages‘, ‘django.contrib.staticfiles‘, ‘blog‘, ) MIDDLEWARE_CLASSES = ( ‘django.contrib.sessions.middleware.SessionMiddleware‘, ‘django.middleware.common.CommonMiddleware‘, # ‘django.middleware.csrf.CsrfViewMiddleware‘, ‘django.contrib.auth.middleware.AuthenticationMiddleware‘, ‘django.contrib.messages.middleware.MessageMiddleware‘, ‘django.middleware.clickjacking.XFrameOptionsMiddleware‘, ) # Database DATABASES = { ‘default‘: { ‘ENGINE‘: ‘django.db.backends.mysql‘, ‘NAME‘: ‘tables_form‘, ‘USER‘:‘root‘, ‘PASSWORD‘:‘passwd‘, ‘HOST‘:‘localhost‘, ‘PORT‘:3306, } }
form_pj.urls.py:
url(r‘^register‘,‘blog.views.register‘),
blog.views.py:
#coding=utf-8 from django.shortcuts import render,render_to_response from django import forms from django.http import HttpResponse class UserForm(forms.Form): #创建form类对象 name = forms.CharField() #form对象基本应用模式 def register(req): # if req.method == ‘POST‘: #数据提交:表单提交的方法 form = UserForm(req.POST) #数据的验证:首先,表单对象的绑定 if form.is_valid(): #数据活取:如果数据有效,会放在cleaned_data字典 print form.cleaned_data return HttpResponse(‘ok‘) #返回动作 else: form = UserForm() return render_to_response(‘register.html‘,{‘form‘:form}) #模板文件和渲染的数据
3、运行开发服务器:
$ python manage.py runserver
时间: 2024-10-27 03:15:50