1

I want to store my data in a database using forms.

How can I do it without using SQLFORM like in php we use $var = $_POST['var_form']

I created a table in modul file called Produit

db.define_table('Produit',`enter code here`
           Field('Nom', requires = IS_NOT_EMPTY()),
           Field('Poid', 'float', requires = IS_NOT_EMPTY()),
           Field('Prix', 'float', requires = IS_NOT_EMPTY()),
           Field('Expiration', 'datetime'),
           auth.signature)

And created a form like

{{extend 'layout.html'}}

<form action="create" method=post>

<fieldset>
<legend><h1><center><em>Ajouter un produit</em></center></h1></legend>
Nom:<br>
<input type="text" name="nom" required/>
<br>
Poid:<br>
<input type="text" name="poid" required/>
<br>
 Prix:<br>
<input type="text" name="prix" required/>
<br>
Date d'expiration:<br>
<input type="date" name="exp" required/>
<br>
<br><br>
<input type="submit" value="Ajouter">

Jimmy T.
  • 4,033
  • 2
  • 22
  • 38

2 Answers2

1

Use URL helper to specify action of the form.

<form action="{{=URL('create')}}" method=post>
...
</form>

Then in create controller, you can access submitted values using request.vars

db.Produit.insert(Nom=request.vars.nom, Poid=request.vars.poid,
                  Prix=request.vars.prix, Expiration=request.vars.exp)
Gaurav Vichare
  • 1,143
  • 2
  • 11
  • 26
  • Thank you But i have another problem When i insert a product on database "Produit" i found it but i found another product with values 'None'. – Amine Sghiouri El-idrissi Aug 25 '16 at 18:09
  • @AmineSghiouriEl-idrissi that means your controller that contains `insert` statement is called twice. Did you refreshed view of that controller or directly opened view of above controller. Add [pdb](http://stackoverflow.com/questions/4228637/getting-started-with-the-python-debugger-pdb) and check. – Gaurav Vichare Aug 26 '16 at 03:53
0

This answer has the right idea, but to make things a little easier, you should use HTML field names that exactly match the database table field names. In that case, you can simplify the insert to:

db.Produit.insert(**db.Produit._filter_fields(request.post_vars))

Beware, though, that your manual approach lacks any protection against CSRF attacks (which the web2py form system would provide). As an alternative, note that you can still use SQLFORM even if you want to generate a custom form layout in the view. This approach is covered in the documentation here and here.

Community
  • 1
  • 1
Anthony
  • 25,466
  • 3
  • 28
  • 57