Flask. sqlalchemy.exc.InterfaceError: <app.models.Menu object at 0x7f287026dd10> - flask

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()

Related

select filtering and removal if they are already present in the db

look at the picture before answering me.
that group2 is inside saved in the db with the button I open a modal that allows me to save other groups in the db and I would like that the same groups no longer appear in that select if I have already added them
form.py
class EserciziForm(forms.ModelForm):
class Meta:
model = models.DatiEsercizi
exclude = ['gruppo_single']
#fields = '__all__'
class GruppiForm(forms.ModelForm):
class Meta:
model = models.DatiGruppi
exclude = ['gruppi_scheda']
views.py
def creazione(request, nome):
scheda = get_object_or_404(Schede, nome_scheda = nome)
eserciziFormSet = formset_factory(EserciziForm, extra = 0)
if request.method == "POST":
gruppo_form = GruppiForm(request.POST, prefix = 'gruppo')
if gruppo_form.is_valid():
gruppo = gruppo_form.save(commit = False)
gruppo.gruppi_scheda = scheda
gruppoName = gruppo_form.cleaned_data['dati_gruppo']
gruppo.save()
esercizi_formset = eserciziFormSet(request.POST, prefix='esercizi')
for esercizi in esercizi_formset:
esercizi_instance = esercizi.save(commit = False)
esercizi_instance.gruppo_single = get_object_or_404(DatiGruppi, gruppi_scheda = scheda.id, dati_gruppo = gruppoName)
esercizi_instance.save()
return HttpResponseRedirect(request.path_info)
else:
gruppo_form = GruppiForm(prefix = 'gruppo')
esercizi_formset = eserciziFormSet(prefix='esercizi')
context = {'scheda' : scheda, 'gruppo_form' : gruppo_form, 'esercizi_formset': esercizi_formset}
return render(request, 'crea/passo2.html', context
models.py
class DatiGruppi(models.Model):
giorni_settimana_scelta = [
("LUNEDI","Lunedì"),
("MARTEDI","Martedì"),
("MERCOLEDI","Mercoledì"),
("GIOVEDI","Giovedì"),
("VENERDI","Venerdì"),
("SABATO","Sabato"),
("DOMENICA","Domenica")
]
giorni_settimana = MultiSelectField(choices = giorni_settimana_scelta,default = '-')
dati_gruppo = models.ForeignKey(
Gruppi,on_delete = models.CASCADE, related_name = 'dati_gruppo')
gruppi_scheda = models.ForeignKey(Schede,on_delete = models.CASCADE, related_name = 'gruppi_scheda')
class Schede(models.Model):
nome_scheda = models.CharField(max_length=100)
data_inizio = models.DateField()
data_fine = models.DateField()
utente = models.ForeignKey(User, on_delete = models.CASCADE,related_name = 'utente')
You can override a form field before instantiate it like this :
views.py
from django import forms
if request.method == "POST":
# Post logic here
else:
# We try to retrieve group that the current user is not yet in.
# Not your logic, but to sum up, you have to retrieve the groups
# which had not yet been added.
# Use a filter that permit you to retrieve only groups which had not yet been added.
group_to_add = Group.objects.filter(...)
GruppiForm.base_fields['group_field'] = forms.ModelChoiceField(
queryset=group_to_add)
# Instantiate the form now
# In this form, the choices are only those contained in the group_to_add queryset
form = GruppiForm(prefix = 'gruppo')

get id not value from SqlAlchemy_wtforms QuerySelectField

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:
....

Cannot assign "42": "Event.user_id" must be a "User" instance

I have checked all the solutions related to my question but no one worked, i have an event table in which i am assigning the id of user. Event Model is
class Event(models.Model):
user_id=models.ForeignKey(User, on_delete=models.CASCADE)
event_auth_id=models.CharField(null=True, max_length=225)
event_title=models.CharField(max_length=225)
ticket_title=models.CharField(max_length=225)
category=models.CharField(max_length=50)
event_summary=models.TextField()
event_information=models.TextField()
restriction=models.CharField(max_length=50, default='No Restriction')
artist_image=models.CharField(null=True, max_length=50)
event_poster=models.CharField(null=True, max_length=50)
notification_email=models.CharField(null=True, max_length=50)
notification_frequency=models.CharField(null=True, max_length=15)
name_on_ticket=models.CharField(max_length=225)
event_tnc=models.TextField()
current_step=models.IntegerField(null=True)
event_status=models.BooleanField(default=True)
created=models.DateTimeField(auto_now=True)
modified=models.DateTimeField(auto_now_add=True)
I am assigning the logged in user id from view
def create_new_event(request, steps):
if request.method == 'POST':
if(steps=="step_1"):
stepFirstForm = CreateEventStepFirstForm(request.POST)
if stepFirstForm.is_valid():
eventStepFirst = Event(
user_id = request.user.id,
event_auth_id = uuid4(),
event_title = request.POST['event_title'],
ticket_title = request.POST['ticket_title'],
category = request.POST['categories'],
event_summary = request.POST['event_summary'],
event_information = request.POST['event_information'],
restriction = request.POST['restrictions'],
notification_email = request.POST['notification_email'],
notification_frequency = request.POST['email_frequency']
)
But its giving me error
Cannot assign "42": "Event.user_id" must be a "User" instance.
The problem is in this code:
def create_new_event(request, steps):
if request.method == 'POST':
if(steps=="step_1"):
stepFirstForm = CreateEventStepFirstForm(request.POST)
if stepFirstForm.is_valid():
eventStepFirst = Event(
user_id = request.user.id,
event_auth_id = uuid4(),
event_title = request.POST['event_title'],
ticket_title = request.POST['ticket_title'],
category = request.POST['categories'],
event_summary = request.POST['event_summary'],
event_information = request.POST['event_information'],
restriction = request.POST['restrictions'],
notification_email = request.POST['notification_email'],
notification_frequency = request.POST['email_frequency']
)
In the place of "user_id = request.user.id" You should use "user_id = request.user" or "user_id = request.user.username" because in the field
user_id=models.ForeignKey(User, on_delete=models.CASCADE)
of Event model,you assigned user_id as a foreign key of User model,So user_id field is expecting a User instance,not request.user.id
Thanks.
The ForeignKey field is expecting an object of type User, not the user ID. Try changing the assignment user_id = request.user.id to user_id = request.user. It might also make sense to rename the field to "user" to avoid confusion in the future.

How to save django fields using objects.create?

I have a model :
class Certificate(models.Model):
comments = models.TextField(blank=True, default='')
generic_certificate = models.ForeignKey(GenericCertificate, related_name='certificates_awarded')
tag = models.ForeignKey('Tag', related_name='certificates_awarded', null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
history_timestamp = models.DateTimeField(auto_now=True)
rewardee = models.ForeignKey(OrganisationUser, related_name='certificates_rewarded')
position = models.CharField(max_length=50, default = '0,0')
I want to save position fields given primary-key.
Here is views.py :
def post(self, request , *args , **kwargs):
comments = Certificate.objects.values("comments").filter(pk = kwargs.get('cert_id') )
gen_certi = Certificate.objects.values("generic_certificate").filter(pk = kwargs.get('cert_id') )
tag = Certificate.objects.values("tag").filter(pk = kwargs.get('cert_id') )
history_timestamp = Certificate.objects.values("history_timestamp").filter(pk = kwargs.get('cert_id') )
rewardee = Certificate.objects.values("rewardee").filter(pk = kwargs.get('cert_id') )
position = request.POST.get('hid')
position = str([position])
a = Certificate.objects.create( comments=comments, generic_certificate = gen_certi , tag=tag,rewardee=rewardee, position=position )
print a
Its giving error :
Exception Value:
Cannot assign "[{'generic_certificate': 2}]": "Certificate.generic_certificate" must be a "GenericCertificate" instance.
Please help how to save position field into database.
gen_certi variable is a queryset (list of objects), because you are using filter() - use get() instead:
gen_certi = Certificate.objects.get(pk = kwargs.get('cert_id')).generic_certificate
Actually, I don't understand what are you planning to do in the view. If you are modifying the object, there is no need to overwrite the existing fields, just update the fields that are passed to the view in request.POST, like position:
try:
certificate = Certificate.objects.get(pk = kwargs.get('cert_id'))
certificate.position = request.POST.get('hid')
certificate.save()
except DoesNotExist:
# create new certificate
certificate = Certificate()
...
Hope that helps.

IntegrityError error while saving value of to foreign key in django

Hey folks i am getting integrity error while saving my views .Please tell me what i am doing wrong
Here is my django model
class Ruleinfo(models.Model):
rule = models.IntegerField(null=False)
From = models.IPAddressField(null=True)
to = models.IPAddressField(null=True)
priority = models.ForeignKey('Priority',related_name='pri_no')
cisp =models.ForeignKey('Priority',related_name = 'CISP_no')
def __unicode__(self):
return u'%s' %(self.rule)
class Priority(models.Model):
pri = models.IntegerField(null = True)
Ruleno = models.ForeignKey('Ruleinfo',related_name = 'ruleno_no')
CISP = models.IntegerField(null = True)
def __unicode__(self):
return u'%s ' % (self.priority)
My model form is looking like .
class RuleInfoForm(ModelForm):
class Meta:
model = Ruleinfo
fields = ("rule","From","to")
here is my views.py
def multiwanrule_info(request):
data = {}
no_of_isp = MultiWAN.objects.all()
try:
form = RuleInfoForm(request.POST)
except:
pass
print "----------------------------printing form"
print form
if form.is_valid():
rl_frm = form.save(commit=False)
get_priorities = request.POST.getlist('priority')
get_cisp_info = request.POST.getlist('cisp')
rule_object = Ruleinfo()
for get_pri,get_ci in zip(get_priorities,get_cisp_info,):
pri_object = Priority.objects.get_or_create(Ruleno = rule_object)
pri_object.pri = get_pri
pri_object.CISP = get_ci
rl_frm.save()
else:
form = RuleInfoForm()
data['form'] = form
data['number_of_isp'] = no_of_isp
return render_to_response('networking.html',data)
I am getting the above error along this
networking_priority.Ruleno_id may not be NULL
help me out so that i could get back on track .
rule_object = Ruleinfo()
This just instantiates a new model object. It is not saved or assigned values. Since it is not saved it does not have an id value.
assigning your rule_object values: rule, from, to, priority, and cisp values, should fix your problem.