2

我使用 sqlalchemy 在数据库中创建了一个表,现在想使用 django 根据数据库制作一个表格,并使用 formencode 对其进行验证。(提到我使用 Django Web 框架)python 代码如下

from sqlalchemy import *
from sqlalchemy.orm import *

engine = create_engine('mysql+mysqldb://root:@localhost/testdb', echo = True)

metadata = MetaData(engine)

session = create_session()

one_table = Table('one', metadata,
              Column('id',Integer, primary_key = True),
              Column('name',String(40))
              )
many_table = Table('many_i', metadata,
               Column('id', Integer, primary_key = True),
               Column('name', String(40)),
               Column('one_id',Integer, ForeignKey('one.id'))
               )

metadata.create_all(engine)

class One(object):
def __init__(self, name):
    self.name = name
def __repr__(self):
    return self.name
#pass

class Man_i(object):
def __init__(self, name):
   self.name = name

def __repr__(self):
    return self.name
#pass

mapper(One, one_table,
   properties={'o2m':relationship(Man_i)
               }
   )

mapper(Man_i, many_table)
4

1 回答 1

2

最后,我创建了自己的解决方案,任何人都比这更喜欢我 **如果有人想要他们可以使用它,它真的可以将数据保存到数据库中(不要从 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%}
于 2011-05-29T10:49:04.717 回答