I'm working on writing the models.py file, and I need some controls to perform the automatic compilation of some fields.
MOTIVOINGRESSO = (
(u'sequestro ', u'sequestro'),
(u'fermo ', u'fermo'),
(u'confisca final ', u'confisca final'),
(u'cambio custodian ', u'cambio custodian'),
)
motivo_ingresso = models.CharField (max_length = 50, choices = MOTIVOINGRESSO)
FERMO = (
(u'30 ', u'30'),
(u'60 ', u'60'),
(u'90 ', u'90'),
(u'180 ', u'180'),
(u'1 month ', u'1 month'),
(u'3 months, 'u'3 months'),
(u'indeterminato ', u'indeterminato'),
)
durata_in_giorni_del_fermo = models.CharField (max_length = 20, choices = STOPPED, blank = True)
If the administrator the choice click 'sequestro', in durata_in_giorni_del_fermo will automatically selected 'indeterminato'.
Should I report the values entered? or machine cycles if within the models?
Any Ideas?
Its very easy if you will do it through Jquery in template. I don't know, this can be possible in models.py. Below links are much relevant to your question.
How to implement two dropdowns dependent on each other using Django and jQuery
Dynamic select fields with JQuery and django
Hoping you will got the idea about ajax and Jquery after following above links :)
Related
I had to build a dashboard , so dash seemed pretty easy. But i faced lot of issues integrating with flask or django.
So I had to rebuild the dashboard with django framework with plotly.js , while using plotly dash #app.callback() was very fast and quick in updating the graphs. To mock the similar behaviour I tried using ajax in django and plotly.js. Even though the job gets done using ajax, i see there is a lag in performance, it takes 3-4 secs to render the updated graph.
Is there a better or efficient way to achieve similar performance of dash callbacks in django/ajax ?
Just because every time i have to read the csv file during ajax call , hinders my performance ?
sample backend code for ajaxcall
def itemsAjax(request):
if request.is_ajax():
itemsList = request.POST.get('items')
#itemsList = ast.literal_eval(itemsList)
#itemsList = [n.strip() for n in itemsList]
itemsList=itemsList.split(',')
daterange = request.POST.get('daterange').split('-')
franchise = request.POST.get('franchise')
startDate = dt.strptime(daterange[0].strip(),'%m/%d/%Y')
endDate = dt.strptime(daterange[1].strip(),'%m/%d/%Y')
df = at.readData()
flag = ut.determineFlag(startDate,endDate)
df = at.filter_df_daterange(df,startDate,endDate)
itemTrend_df = at.getDataForItemsTrend(df,startDate,endDate,flag)
itemTrend_plt = [{'type':'scatter',
'x' : itemTrend_df[itemTrend_df['S2PName']==item]['S2BillDate'].tolist(),
'y' : itemTrend_df[itemTrend_df['S2PName']==item]['totSale'].tolist(),
#'text' : itemTrend_df[itemTrend_df['S2PName']==item]['Hover'],
'mode' : 'markers+lines',
'name' : item
}for item in itemsList]
return JsonResponse({'itemTrend_plt':itemTrend_plt})
else:
return HttpResponse(' Not authorised!')
I want to override fields_view_get of odoo to add groups to fields dynamically based on a condition.
#api.model
def fields_view_get(self, view_id=None, view_type='form', toolbar=False, submenu=False):
res = super(client_quote, self).fields_view_get(view_id=view_id, view_type=view_type, toolbar=toolbar,
submenu=submenu)
"""update this method to change the string of fields in different tab of client quote if it changes from vfx sheet """
if view_type == 'form' and ('vfx_shots_ids' in res['fields']):
for field in res['fields']['vfx_shots_ids']['views']['tree']['fields']:
if self._context.get('quote_id'):
vfx_quote_id = self.env['vfx.quote'].browse(self._context['quote_id'])
field_id = self.env['field.name'].search([('name', '=', field)])
if field_id:
line_id = self.env['mapping.template.line'].search([('template_id', '=', vfx_quote_id.template_id.id),
('field_id', '=', field_id.id),
('model_name', '=', 'vfx.shots')
])
if line_id:
string = line_id.heading_id.name
res['fields']['vfx_shots_ids']['views']['tree']['fields'][field]['string'] = _(string)
res['fields']['vfx_shots_ids']['views']['tree']['fields'][field]['groups'] = str('vfx_quote_template.group_empty_fields')
return res
This is my class and fields, i want to change vfx_quote_template.group_executive_producer group based of a condition.
Currently fields_view_get code seems to have no effect.
class vfx_shots(models.Model):
_name = 'vfx.shots'
item_number = fields.Char('Item',groups="vfx_quote_template.group_executive_producer")
You have to use lxml library to modify the XML architecture of the view in the fields_view_get() method.
You can also override the fields definition by overriding the fields_get() method.
You can get examples here : https://bazaar.launchpad.net/~unifield-team/unifield-server/trunk/view/head:/bin/addons/consumption_calculation/history_consumption.py#L457
I know it is in v6 version of the code, but the fields_view_get behavior didn't change a lot since this version.
I have a python script using exiftool to update the meta data within a given PDF. The documentation and download for the exiftool can be found here: PyExifTool
Below is my current code:
if __name__ == '__main__':
from exif_tool import ExifTool, fsencode
source_file = 'D:\\my_file.pdf'
author = 'some author'
keywords = 'some keywords'
subject = 'some subject'
title = 'some title'
with ExifTool('exiftool.exe') as et:
params = map(fsencode, ['-Title=%s' % title,
'-Author=%s' % author,
'-Creator=%s' % author,
'-Subject=%s' % subject,
'-Keywords=%s' % keywords,
'%s' % source_file])
et.execute(*params)
os.remove('%s_original' % source_file)
for key, value in dict(et.get_metadata(source_file)).items():
if key.startswith('PDF:') and ('Author' in key or 'Keywords' in key or 'Title' in key or 'Subject' in key):
print key, value
>>> PDF:Keywords [u'some', u'keywords']
>>> PDF:Title some title
>>> PDF:Subject some subject
>>> PDF:Author some author
The above code works and updates the PDF meta data accordingly. However , when I go to view the PDF meta within Adobe Acrobat or Adobe Reader, the values for both Subject and Keywords are being displayed within the Keyword field.
Over all, this will not be a critical issue in most cases, but I can foresee receiving many complaints over this.
I may just be missing some small configuration or setting, but I have read through the documentation and I have not been able to find anything to get around this.
Does anybody have any thoughts or ideas?
I was able to find a solution to fix this, and this is what I came up with. In order to prevent the Subject and Keywords from being combined within the Keyword field, there are a few more tags that need to be updated using Exiftool.
params = map(fsencode, ['-PDF:Subject=%s' % subject,
'-XMP:Subject=',
'-PDF:Title=%s' % title,
'-XMP:Title=',
'-PDF:Author=%s' % author,
'-XMP:Author=',
'-PDF:Keywords=%s' % keywords,
'-XMP:Keywords=',
'-overwrite_original',
'%s' % source_file])
models.py (derived from existing db)
class IceCreamComponent(models.Model):
name = models.CharField
#can be 'flavor', 'nut', etc
class IceCream(models.Model):
name = models.CharField
component = models.ForeignKey(IceCreamComponent)
value = models.CharField #will correspond to the component
The context behind this database is that 'IceCream' reports will come in from someone who's only purpose is to report back on a certain component (i.e. my 'extras' reporter will report the name of the ice cream and the extra it contained). It is assumed that all needed reports are in the db when queried so that something like:
IceCreams = IceCream.objects.values('name', 'component__name', 'value')
will return something akin to:
[
{'name': 'Rocky road', 'component__name': 'ice cream flavor', 'value':'chocolate'},
{'name': 'Rocky road', 'component__name': 'nut', 'value':'almond'},
{'name': 'Rocky road', 'component__name': 'extra', 'value':'marshmallow'},
{'name': 'Vanilla Bean', 'component__name': 'ice cream flavor', 'value':'vanilla'},
{'name': 'Vanilla Bean', 'component__name': 'extra', 'value':'ground vanilla bean'},
]
However, as you can imagine something like:
[
{'name': 'Rocky Road', 'ice cream flavor': 'chocolate', 'nut': 'almond', 'extra':'marshmallow' },
{'name': 'Vanilla Bean', 'ice cream flavor': 'vanilla', 'extra':'ground vanilla bean'}
]
is much more usable (especially considering I'd like to use this in a ListView).
Is there a better way to query the data or will I need to loop through the ValuesQuerySet to achieve the desired output?
Can't you reconstruct the list from the original result?
results = []
for row in vqueryset:
converted_row = {}
converted_row[row['component__name']] = row['value']
converted_row['name'] = row['name']
results.append(converted_row)
Of course you would want to paginate the original result before evaluating it (turning it into a list).
oh, you asked if there's a better way. I'm doing it this way because I couldn't find a better way anyway.
Here is the solution I came up with.
processing = None
output = []
base_dict = {}
for item in IceCreams:
# Detect change current site code from ordered list
if item['name'] != processing:
processing = item['name']
# If base_dict is not empty add it to our output (only first one)
# TODO see if there's a better way to do first one
if base_dict:
output.append(base_dict)
base_dict = {}
base_dict['name'] = item['name']
base_dict[item['component__name']] = item['value']
I have an action in my controller to create a new page which is one of my models.
Afterwards, I want to clear out the form and transition to the new page.
Here is my code:
App.ApplicationController = Ember.ObjectController.extend
newSlug: (->
# some function
).property('newTitle')
newMenuName: # some property
actions:
addNewPage: ->
# Get the site
site = #get('model')
# Get all the pages associated with the site
pages = site.get('pages')
# ...
# snipped a bunch out to save space
# ...
# Create a new page passing in our title, slug and menu_name
page = pages.createRecord({title: title, slug: slug, menu_name: menu_name, menu_1: menu_1, menu_2: menu_2, menu_1_order: menu_1_order, menu_2_order: menu_2_order})
page.save().then(onSuccess, onError)
onSuccess = (page) ->
page = this.store.find('page', slug)
console.log('Slug: ' + slug + ' ' + page.slug)
#set('newTitle', '')
#set('newSlug', '')
#set('newMenuName', '')
$('#addPageModal').foundation('reveal', 'close')
#transitionToRoute('page', page)
But I'm getting the error that this has no method set. I have even tried using self = this but it gives me the same error.
Any thoughts?
BTW, in case you're wondering, inside onSuccess, page is not defined, so I have to look it up again. I thought a promise was supposed to return the data sent back from the API.
EDIT:
I must look like a total imbecile, but once again, right after posting a question here, I find (part) of the answer myself. Turns out in CoffeeScript (so far I'm not a big fan of it in combination with Ember.js) I needed the => so my callback function becomes:
onSuccess = (page) =>
page = this.store.find('page', slug)
console.log('Slug: ' + slug + ' ' + page.slug)
#set('newTitle', '')
#set('newSlug', '')
#set('newMenuName', '')
$('#addPageModal').foundation('reveal', 'close')
#transitionToRoute('page', page)
However, page is still not defined. Not sure what to do about that.
EDIT:
And the correct answer is....
App.ApplicationController = Ember.ObjectController.extend
newSlug: (->
# some function
).property('newTitle')
newMenuName: # some property
actions:
addNewPage: ->
# Get the site
site = #get('model')
# Get all the pages associated with the site
pages = site.get('pages')
# ...
# snipped a bunch out to save space
# ...
onSuccess = (page) ->
#set('newTitle', '')
#set('newSlug', '')
#set('newMenuName', '')
$('#addPageModal').foundation('reveal', 'close')
#transitionToRoute('page', page.get('slug'))
# And just for completeness
onError = (page) =>
# Do something
# Create a new page passing in our title, slug, menu_name, etc.
page = pages.createRecord({title: title, slug: slug, menu_name: menu_name, menu_1: menu_1, menu_2: menu_2, menu_1_order: menu_1_order, menu_2_order: menu_2_order})
page.save().then(onSuccess, onError)