Posted on

Pyramid 03: Add Item to database

Let’s add items to our database.
For this task we are going to use WTForms.
I recommend the crash course.

First create the file forms.py at the same lavel of views.py:

from wtforms import Form, StringField, IntegerField, validators


class TaskForm(Form):
    name = StringField('Name', [validators.Length(min=4, max=25)])
    active = IntegerField('Active', [validators.InputRequired()])

Now change the setup.py to include wtforms at the requires section:

requires = [
    'pyramid',
    'pyramid_jinja2',
    'pyramid_debugtoolbar',
    'waitress',
    'pymongo',
    'wtforms',
]

Now go to the views.py and add a view for adding new items to database and the necessary imports:

from .forms import TaskForm
from pyramid.httpexceptions import HTTPFound
from pyramid.url import route_url
from pyramid.view import view_config


@view_config(route_name='home', renderer='templates/home.jinja2')
def task_list(request):
    tasks = request.db['tasks'].find()
    return {
        'tasks': tasks,
        'project': 'task_manager',
    }

@view_config(route_name='tadd', renderer='templates/add.jinja2')
def task_add(request):
    form = TaskForm(request.POST, None)

    if request.POST and form.validate():
        entry = form.data
        request.db['tasks'].save(entry)
        return HTTPFound(route_url('home', request))

    return {'form': form}

Create the template file add.jinja2 next to home.jinja2:

{% extends "layout.jinja2" %}


{% block content %}
<form action="" method="post">
    <div>
        {{ form.name.label }}: {{ form.name(class="text-primary") }}
        {% if form.name.errors %}
            <ul class="errors">
            {% for error in form.name.errors %}
            <li>{{ error }}</li>
            {% endfor %}
            </ul>
        {% endif %}
    </div>
    <div>
        {{ form.active.label}}: {{ form.active(class="text-primary") }}
        {% if form.active.errors %}
            <ul class="errors">
            {% for error in form.active.errors %}
            <li>{{ error }}</li>
            {% endfor %}
            </ul>
        {% endif %}   
    </div>
    <input type="submit" value="Submit">
</form>
{% endblock content %}

At the end of the block content on file home.jinja2 add a link to add new items to the database:

<h2>Actions</h2>
<ul>
    <li><a href="{{request.route_url('tadd')}}">Add new Task</a></li>
</ul>

{% endblock content %}

Configure the route at the routes.py file:

def includeme(config):
    config.add_static_view('static', 'static', cache_max_age=3600)
    config.add_route('home', '/')
    config.add_route('tadd', '/add')

Go to the folder where setup.py is and install the project in order to install wtforms:

env/bin/pip install -e .

Run the project and add a few items:

env/bin/pserve development.ini --reload

Now you can add items to the database. Test it.

You can find the code for this part of the project at the part03 branch of the project repository.
To clone and run the specific branch use:

git clone -b part03 https://github.com/albertosdneto/tutorial_pyramid_mongo.git
cd tutorial_pyramid_mongo/
python3 -m venv env
env/bin/pip install --upgrade pip setuptools
env/bin/pip install -e .
env/bin/pserve development.ini --reload