This is my query:
SELECT
form_fields.label_name,
entry_details.value,
entry_details.entry_id
FROM
form_fields
JOIN
entry_details ON entry_details.field_id = form_fields.id
WHERE
form_fields.id IN (21401, 21402)
AND entry_details.entry_id = 79;
I am a entry level developer having problem to convert this query into django query... Please help me
Assuming that form_fields model is called FormFields and entry_details is a field on this model then it should be something like:
query = FormFields.objects.filter(
id__in=[21401, 21402], entry_details__id=79)
.select_related(
"entry_details"
).only("label_name", "entry_details__id", "entry_details__value")
I'm not sure about only here. You can try without it first
My constrains method not working for id_number. can't figure it out why.
from odoo import models, fields, api
from odoo.exceptions import ValidationError
class KindeGarden(models.Model):
_inherits = {'res.partner': 'partner_id'}
_name = 'kindergarten.model'
_description = 'Kindergarten'
age = fields.Integer(string="Amžius", required=False, default="1")
group = fields.Char(string="Grupė", compute="_compute_group", store=True)
height = fields.Float(string="Ūgis", required=False)
weight = fields.Float(string="Svoris", required=False)
id_number = fields.Integer(string="Registravimo Nr", required=True)
#api.constrains('id_number')
def _check_id_number_field(self):
for i in self:
if i.id_number < 10:
raise ValidationError("Number is to small")
and i'm also having this
WARNING -Kindegarden odoo.models.schema: Table 'kindergarten_model': unable to set a NOT NULL constraint on column 'id_number' !
If you want to have it, you should update the records and execute manually:
ALTER TABLE kindergarten_model ALTER COLUMN id_number SET NOT NULL
Like mentioned above, it looks like it is some data are null already before you set required parameter to true.
odoo has a shell you can use to access your DB if you are not familiar with SQL.
odoo-bin -d <database_name> shell
inside the shell, do as follow so you will see.
>> records = env['kindergarten.model'].search([('id_number','=',False)])
>> len(records)
if it returns a number aside from 0, it means that those are NULL value. so do like.
>> for record in records:
record.write({'id_number': 0.0})
>>env.cr.commit()
Then update your module again.
If this doesn't work you will need to do it manually with SQL.
Did you add constraint after few records were added ?
The error you got generally comes when postgres is unable to set "NOT NULL" to the column because it already has null values
i cant really understand what is the problem i have this model :
class Upload_files(models.Model): #uploaded files(for approval) are stored here
file=models.FileField(upload_to=""+strftime("%j", gmtime())+"/")
cont = models.ForeignKey(Contractor)
def __unicode__(self):
return self.file.name
and the form :
class uploadFile(forms.ModelForm):
file = forms.FileField(label=(u'file'))
cont = forms.ModelChoiceField(label="cont",
queryset=Contractor.objects.all(),
required = False
)
and in the method that i create in it the object :
cont = Contractor.objects.get(id=contractor_id)
file = Upload_files.objects.create(file=file,cont=cont)
file.save()
and thats the error that i get :
shoghlanah_upload_files has no column named cont_id
i cant really understand whats wrong with my code so please any ideas ?
You need to either delete your database and recreate it using syncdb, or setup south and run a migration on your current database.
I have written code for managing conditional insert/update/delete to
multiple tables from single form in 'web2py'.
I agree, the code is in very raw form & may not be ‘pythonic’.
There are code repeatitions.
But at least I have something to go ahead & build a refined
structure.
MODELS:
db.define_table('mdlmst',
Field('mdlmstid','id'),
Field('mdlmstcd'),
Field('mdlmstnm'),
migrate=False,
format='%(mdlmstnm)s'
)
db.define_table('wrmst',
Field('wrmstid','id'),
Field('wrmstcd'),
Field('wrmstnm'),
migrate=False,
format='%(wrmstnm)s'
)
db.define_table('extwrmst',
Field('extwrmstid','id'),
Field('extwrmstcd'),
Field('extwrmstnm'),
migrate=False,
format='%(extwrmstnm)s'
)
from the FORM, data will be populated in the following two tables
db.define_table('mdlwr',
Field('mdlwrid','id'),
Field('mdlmstid',db.mdlmst),
Field('wrmstid',db.wrmst),
migrate=False
)
db.define_table('mdlextwr',
Field('mdlextwrid','id'),
Field('mdlmstid',db.mdlmst),
Field('extwrmstid',db.extwrmst),
migrate=False
)
CONTROLLERS:
‘modelwar’ controller will render the records from ‘mdlmst’ table
def modelwar():
models = db(db.mdlmst.mdlmstid>0).select(orderby=db.mdlmst.mdlmstnm)
return dict(models=models)
after clicking a particular record, ‘war_edit’ controller will
manage the tables – ‘mdlwr’ & ‘mdlextwr’
def war_edit():
mdl_id = request.args(0)
mdl_id is a variable identifying the ‘mdlmstid’ (which record to be modified)
mdl_nm = request.args(1)
mdl_nm is a variable for getting the ‘mdlmstnm’
warset = db(db.mdlwr.mdlmstid==mdl_id) # fetch a set
extwarset = db(db.mdlextwr.mdlmstid==mdl_id) # fetch a set
warlist = db(db.mdlwr.mdlmstid==mdl_id).select() # get a ROW object
extwarlist = db(db.mdlextwr.mdlmstid==mdl_id).select() # get a ROW object
form_war=FORM(TABLE(TR("Basic Warranty",
SELECT(_type="select",_name="baswar",*[OPTION(x.wrmstnm,_value=x.wrmstid)
for x in db().select(db.wrmst.ALL)]),
TR("Extended Warranty",
SELECT(_type="select",_name="extwar",*[OPTION(x.extwrmstnm,_value=x.extwrmstid)
for x in db().select(db.extwrmst.ALL)]),
TR("", INPUT(_type='submit',_value='Save')), ))))
pre-populate the fields in‘form_war’
if len(warlist)>0:
form_war.vars.baswar = warlist[0].wrmstid
if len(extwarlist)>0:
form_war.vars.extwar = extwarlist[0].extwrmstid
after successful form submission, manage the table 'mdlwr'
if form_war.accepts(request.vars, session):
if there was any record in the list fetched from database & sent to FORM,
if len(warlist)>0:
delete if value returned from FORM field is blank, else update
if form_war.vars.baswar==''
warset.delete()
else:
warset.update(wrmstid=form_war.vars.baswar)
else insert
else:
db.mdlwr.insert(mdlmstid=mdl_id, wrmstid=form_war.vars.baswar)
Similarly, manage the table 'mdlextwr'
if len(extwarlist)>0:
if form_war.vars.extwar=='':
extwarset.delete()
else:
extwarset.update(extwrmstid=form_war.vars.extwar)
else:
db.mdlextwr.insert(mdlmstid=mdl_id, extwrmstid=form_war.vars.extwar)
response.flash = 'Warranty definition saved'
return dict(form_war=form_war,mdlnm=mdl_nm)
VIEW for 'mdlmst' table
{{response.files.append(URL(r=request,c='static',f='jquery.dataTables.min.j
s'))}}
{{response.files.append(URL(r=request,c='static',f='demo_table.css'))}}
{{extend 'layout.html'}}
jQuery(document).ready(function()
{ jQuery('.smarttable').dataTable();});
Modelwise Warranty Master
Model IDModel CodeModel Name
{{for model in models:}}
{{=model.mdlmstid}}
{{=model.mdlmstcd}}
{{=model.mdlmstnm}}
{{=A('edit
warranty',_href=URL('war_edit',args=[model.mdlmstid,model.mdlmstnm]))}}
{{pass}}
Pl. tell me if I have coded anything stupid here.
I would highly welcome any ideas/suggestions for improvements.
Thanks,
Vineet
Your database design looks strange to me.
In each table you have a field of type 'id'. This will replace the id field automatically generated by web2py - a bad idea. From the web2py book: "Do not declare a field called "id", because one is created by web2py anyway. Every table has a field called "id" by default. It is an auto-increment integer field (starting at 1) used for cross-reference and for making every record unique, so "id" is a primary key"
You have created a many to many relationship between table 'mdlmst' and 'wrmst' and another many to many relationship between 'mdlmst' and 'extwrmst'. While this is not necessarily wrong, it strikes me as extremely unlikely this is what you want.
My feeling is that your database design needs work. This should be sorted out before you start designing forms.
I'm trying to set custom 'name' attribute in django form.
I've been trying this kind of approach:
class BaseQuestionForm(forms.Form):
question_id = forms.CharField(widget=forms.HiddenInput)
answer = forms.ChoiceField(choices = [ ... ], widget=forms.RadioSelect)
and then setting the 'name'-attr on answer with:
form.fields['answer'].widget.name = 'new_name'
But this does not work, and name is always set to 'answer' as in field name. Is there some way to do this?
First try:
print form.fields['answer'].widget.name
I believe widget doesn't have a name (ok, I am even pretty sure ;-)).
To achieve what you want, you would have to:
form.fields['new_name'] = form.fields['answer']
del form.fields['answer']
This however will move new_name field to the bottom of fields if you use simply {{ form }} in the template (this dictionary is ordered). Django builds the form fields names in template using names of the keys.