I have the following model:
from marshmallow import Schema, fields
from server import db, ma, app
from sqlalchemy.ext.hybrid import hybrid_property
from .analysis import AnalysisSchema
class Category(db.Model):
__tablename__ = 'Categories'
__table_args__ = {'extend_existing': True}
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(120), index=True, unique=True)
description = db.Column(db.Text, nullable=False)
img = db.Column(db.LargeBinary, nullable=False)
img_mimetype = db.Column(db.Text, nullable=False)
img_name = db.Column(db.Text, nullable=False)
analysis = db.relationship("Analysis", back_populates="category")
#property
def img_url(self):
return "/categories/" + str(self.id)
class CategorySchema(ma.SQLAlchemyAutoSchema):
class Meta:
# model = Category
fields = ("id", "name", "description", "img", "img_url", "analysis")
analysis = fields.Nested(AnalysisSchema, many=True)
class CreateCategorySchema(Schema):
name = fields.Str(required=True)
description = fields.Str(required=True)
class UpdateCategorySchema(Schema):
name = fields.Str(required=True)
description = fields.Str(required=False)
img_name = fields.Str(required=False)
img_mimetype = fields.Str(required=False)
I create a new category with the following code:
from flask import jsonify
from server import db, app
from ..models.category import (
Category,
CategorySchema,
CreateCategorySchema,
UpdateCategorySchema
)
def create_category(data):
app.logger.info('Create category invoked')
create_category_schema = CreateCategorySchema()
# errors = create_category_schema.validate(data)
errors = None
if errors:
app.logger.info('Found errors %s', errors)
return jsonify(errors), 400
name = Category.query.filter_by(name=data['name']).first()
app.logger.info('Name is %s', name)
if not name:
app.logger.info('Name not present')
category = Category(
name=data['name'],
description=data['description'],
img=data['img'],
img_name=data['img_name'],
img_mimetype=data['img_mimetype']
)
_save_category(category)
category_schema = CategorySchema()
response = category_schema.dump(category), 201
#response = jsonify('Category created'), 200
else:
response = jsonify('Category already exists'), 409
return response
def all_categories():
category_schema = CategorySchema(many=True, exclude=['img'])
categories = Category.query.all()
response = category_schema.dump(categories)
return jsonify(response), 20
def get_category(id):
return Category.query.filter_by(id=id).first()
def _save_category(category):
db.session.add(category)
db.session.commit()
If I try to invoke create_category I got the following error:
sqlalchemy.exc.DataError: (MySQLdb._exceptions.DataError) (1406, "Data too long for column 'img' at row 1")
[SQL: INSERT INTO `Categories` (name, description, img, img_mimetype, img_name) VALUES (%s, %s, %s, %s, %s)]
[parameters: ('test10', 'blah blah blah', b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00\x84\x00\x06\x06\x06\x06\x07\x06\x07\x08\x08\x07\n\x0b\n\x0b\n\x0f\x ... (371140 characters truncated) ... xe4\xd3\xc0\xe3\xcag\xaf\x17\xff\x00\xcc?\xfdD\xfe\x85\xc3\x91\x06\x07\x017#3\x93:\x7fE\xfe\xb3\xff\x00\xe9_\xff\x00\x04r-i\x86\xb7\xd6|#\xbf\xff\xd9', 'image/jpeg', 'WhatsApp_Image_2021-06-04_at_11.14.49_AM.jpeg')]
(Background on this error at: http://sqlalche.me/e/14/9h9h)
I don't understand why is trying to insert an image as a String if it is explicitly defined as a LargeBinary.
The solution can be found in the question comments. I had to increase the size of the Blob using the length attribute of SQLAlchemy.
Related
I'm trying to use bulk_create in order to add objects to related models. Here i'm fetching the csv file through post request which contains required fields. As of now I can add items to models which is unrelated using the csv file and bulk_create and it's working.
class BulkAPI(APIView):
def post(self, request):
paramFile = io.TextIOWrapper(request.FILES['requirementfile'].file)
dict1 = csv.DictReader(paramFile)
list_of_dict = list(dict1)
objs = [
ManpowerRequirement(
project=row['project'],
position=row['position'],
quantity=row['quantity'],
project_location=row['project_location'],
requested_date=row['requested_date'],
required_date=row['required_date'],
employment_type=row['employment_type'],
duration=row['duration'],
visa_type=row['visa_type'],
remarks=row['remarks'],
)
for row in list_of_dict
]
try:
msg = ManpowerRequirement.objects.bulk_create(objs)
returnmsg = {"status_code": 200}
print('imported successfully')
except Exception as e:
print('Error While Importing Data: ', e)
returnmsg = {"status_code": 500}
return JsonResponse(returnmsg)
My models are:
class ManpowerRequirement(models.Model):
project = models.CharField(max_length=60)
position = models.CharField(max_length=60)
quantity = models.IntegerField()
project_location = models.CharField(max_length=60)
requested_date = models.DateField()
required_date = models.DateField()
employment_type = models.CharField(max_length=60,choices = EMPLOYMENT_TYPE_CHOICES,
default = 'Permanent')
duration = models.CharField(max_length=60)
visa_type = models.CharField(max_length=60)
remarks = models.TextField(blank = True , null=True)
def __str__(self):
return self.project
class Meta:
verbose_name_plural = "Manpower_Requirement"
class Fulfillment(models.Model):
candidate_name = models.CharField(max_length=60)
manpower_requirement = models.ForeignKey(ManpowerRequirement, on_delete=models.CASCADE)
passport_number = models.CharField(blank = True, max_length=60)
subcontract_vendors = models.CharField(max_length=200,blank = True , null=True ,default='')
joined_date = models.DateField(blank = True, null = True, default = '')
remarks = models.TextField( blank = True,null = True)
def __str__(self):
return self.candidate_name
class Meta:
verbose_name_plural = "Fulfillment"
class FulfillmentStatus(models.Model):
fulfillment = models.ForeignKey(Fulfillment, on_delete=models.CASCADE)
status = models.CharField(max_length=60)
status_date = models.DateField()
remarks = models.TextField( blank = True, null = True )
def __str__(self):
return self.fulfillment.candidate_name
class Meta:
verbose_name_plural = "FulfillmentStatus"
I don't know how to do the same using bulk_create for Fulfillment and FulfillmentStatus models which are related to ManpowerRequirement. Csv file which I recieve in order to bulkcreate for Fulfillment consists of all the fields of ManpowerRequirement and all fields of Fulfillment and FulfillmentStatus excluding the foreign keys and id fields.
in the past I had the same problem; I solved in that way
Assuming that in a single CSV row you have data for all models I'd go for
create a mapping between the main model and the linked ones (you could use row index as key
use bulk_create() on the main model
iterate the dict and use bulk_create() for the linked modules
items = []
mrs = []
for row in list_of_dict:
mr = ManpowerRequirement(...)
mrs.append(mr)
f = ManpowerRequirement(...)
fs = FulfillmentStatus(...)
items.append((mr, f, fs))
# create all Manpower Requirements
ManpowerRequirements.objects.bulk_create(mrs)
a = []
for mr, f, fs in items:
f.manpower_requirement = mr
a.append(f)
# create all Fulfillments
Fulfillment.objects.bulk_create(a)
a = []
for mr, f, fs in items:
fs.fulfillment = f
a.append(fs)
# create all FulfillmentStatus
FulfillmentStatus.objects.bulk_create(a)
not sure if you can do some optimization in looping but it should solve the problem with just 3 queries
For related models we can do like this
class FulfillmentAPI(APIView):
def post(self, request):
paramFile = io.TextIOWrapper(request.FILES['fulfillmentfile'].file)
dict1 = csv.DictReader(paramFile)
list_of_dict = list(dict1)
objs = [
Fulfillment(
manpower_requirement=ManpowerRequirement.objects.get(project=row['project'], position=row['position'], quantity=row['quantity'], requested_date=row['requested_date'],),
remarks=row['remarks'],
candidate_name=row['candidate_name'],
passport_number=row['passport_number'],
joined_date=row['joined_date'],
subcontract_vendors=row['subcontract_vendors'],
)
for row in list_of_dict
]
try:
msg = Fulfillment.objects.bulk_create(objs)
returnmsg = {"status_code": 200}
print('imported successfully')
except Exception as e:
print('Error While Importing Data: ', e)
returnmsg = {"status_code": 500}
return JsonResponse(returnmsg)
I have been trying to make a relationship between two table and have a QuerySelectFiled to select a field from the other table, I have managed to do so, but the problem came when I wanted to submit the field I keep getting :
InterfaceError: <unprintable InterfaceError object>
after debugging the issue I found out that when the form is submitted the value of the field is being submitted not the id, I have solved that by saying in my model
self.firstAuthor = firstAuthor.id
solved the issue but if I choose the empty value it will break because the empty field does not have property id.
so can someone suggest how to do that?
here is my form:
from wtforms_alchemy import QuerySelectField, QuerySelectMultipleField
from ....module1.authors.author.authorModel import Author
from flask_wtf import FlaskForm
from wtforms import SubmitField, HiddenField, BooleanField, SelectField, StringField, FileField, IntegerField, DateTimeField
from datetime import datetime
from wtforms.validators import DataRequired
def getAuthor():
return Author.query
class PublicationsForm(FlaskForm):
id = HiddenField()
title = StringField('Title', validators=[DataRequired()])
category = SelectField('Category', choices=[('', ''),('Journal', 'Journal'), ('Conference', 'Conference'), ('Talk', 'Talk'),('Talk2', 'Talk2'),('Talk3', 'Talk3')])
year = DateTimeField('Year', format='%Y')
publisher = BooleanField('Publisher')
volume = IntegerField('Volume')
issue = IntegerField('Issue')
pages = StringField('Pages')
location = StringField('Location')
note = StringField('Note')
fullCitation = FileField('FullCitation')
fullSource = FileField('FullSource')
finalVersion = FileField('FinalVersion')
firstAuthor = QuerySelectField("FirstAuthor", query_factory=getAuthor, get_label="lastName", allow_blank=True, blank_text='')
secondAuthor = QuerySelectField("SecondAuthor", query_factory=getAuthor, get_label="lastName", allow_blank=True, blank_text='')
thirdAuthor = QuerySelectField("ThirdAuthor", query_factory=getAuthor, get_label="lastName", allow_blank=True, blank_text='')
fourthAuthor = QuerySelectField("FourthAuthor", query_factory=getAuthor, get_label="lastName", allow_blank=True, blank_text='')
fifthAuthor = QuerySelectField("FifthAuthor", query_factory=getAuthor, get_label="lastName", allow_blank=True, blank_text='')
sixthAuthor = QuerySelectField("SixthAuthor", query_factory=getAuthor, get_label="lastName", allow_blank=True, blank_text='')
submit = SubmitField("Save")
here is my model:
from sqlalchemy import Column, Integer, String, Boolean, DateTime
from app import db
class Publications(db.Model):
id = db.Column(Integer, primary_key=True)
title = db.Column(String, nullable=False)
category = db.Column(String, nullable=False)
year = db.Column(db.DateTime)
publisher = db.Column(Boolean)
volume = db.Column(Integer)
issue = db.Column(String)
pages = db.Column(String)
location = db.Column(String)
note = db.Column(String)
fullCitation = db.Column(String)
fullSource = db.Column(String)
finalVersion = db.Column(String)
issue = db.Column(db.Text)
firstAuthor = db.Column(db.Integer, db.ForeignKey('author.id'))
secondAuthor = db.Column(db.Integer, db.ForeignKey("author.id"),nullable=True )
thirdAuthor = db.Column(db.Integer, db.ForeignKey("author.id"),nullable=True )
fourthAuthor = db.Column(db.Integer, db.ForeignKey("author.id"),nullable=True )
fifthAuthor = db.Column(db.Integer, db.ForeignKey("author.id"),nullable=True )
sixthAuthor = db.Column(db.Integer, db.ForeignKey("author.id"),nullable=True )
def __init__(self, title, category, year, publisher, volume, issue, pages, location, note, fullCitation, fullSource, finalVersion, firstAuthor, secondAuthor, thirdAuthor, fourthAuthor, fifthAuthor, sixthAuthor):
self.title = title
self.category = category
self.year = year
self.publisher = publisher
self.volume = volume
self.issue = issue
self.pages = pages
self.location = location
self.note = note
self.fullCitation = fullCitation
self.fullSource = fullSource
self.finalVersion = finalVersion
self.firstAuthor = firstAuthor
self.secondAuthor = secondAuthor
self.thirdAuthor = thirdAuthor
self.fourthAuthor = fourthAuthor
self.fifthAuthor = fifthAuthor
self.sixthAuthor = sixthAuthor
def __repr__(self):
return self.title
here is my view:
from flask import render_template, request, flash, redirect, url_for
from . import publications_blueprint
from .publicationsForm import PublicationsForm
from .publicationsModel import Publications
from app import db
#publications_blueprint.route("/publications", methods=["GET", "POST"])
def createPublications():
form = PublicationsForm(request.form)
publicationss = Publications.query.all()
if request.method == "POST" and form.validate_on_submit():
publications = Publications(form.title.data, form.category.data, form.year.data, form.publisher.data, form.volume.data, form.issue.data, form.pages.data, form.location.data, form.note.data, form.fullCitation.data, form.fullSource.data, form.finalVersion.data, form.firstAuthor.data, form.secondAuthor.data, form.thirdAuthor.data, form.fourthAuthor.data, form.fifthAuthor.data, form.sixthAuthor.data)
db.session.add(publications)
db.session.commit()
flash("Added Publications Successfully")
return redirect(url_for("publications.createPublications"))
return render_template("publications/publications.html", title="Publicationss", form=form, publicationss=publicationss)
#publications_blueprint.route("/updatePublications/<int:publications_id>", methods=["GET", "POST"])
def updatePublications(publications_id):
publications = Publications.query.get(publications_id)
form = PublicationsForm(request.form, obj=publications)
if request.method == "POST" and form.validate_on_submit():
publications.title = form.title.data
publications.category = form.category.data
publications.year = form.year.data
publications.publisher = form.publisher.data
publications.volume = form.volume.data
publications.issue = form.issue.data
publications.pages = form.pages.data
publications.location = form.location.data
publications.note = form.note.data
publications.fullCitation = form.fullCitation.data
publications.fullSource = form.fullSource.data
publications.finalVersion = form.finalVersion.data
publications.firstAuthor = form.firstAuthor.data
publications.secondAuthor = form.secondAuthor.data
publications.thirdAuthor = form.thirdAuthor.data
publications.fourthAuthor = form.fourthAuthor.data
publications.fifthAuthor = form.fifthAuthor.data
publications.sixthAuthor = form.sixthAuthor.data
db.session.commit()
flash("Updated Publications Successfully")
return redirect(url_for("publications.createPublications"))
publicationss = Publications.query.all()
return render_template("publications/publications.html", title="Publications", form=form, publicationss=publicationss)
#publications_blueprint.route("/deletePublications/<int:publications_id>", methods=["GET", "POST"])
def deletePublications(publications_id):
publications = Publications.query.get(publications_id)
db.session.delete(publications)
db.session.commit()
return redirect(url_for("publications.createPublications"))
In a similar case, I also use allow_blank=True in the model for a QuerySelectField search_target. I check manually if there was something selected in the view:
if formfilter.search_target.data:
search_target = formfilter.search_target.data.id
else:
....
I am trying to paginate a secondary table for Client but it doesn't work, the results always more than the per_page parameter that by default shows only three items per page .
Here is my models.py:
subscribers = db.Table(
'clients_subscribed',
db.Column('client_id', db.Integer, db.ForeignKey('client.id', ondelete='CASCADE')),
db.Column('user_id', db.Integer, db.ForeignKey('user.id', ondelete='CASCADE'))
)
class Client(db.Model, UserMixin):
id = db.Column(db.Integer(), primary_key=True)
public_id = db.Column(db.String(50), default=uuid.uuid4)
name = db.Column(db.String())
subscribed_users = db.relationship(
'User',
secondary=subscribers,
backref=db.backref('user', passive_deletes=True, lazy='dynamic')
)
Here is also my views.py :
from flask import current_app
current_app.config['SUBSCRIBERS_PER_PAGE'] = 3
#api_route.route('/client/subscribers/<string:category>/<string:client_id>', methods=['GET'])
#token_required
def subscribers(current_user, category, client_id):
if request.method == 'GET':
page = request.args.get('page', 1, type=int)
client = Client.query.filter_by(public_id=client_id).first()
if not client:
raise InvalidUsage(u'404, not found!', status_code=404)
pagination = # Paginate Client.subscribed_users
psubscribers = pagination.items
subscribers = {}
prev = None
if pagination.has_prev:
prev = url_for('api.subscribers', category=category, client_id=client_id, page=page-1, _external=True)
next = None
if pagination.has_next:
next = url_for('api.subscribers', category=category, client_id=client_id, page=page+1, _external=True)
for client in client.subscribed_users:
subscribers_case = {
'id': client.id,
'public_id': client.public_id,
'image': '/static/img/'+client.image if client.image else '/static/img/logo.png',
'name': client.name,
}
subscribers[client.public_id] = subscribers_case
return jsonify({
'subscribers' : subscribers,
'prev' : prev,
'next': next,
'count' : pagination.total
})
return jsonify({'error' : 'No data!'})
Also here is the class User in models:
class User(db.Model, UserMixin):
__tablename__ = 'user'
id = db.Column(db.Integer(), primary_key=True)
public_id = db.Column(db.String(50), default=uuid.uuid4)
name = db.Column(db.String())
family = db.Column(db.String())
bio = db.Column(db.String())
tele = db.Column(db.String(), unique=True)
password = db.Column(db.String())
clients = db.relationship('Client', backref='user', passive_deletes=True, lazy='dynamic')
news = db.relationship('News', backref='user', passive_deletes=True, lazy='dynamic')
notifications = db.relationship('Notification', backref='user', passive_deletes=True, lazy='dynamic')
image = db.Column(db.String(), nullable=True)
slug = db.Column(db.String())
roles = db.relationship(
'Role',
secondary=roles,
backref=db.backref('users', lazy='joined',
passive_deletes=True,
single_parent=True)
)
subscribed_clients = db.relationship(
'Client',
secondary=subscribers,
backref=db.backref('client', passive_deletes=True, lazy='joined')
)
Any suggestions guys how to make that work !!!
You need to use lazy=dynamic in the relationship in order to get a Query object back. Documentation here, and another StackOverflow question about this here.
I am getting this error during inserting data in many to many relationship in sqlalchemy.
Models.py
class Event(db.Model):
__tablename__ = 'event'
id = db.Column(db.String(255), primary_key=True)
title = db.Column(db.String(255))
image_url = db.Column(db.String(255))
category_id = db.Column(db.String(255), db.ForeignKey('category.id'),
nullable=True)
subheading = db.Column(db.String(255))
event_city = db.Column(db.String(255))
venue = db.Column(db.String(255))
start_date = db.Column(db.DateTime)
end_date = db.Column(db.DateTime)
description = db.Column(db.String(255))
speaker = db.relationship("Speaker",
secondary=association_table)
errors = {}
def __init(self, **kwargs):
print kwargs
speaker1 = db.session.query(Speaker).first()
print speaker
self.speaker.append(speaker1)
self.id = generate_id()
kwargs.pop(EVENT_FIELDS['EVENT_SPEAKER'])
kwargs.pop(EVENT_FIELDS['EVENT_CATEGORY'])
for key, value in kwargs.iteritems():
try:
setattr(self, key, value)
except ex:
Event.errors = FORM_EMPTY_FIELD.format(key)
association table is
association_table = db.Table('association',
db.Column('speaker_id', db.String(255),
db.ForeignKey('speaker.id')),
db.Column('event_id', db.String(255),
db.ForeignKey('event.id')))
when i am inserting data i am getting error as mention above
In a M2M relationship the association in the speaker column of your model Event must be passed as list (means between brackets []) in this way, please note in __init__ method the assignation of speaker :
def __init(self, **kwargs):
print kwargs
speaker1 = db.session.query(Speaker).first()
print speaker
self.speaker = [speaker1]
self.id = generate_id()
kwargs.pop(EVENT_FIELDS['EVENT_SPEAKER'])
kwargs.pop(EVENT_FIELDS['EVENT_CATEGORY'])
for key, value in kwargs.iteritems():
try:
setattr(self, key, value)
except ex:
Event.errors = FORM_EMPTY_FIELD.format(key)
I am using QuerySelectField in my forms.py and when submitting it I get the following error:
InterfaceError: (InterfaceError) Error binding parameter 8 - probably unsupported
type. u'INSERT INTO menu (title, title_eng, alias, menu_type, ordering,
check_out_time, access, published, parent_id, image, content, content_eng,
metades, metakey) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
(u'\u0423\u0441\u043b\u043e\u0432\u0438\u044f \u043f\u043e\u0434\u043a\u043b\u044e\u0447\u0435\u043d\u0438\u044f',
u'terms of connecting', u'terms', u'simple', 4, '2014-01-23 00:00:00.000000',
u'public', u'1', <app.models.Menu object at 0x7fe158171990>, u'url/folder/image.jpg',
u'asd', u'asd', u'asd', u'asd')
I googled it and found out that the issue is that the returned value of QuerySelectField is object and I have to convert it to string, but I couldnt. Can you please help me with that issue?
here is my forms.py:
def menu_list():
return Menu.query
class Add_menu_form(Form):
"""Add_menu_form is used to add/edit menu"""
title = TextField(u'Название меню', [validators.Length(min=1, max=250), validators.Required()])
title_eng = TextField(u'Название меню на английском', [validators.Length(min=1, max=250), validators.Required()])
alias = TextField(u'Короткое название')
menu_type = SelectField(u'Тип меню',
choices=[('simple', u'обычное'),
('blog', u'блог'),
('products', u'продукция'),
('gallery', u'галерея')])
ordering = IntegerField(u'Позиция')
check_out_time = DateField(u'Дата публикации')
access = SelectField(u'Доступ',
choices=[('public', u'открытый'),
('registered', u'для зарегистрированных'),
('admin', u'для администратора')])
published = SelectField(u'Опубликовать',
choices=[('1', u'да'),
('0', u'нет')])
parent_id = QuerySelectField(u'Родительская группа',
query_factory = menu_list,
get_pk = lambda a: a.id,
get_label = lambda a: a.title,
allow_blank=True)
image = TextField(u'Заглавная картинка')
content = TextAreaField(u'Содержание', [validators.Required()])
content_eng = TextAreaField(u'Содержание на английском', [validators.Required()] )
metades = TextAreaField(u'HTML описание')
metakey = TextAreaField(u'HTML ключевые слова')
this is my models.py:
class Menu(db.Model):
"""Menu is used for websites navigation titles.
eg. Home/About Us/Blog/Contacts/and etc"""
id = db.Column(db.Integer, primary_key = True)
title = db.Column(db.String(255))
title_eng = db.Column(db.String(255))
alias = db.Column(db.String(255))
menu_type = db.Column(db.String(10))
#menu type: simple, blog, gallery, contacts, products
ordering = db.Column(db.SmallInteger, default = '1')
check_out_time = db.Column(db.DateTime)
access = db.Column(db.String(30))
#access: user, reductor, manager, administrator
published = db.Column(db.SmallInteger, default = '1')
parent_id = db.Column(db.Integer)
image = db.Column(db.String(350))
content = db.Column(db.String)
content_eng = db.Column(db.String)
metades = db.Column(db.String(350))
metakey = db.Column(db.String(350))
def __init__(self, title, title_eng, alias,
menu_type, ordering, check_out_time, access,
published, parent_id, image, content, content_eng,
metades, metakey):
self.title = title
self.title_eng = title_eng
self.alias = alias
self.menu_type = menu_type
self.ordering = ordering
self.check_out_time = check_out_time
self.access = access
self.published = published
self.parent_id = parent_id
self.image = image
self.content = content
self.content_eng = content_eng
self.metades = metades
self.metakey = metakey
# __str__ is a special method, like __init__, that is
# supposed to return a string representation of an object.
def __str__(self):
return '%.d' % (self.id)
and the views.py:
#admin.route('/manage/add_menu', methods = ['GET', 'POST'])
#login_required
def add_menu(parent = ''):
form = Add_menu_form()
if form.validate_on_submit():
new_menu = Menu(
form.title.data,
form.title_eng.data,
form.alias.data,
form.menu_type.data,
form.ordering.data,
form.check_out_time.data,
form.access.data,
form.published.data,
form.parent_id.data,
form.image.data,
form.content.data,
form.content_eng.data,
form.metades.data,
form.metakey.data)
form.populate_obj(new_menu)
db.session.add(new_menu)
db.session.commit()
flash('New menu was added successfully.')
return redirect(url_for('cabinet.manage', current = 'menu_settings'))
return render_template('admin/manage/site_figuration/add_menu.html',
title = 'Internet market',
parent = parent,
form = form)
Finally the issue is solved after hours of googling. the issue was about QuerySelectField. The problems was that when retrieving form.parent_id.data it actually returned a query object, whie I need a string vaue. So I converted the value to string and added submitted it to database:
a = str(form.parent_id.data)
if form.validate_on_submit():
new_menu = Menu(
form.title.data,
form.title_eng.data,
form.alias.data,
form.menu_type.data,
form.ordering.data,
form.check_out_time.data,
form.access.data,
form.published.data,
a, #form.parent_id.data,
form.image.data,
form.content.data,
form.content_eng.data,
form.metades.data,
form.metakey.data)
form.populate_obj(new_menu)
db.session.add(new_menu)
db.session.commit()