最后,我创建了自己的解决方案,任何人都比这更喜欢我
**如果有人想要他们可以使用它,它真的可以将数据保存到数据库中(不要从 settings.py->middleware_classes ->> #'django 评论这一行.middleware.csrf.CsrfViewMiddleware',用于使用 post 方法)**
from django.shortcuts import render_to_response
from sqlalchemy import *
from sqlalchemy.orm import *
import formencode
from formencode import validators, htmlfill
engine = create_engine("mysql+mysqldb://root:@localhost/testdb",echo = True)
#create database link
metadata = MetaData(engine)
session = create_session()
#database table
person_table = Table('person', metadata,
Column('id', Integer, primary_key = True),
Column('name', String(40)),
Column('age', Integer),
Column('about', String(100))
)
metadata.create_all(engine)#create database if not exist
class Person(object):#create a class for mapping
def __init__(self,name,age,about):
self.name = name
self.age = age
self.about = about
def __repr__(self):
return self.name, self.age, self.about
mapper(Person, person_table) #define map
class PersonValid(formencode.Schema):#for validation
name = validators.String(not_empty=True, min = 3, max = 40)
age = validators.Int(not_empty = True, min=1, max=120)
about = validators.String(not_empty=True, min = 5, max = 100)
def insert_d(request): #insert def
#for template page
out = """
<table>
<tr>
<td>Name:</td>
<td><input type="text" name = "name"/>
<form:error name = "name"/>
<!--form:iferror name="name">Horrible horror message</form:iferror-->
<td>
</tr>
<tr>
<td>Age:</td>
<td><input type="text" name="age"/>
<form:error name="age" />
<!--form:iferror name="age">Horrible horror message</form:iferror-->
</td>
</tr>
<tr>
<td>About</td>
<td><textarea name="about"></textarea>
<form:error name="about" />
<!--form:iferror name="about">Horrible horror message</form:iferror-->
<td>
</tr>
<table>
<input type = "submit" value = "Submit">
"""
if request.method == 'POST':
inp = {'name': request.POST['name'],
'age': request.POST['age'],
'about': request.POST['about']
}
try:
PersonValid.to_python(inp)
a_person = Person(['name'],
inp['age'],
inp['about']
)
session.add(a_person)
session.flush()
return render_to_response('formencode/htmlfill.html',
{'out': htmlfill.render(out,{} ),
'text':"Saved OK"}
)
except validators.Invalid, e:
val = htmlfill.render(out, e.error_dict or {})
else:
return render_to_response('formencode/htmlfill.html',
{'out':out,'text':"POST NOT START"}
)
#html form
#the htmlfill.html locate in "templete/formencode/"
directory contain the page below
<form name="out" method="POST" action="/fcode_alch/">
{%autoescape off%}
{{text}}
{{out}}
{%endautoescape%}