added populate methodes to froms.py that reduces the amount of different forms by 50%. you can use populate_for_add, populate_for_update and so on as eneccesery. and ythis alos you to not populate anything on routes.py

master
Kerem Yollu 10 months ago
parent 64cf31f939
commit 766f850d98

Binary file not shown.

@ -12,7 +12,7 @@ from minibase.blueprints.sensor.models import nbiotDevice
from minibase.blueprints.user.models import Users from minibase.blueprints.user.models import Users
class updateCompanyForm(FlaskForm): # Defines the form class to be used for the user update class companyForm(FlaskForm): # Defines the form class to be used for the user update
name = StringField('Name', validators=[DataRequired(), Length(min=3, max=100)]) name = StringField('Name', validators=[DataRequired(), Length(min=3, max=100)])
website = URLField('Website', validators=[DataRequired(), Length(min=3, max=100)]) website = URLField('Website', validators=[DataRequired(), Length(min=3, max=100)])
country_id = SelectField('Country', validators=[DataRequired()], render_kw={"hx-get": "/geography/get_cities", "hx-target": "#city_id"}) country_id = SelectField('Country', validators=[DataRequired()], render_kw={"hx-get": "/geography/get_cities", "hx-target": "#city_id"})
@ -30,9 +30,10 @@ class updateCompanyForm(FlaskForm): # Defines the form class to be used for the
image_file = FileField('Update company Picture', validators=[FileAllowed(['jpg', 'png'])]) image_file = FileField('Update company Picture', validators=[FileAllowed(['jpg', 'png'])])
submit = SubmitField('Update') submit = SubmitField()
def populate_choices(self, company): def populate_for_update(self, company):
self.submit.label.text = "Update"
self.country_id.choices = [(row.id, row.name) for row in geoUtils.queryCountryNamesWithDefault(company.country_id)] self.country_id.choices = [(row.id, row.name) for row in geoUtils.queryCountryNamesWithDefault(company.country_id)]
# This is for the htmx implementation. please be careful how of there is data we first take from the database an then from the from(containing th htmx call) # This is for the htmx implementation. please be careful how of there is data we first take from the database an then from the from(containing th htmx call)
@ -49,35 +50,28 @@ class updateCompanyForm(FlaskForm): # Defines the form class to be used for the
self.relation_id.choices = [(row.id, row.name) for row in companyUtils.queryRelationNamesWithDefault(company.relation_id)] self.relation_id.choices = [(row.id, row.name) for row in companyUtils.queryRelationNamesWithDefault(company.relation_id)]
self.status_id.choices = [(row.id, row.name) for row in companyUtils.queryStatusNamesWithDefault(company.status_id)] self.status_id.choices = [(row.id, row.name) for row in companyUtils.queryStatusNamesWithDefault(company.status_id)]
# Queries to be made in order to validate the form : If username exists def populate_for_adding(self, company):
def validate_companyName(self, company_name): self.submit.label.text = "Add"
company = companyUtils.queryByNameFirst(company_name) del self.image_file
if company:
raise ValidationError('That username is taken please choose another one')
self.country_id.choices = [(row.id, row.name) for row in geoUtils.queryCountryNames()]
class addCompanyForm(FlaskForm): # Defines the form class to be used for the user update # This is for the htmx implementation. please be careful how of there is data we switch the funtion needed
name = StringField('Name', validators=[DataRequired(), Length(min=3, max=100)]) if self.country_id.data:
website = URLField('Website', validators=[DataRequired(), Length(min=3, max=100)]) self.city_id.choices = [(row.id, row.name) for row in geoUtils.queryCityNamesWithCountryId(self.country_id.data)]
self.state_id.choices = [(row.id, row.name) for row in geoUtils.queryStateNamesWithCountryId(self.country_id.data)]
country = SelectField('Country', validators=[DataRequired()],choices=[], render_kw={"hx-get": "/geography/get_cities", "hx-target": "#city"}) else:
city = SelectField('City', validators=[DataRequired()], render_kw={"hx-get": "/geography/get_states", "hx-target": "#state"}) self.city_id.choices = []
state = SelectField('State', validators=[]) self.state_id.choices = []
post_code = IntegerField('Post', validators=[DataRequired()])
street = StringField('Street', validators=[DataRequired()])
street_no = IntegerField('No', validators=[DataRequired()])
industry = SelectField('Industry', validators=[DataRequired()])
legal_entity= SelectField('Legal Entity', validators=[DataRequired()])
type = SelectField('Type', validators=[DataRequired()])
relation = SelectField('Relation', validators=[DataRequired()])
status = SelectField('Status', validators=[DataRequired()])
comment = StringField('Comment', validators=[DataRequired(), Length(min=3, max=400)])
submit = SubmitField('Add') self.industry_id.choices = [(row.id, row.name) for row in mainUtils.queryIndustryNames()]
self.legal_entity_id.choices = [(row.id, row.name) for row in companyUtils.queryLegalEntityNames()]
self.type_id.choices = [(row.id, row.name) for row in companyUtils.queryTypeNames()]
self.relation_id.choices = [(row.id, row.name) for row in companyUtils.queryRelationNames()]
self.status_id.choices = [(row.id, row.name) for row in companyUtils.queryStatusNames()]
# Queries to be made in order to validate the form : If username exists # Queries to be made in order to validate the form : If username exists
def validate_companyName(self, company_name): def validate_companyName(self, company_name):
company = companyUtils.queryByNameFirst(company_name) company = companyUtils.queryByNameFirst(company_name)
if company: if company:
raise ValidationError('That username is taken please choose another one') raise ValidationError('That username is taken please choose another one')

@ -7,11 +7,12 @@ import minibase.blueprints.database.utils as dbUtils
import minibase.blueprints.main.utils as mainUtils import minibase.blueprints.main.utils as mainUtils
import minibase.blueprints.geography.utils as geoUtils import minibase.blueprints.geography.utils as geoUtils
import minibase.blueprints.company.utils as companyUtils import minibase.blueprints.company.utils as companyUtils
from minibase.blueprints.company.forms import updateCompanyForm, addCompanyForm from minibase.blueprints.company.forms import companyForm
# Declaring a blueprint # Declaring a blueprint
company = Blueprint('company', __name__, template_folder='templates') company = Blueprint('company', __name__, template_folder='templates')
@company.route("/list", methods=['GET', 'POST']) @company.route("/list", methods=['GET', 'POST'])
def list(): def list():
page=request.args.get('page', 1, type=int) page=request.args.get('page', 1, type=int)
@ -24,78 +25,48 @@ def list():
def account(companyId): def account(companyId):
if companyId: if companyId:
company = Companies.query.get_or_404(companyId) company = Companies.query.get_or_404(companyId)
form = updateCompanyForm() form = companyForm()
form.populate_for_update(company)
form.populate_choices(company) _accountInfo = mainUtils.accountInfo(
title=company.name,
description=company.legal_entity.name,
short=company.website,
status=company.type.name,
image_file=mainUtils.imageFileLink(company.image_file)
)
if form.validate_on_submit(): if form.validate_on_submit():
if form.image_file.data: if form.image_file.data:
picture_file = mainUtils.save_picture(form.image_file.data) picture_file = mainUtils.save_picture(form.image_file.data)
company.image_file = picture_file company.image_file = picture_file
for item in form: mainUtils.fill_model(company, form)
mainUtils.modelFill(company, item, ["image_file"])
dbUtils.dbCommit() dbUtils.dbCommit()
flash('Company Has been successfully updated', 'success') flash('Company Has been successfully updated', 'success')
return redirect(url_for('company.account', companyId=companyId)) return redirect(url_for('company.account', companyId=companyId))
elif request.method == 'GET': elif request.method == 'GET':
for item in form: mainUtils.populate_form(form, company)
item.data = mainUtils.formFill(item, company)
image_file = url_for('static', filename='pics/' + companyUtils.queryImageById(companyId))
return render_template('company/account.html', return render_template('account.html', theme=theme, accountInfo=_accountInfo, form=form)
theme=theme,
image_file=image_file,
form=form)
else: else:
flash('You need to select a company id', 'alarm') flash('You need to select a company id', 'alarm')
return redirect(url_for('company.list')) return redirect(url_for('company.list'))
@company.route("/add", methods=['GET', 'POST']) @company.route("/add", methods=['GET', 'POST'])
@login_required @login_required
def add(): def add():
form = addCompanyForm() company = Companies()
form = companyForm()
form.country.choices = [(row.id, row.name) for row in geoUtils.queryCountryNames()] form.populate_for_adding(company)
# This is for the htmx implementation. please be careful how of there is data we switch the funtion needed
if form.country.data:
form.city.choices = [(row.id, row.name) for row in geoUtils.queryCityNamesWithCountryId(form.country.data)]
form.state.choices = [(row.id, row.name) for row in geoUtils.queryStateNamesWithCountryId(form.country.data)]
else:
form.city.choices = []
form.state.choices = []
form.industry.choices = [(row.id, row.name) for row in mainUtils.queryIndustryNames()]
form.legal_entity.choices = [(row.id, row.name) for row in companyUtils.queryLegalEntityNames()]
form.type.choices = [(row.id, row.name) for row in companyUtils.queryTypeNames()]
form.relation.choices = [(row.id, row.name) for row in companyUtils.queryRelationNames()]
form.status.choices = [(row.id, row.name) for row in companyUtils.queryStatusNames()]
if form.validate_on_submit(): if form.validate_on_submit():
company = Companies( mainUtils.fill_model(company, form)
name = form.name.data,
website = form.website.data,
country_id = form.country.data,
city_id = form.city.data,
state_id = form.state.data,
post_code = form.post_code.data,
street = form.street.data,
street_no = form.street_no.data,
industry_id = form.industry.data,
legal_entity_id = form.legal_entity.data,
type_id = form.type.data,
relation_id = form.relation.data,
status_id = form.status.data,
comment = form.comment.data)
dbUtils.dbAddAndCommit(company) dbUtils.dbAddAndCommit(company)
flash('Company Has been successfully added', 'success') flash('Company Has been successfully Added', 'success')
return redirect(url_for('company.list')) return redirect(url_for('company.list'))
return render_template('edit.html', return render_template('edit.html', title="Add Company", theme=theme, form=form)
title="Add Company",
theme=theme,
form=form)

@ -5,12 +5,12 @@
<div class="row"> <div class="row">
<div class="col-md-3 border-right"> <div class="col-md-3 border-right">
<div class="d-flex flex-column align-items-center text-center p-3 py-5"> <div class="d-flex flex-column align-items-center text-center p-3 py-5">
<img class="rounded-circle mt-4 border-info" width="150px" src="{{ image_file }}"> <img class="rounded-circle mt-4 border-info" width="150px" src="{{ accountInfo.image_file }}">
<h2 class="account-heading" style="color: {{ theme.orange }};">{{ form.name.data }}</h2> <h2 class="account-heading" style="color: {{ theme.orange }};">{{ accountInfo.title }}</h2>
<h3 class="account-heading" style="color: {{ theme.orange }};">{{ form.legal_entity_id.data }}</h2> <h3 class="account-heading" style="color: {{ theme.orange }};">{{ accountInfo.description }}</h2>
<h5 class="account-heading" style="color: {{ theme.light_blue }};">{{ form.website.data }}</h5> <h5 class="account-heading" style="color: {{ theme.light_blue }};">{{ accountInfo.short }}</h5>
<div class="p-3 py-5"> <div class="p-3 py-5">
<h4 class="account-heading" style="color: {{ theme.yellow }};">{{ form.type_id.data }}</h4> <h4 class="account-heading" style="color: {{ theme.yellow }};">{{ accountInfo.status }}</h4>
</div> </div>
</div> </div>
</div> </div>

@ -8,23 +8,47 @@ from minibase.blueprints.main.models import Industries
import minibase.blueprints.database.utils as dbUtils import minibase.blueprints.database.utils as dbUtils
def formFill(item, table, to_ignore=[]): class accountInfo:
def __init__(self, title, description, short, status, image_file):
self.title = title
self.description = description
self.short = short
self.status = status
self.image_file = image_file
# FORM AND MODEL MANAGEMENT
def fill_model(company, form):
for item in form:
modelFill(company, item)
def populate_form(form, company):
for item in form:
item.data = formFill(item, company)
def formFill(item, table):
if item.type not in ["SubmitField", "CSRFTokenField"]: if item.type not in ["SubmitField", "CSRFTokenField"]:
if item.name not in to_ignore: return getattr(table, item.name)
attribute = getattr(table, item.name)
if hasattr(attribute, 'name'):
return getattr(attribute, 'name')
else:
return attribute
def modelFill(table, item, to_ignore=[]): def modelFill(table, item):
if item.type not in ["SubmitField", "CSRFTokenField"]: if item.type not in ["SubmitField", "CSRFTokenField"]:
print(item.type) if item.type == "FileField":
if item.name not in to_ignore: if item.data == "None":
print(f"File filed found with no data -> item name {item.name}")
print(f"It will be filled with the existin tbale data -> item name {getattr(table, item.name)}")
setattr(table, item.name, getattr(table, item.name))
else:
setattr(table, item.name, item.data) setattr(table, item.name, item.data)
# PICTURE MANAGEMENT
def imageFileLink(imageFileName):
return url_for('static', filename='pics/' + imageFileName)
def save_picture(form_picture): def save_picture(form_picture):
random_hex = secrets.token_hex(8) random_hex = secrets.token_hex(8)
_, f_ext = os.path.splitext(form_picture.filename) _, f_ext = os.path.splitext(form_picture.filename)
@ -37,6 +61,7 @@ def save_picture(form_picture):
return picture_fn return picture_fn
# MAIL MECHANISMS
def send_reset_email(user): def send_reset_email(user):
token = user.get_reset_token() token = user.get_reset_token()
msg = Message('Password Reset Request', msg = Message('Password Reset Request',
@ -44,17 +69,16 @@ def send_reset_email(user):
recipients=[user.email_account]) recipients=[user.email_account])
msg.body = f'''To reset your password, visit the following link: msg.body = f'''To reset your password, visit the following link:
{url_for('user.reset_token', token=token, _external=True)} {url_for('user.reset_token', token=token, _external=True)}
If you didn't make this request, then simply ingnore this email and no chancges will be made. If you didn't make this request, then simply ingnore this email and no changes will be made.
''' '''
mail.send(msg) mail.send(msg)
# QUERIES
def queryIndustryNames(): def queryIndustryNames():
choices = Industries.query.order_by(Industries.name.asc()) choices = Industries.query.order_by(Industries.name.asc())
return choices return choices
def queryIndustryNamesWithDefault(defId): def queryIndustryNamesWithDefault(defId):
choices = dbUtils.queryNameWithDefaultId(Industries,defId) choices = dbUtils.queryNameWithDefaultId(Industries,defId)
return choices return choices

@ -105,17 +105,3 @@ class updateNbioDeviceAddForm(FlaskForm): # Defines the form class to be used f
if content: if content:
raise ValidationError('That IP id is taken please choose another one') raise ValidationError('That IP id is taken please choose another one')
class updateRoleForm(FlaskForm):
id = StringField('ID', render_kw={'disabled':''})
role = StringField('Role', validators=[DataRequired(), Length(min=4, max=20)])
description = StringField('Description', validators=[DataRequired(), Length(min=4, max=200)])
submit = SubmitField()
class updateRoleForm(FlaskForm):
id = StringField('ID', render_kw={'disabled':''})
role = StringField('Role', validators=[DataRequired(), Length(min=4, max=20)])
description = StringField('Description', validators=[DataRequired(), Length(min=4, max=200)])
submit = SubmitField()

@ -11,7 +11,6 @@ from minibase.app import db
import json import json
import os import os
# TODO:
sensor = Blueprint('sensor', __name__, template_folder='templates') sensor = Blueprint('sensor', __name__, template_folder='templates')
@ -59,6 +58,7 @@ def get_data():
if os.path.exists(DATA_FILE): if os.path.exists(DATA_FILE):
with open(DATA_FILE, 'r') as f: with open(DATA_FILE, 'r') as f:
stored_data = json.load(f) stored_data = json.load(f)
# TODO:
else: else:
stored_data = [] stored_data = []

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

@ -0,0 +1,31 @@
{% extends "base.html" %}
{% block content %}
<div class="container-fluid rounded-5 mt-5 mb-5" style="{{ theme.form.div_style }};">
<div class="row">
<div class="col-md-3 border-right">
<div class="d-flex flex-column align-items-center text-center p-3 py-5">
<img class="rounded-circle mt-4 border-info" width="150px" src="{{ accountInfo.image_file }}">
<h2 class="account-heading" style="color: {{ theme.orange }};">{{ accountInfo.title }}</h2>
<h3 class="account-heading" style="color: {{ theme.orange }};">{{ accountInfo.description }}</h2>
<h5 class="account-heading" style="color: {{ theme.light_blue }};">{{ accountInfo.short }}</h5>
<div class="p-3 py-5">
<h4 class="account-heading" style="color: {{ theme.yellow }};">{{ accountInfo.status }}</h4>
</div>
</div>
</div>
<div class="col-md-4">
<div class="p-3 py-4">
{% include 'form.html' %}
</div>
</div>
<div class="col-md-4">
<div class="p-3 py-4">
</div>
</div>
</div>
</div>
{% endblock content %}
Loading…
Cancel
Save