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?