开发者

Python django sqlalchemy and formencode

I create a table in database using sqlalchemy and now want to make a form according to the database using django and valid it use formencode. (mention I use Django Web Framework) The python code is below

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 _开发者_StackOverflow_repr__(self):
    return self.name
#pass

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

mapper(Man_i, many_table)


At last I crete my own solutions can any one prefer me better than this **and if any one want they can use it its really save data onto database (not comment this line from settings.py->middleware_classes ->> #'django.middleware.csrf.CsrfViewMiddleware', for using post method )**

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%}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜