0
votes

I have the following Database Models:

class FlashcardCollection(db.Model):
    __tablename__ = 'flashcardcollection'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), index=True)
    timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
    flashcards = db.relationship('Flashcard', backref='collection', lazy='dynamic')
    categories = db.relationship('Category',
                             secondary=has_category,
                             backref=db.backref('collections', lazy='dynamic'),
                             lazy='dynamic')

class Category(db.Model):
    __tablename__ = 'category'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True, index=True)

has_category = db.Table('has_category',
                    db.Column('category_id', db.Integer, db.ForeignKey('category.id')),
                    db.Column('flashcardcollection_id', db.Integer, db.ForeignKey('flashcardcollection.id')))

I have the following Form Class:

class FlashcardCollectionForm(FlaskForm):
    name = StringField('Collection name', validators=[DataRequired()])
    category = SelectField('Category', choices=[])
    submit = SubmitField('Add')

With this Form i will add a new Flashcard Collection. Also i will allow the User to add a new Category for the Flashcard Collection while creating the Collection.

The View Function is the following (did not do anything right now)

@main.route('/add-collection', methods=['GET', 'POST'])
@login_required
def add_collection():
   form = FlashcardCollectionForm()
   if form.validate_on_submit():
       flash('Flashcard Collection added.')
       return redirect(url_for('.index'))
   return render_template('add_collection.html', form=form)

In this view Function the new Flashcardcollection will be created and added to the Database.

This is the Template:

{% block page_content %}
    <div class="page-header">
        <h1>Add a new Flashcard Collection</h1>
    </div>
    <div class="col-md-4">

        <form action="#" method="post">
            {{ form.csrf_token }}
            {{ form.name.label }} {{ form.name(size=20) }}
            {{ form.category.label }} {{ form.category(id="test") }}
            <button>Add</button>
            <input type="submit" value="Go">
        </form>
    </div>
{% endblock %}

A Click on the Add Button should prompt the User to enter a new Category. This Category should then be added to the Database and displayed in the Select Field. A CLick on the Submit Button should add the Flashcard Collection to the Database.

The Problem is the First Part. How can i dynamically add a new Category while creating a new Flashcard Collection? Is there a solution without Javascript or should i use javascript. If yes how does the Function looks like?

1

1 Answers

0
votes

With flask_sqlalchemy easily can create a model and populate select tag. Next add __init__ method to form class to populate values from database:

class FlashcardCollectionForm(FlaskForm):
    ...
    def __init__(self, *args, **kwargs):
        super(FlashcardCollectionForm, self).__init__(*args, **kwargs)
        self.category.choices = [(card.id)(card.category) for card in Card.query.all()]

with __init__, we set choices for select field all comes from database. Last, to save entries:

def add_collection():
   form = FlashcardCollectionForm()
   if request.method == 'POST':
       c = Category(name=form.name.data)
       f = FlashcardCollection(...)
       has_category(category_id=c.id, flashcardcollection_id=f.id)
       db.session.add_all([c, f])
       db.session.commit()