Skip to content

Instantly share code, notes, and snippets.

@MariaCarolinass

MariaCarolinass/form.py

Last active Oct 26, 2020
Embed
What would you like to do?
tags n pra n
#!/usr/bin/env python -*- coding: utf-8 -*-
from flask import request
from flask_wtf import FlaskForm, RecaptchaField
from wtforms import StringField, SelectField, TextField, TextAreaField, \
DateField, PasswordField, RadioField, BooleanField, SubmitField
from wtforms.validators import ValidationError, DataRequired, Length, \
Email, EqualTo, Regexp
from app.util.validators import Unique
from datetime import datetime
from flask_babel import _, lazy_gettext as _l
from app.models import User, Source
class TagField(StringField):
def _value(self):
if self.data:
# Display tags as a comma-separated list.
return ', '.join([tag.keyword for tag in self.data])
return ''
def get_tags_from_string(self, tag_string):
raw_tags = tag_string.split(',')
# Filter out any empty tag names.
tag_names = [keyword.strip() for keyword in raw_tags if keyword.strip()]
# Query the database and retrieve any tags we have already saved.
existing_tags = Tag.query.filter(Tag.keyword.in_(tag_names))
# Determine which tag names are new.
new_names = set(tag_names) - set([tag.keyword for tag in existing_tags])
# Create a list of unsaved Tag instances for the new tags.
new_tags = [Tag(keyword=keyword) for keyword in new_names]
# Return all the existing tags + all the new, unsaved tags.
return list(existing_tags) + new_tags
def process_formdata(self, valuelist):
if valuelist:
self.data = self.get_tags_from_string(valuelist[0])
else:
self.data = []
class SourceForm(FlaskForm):
title = StringField(_l('Título: *'), validators=[DataRequired()])
keyword = TagField(_l('Palavras-Chaves: *'), id="tag", validators=[DataRequired()],
render_kw={"placeholder": "Digite as palavras-chaves"})
submit = SubmitField(_l('Registrar'))
tags = db.Table('tags',
db.Column('tag_id', db.Integer, db.ForeignKey('tag.id')),
db.Column('source_id', db.Integer, db.ForeignKey('source.id')),
)
class Source(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(200), index=True, unique=True)
timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow)
tags = db.relationship('Tag', secondary=tags,
backref=db.backref('source_tag', lazy='dynamic'))
def __repr__(self):
return '{}'.format(self.title)
class Tag(db.Model):
id = db.Column(db.Integer, primary_key=True)
keyword = db.Column(db.String(200), index=True)
timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow)
def __repr__(self):
return '{}'.format(self.keyword)
@bp.route('/register_source', methods=['GET', 'POST'])
def register_source():
form = SourceForm()
if form.validate_on_submit():
source = Source(title=form.title.data)
db.session.add(source)
db.session.flush()
tag = Tag(keyword=form.keyword.data, tag_id=tag.id)
db.session.add(tag)
db.session.flush()
db.session.commit()
return render_template('register_source.html', title=(_('Cadastrar')), form=form)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment