inherit product_id_change and add new argument odoo 8 - odoo-8

i'm working on sale.order.line ,adding new field lot
lot = fields.Many2one('stock.production.lot','lot')
and i want pass this field as argument into an inherited method (onchange on quantity )
def product_id_change(self, cr, uid, ids, pricelist, product, qty=0,
uom=False, qty_uos=0, uos=False, name='', partner_id=False,
lang=False, update_tax=True, date_order=False, packaging=False,
fiscal_position=False, flag=False, lot=False,context=None):
res = super(order_line, self).product_id_change(cr, uid, ids,
pricelist, product,
qty,uom, qty_uos,
uos, name, partner_id,
lang, update_tax,
date_order, packaging,
fiscal_position,
flag, context=context)
if product:
print "----------------------------------------------"
print lot
print "----------------------------------------------"
# res['value']['changement_prix'] = lot.change_prix
# res['value']['old_price'] = res['value']['price_unit']
# res['value']['price_unit'] = res['value']['old_price'] + lot.change_prix
return res
but all i got in my print is False for lot
so im wondering how to pass lot as argument on this function
thnx

You can not pass new argument this way in function.
Its call super method of object, it will create problem in the super method also. So either you can pass lot in context for xml side,
like
<field name="product_id"
context="{'partner_id':parent.partner_id,
'quantity':product_uom_qty,
'pricelist':parent.pricelist_id,
'uom':product_uom, 'company_id': parent.company_id,
'lot': lot}" <======
groups="base.group_user"
on_change="product_id_change(parent.pricelist_id, product_id, product_uom_qty, False, product_uos_qty, False, name, parent.partner_id, False, True, parent.date_order, False, parent.fiscal_position, False, context)"/>
So in context you get you passed the lot.
lot = context.get('lot')
in python side you get from context and done your code.
Otherwise you have to overwrite whole function of onchange in your new modules
change in xml side for arguements of onchange
Hope this will help you.

well i couldnt get lot by context
so i made an invisible field many2one in product.product
and save it there .
than get it back later by browsing my product
thnx

Related

Fill the date field (today date) automatically o when you access to a view

I want to change the value of field ( that changes to the date of the day for example)
automatically or when you access an already created view the action is generate in odoo13.
Thaks
You should use fields_view_get method, it will fired with every type of view, if you need it when a form is open you can do something like this:
#api.model
def fields_view_get(self, view_id=None, view_type='form', toolbar=False, submenu=False):
res = super(Movimiento, self).fields_view_get(
view_id=view_id, view_type=view_type, toolbar=toolbar, submenu=submenu
)
if view_type == 'form':
# Get today date
today = fields.Date.context_today(self)
# update your field here.
return res
I hope this answer can be helpful for you.

Django Rest Framework "This field is required" only when POSTing JSON, not when POSTing form content

I'm getting a strange result whereby POSTing JSON to a DRF endpoint returns:
{"photos":["This field is required."],"tags":["This field is required."]}'
Whereas when POSTing form data DRF doesn't mind that the fields are empty.
My model is:
class Story(CommonInfo):
user = models.ForeignKey(User)
text = models.TextField(max_length=5000,blank=True)
feature = models.ForeignKey("Feature", blank=True, null=True)
tags = models.ManyToManyField("Tag")
My serializer is:
class StorySerializer(serializers.HyperlinkedModelSerializer):
user = serializers.CharField(read_only=True)
def get_fields(self, *args, **kwargs):
user = self.context['request'].user
fields = super(StorySerializer, self).get_fields(*args, **kwargs)
fields['feature'].queryset = fields['feature'].queryset.filter(user=user)
fields['photos'].child_relation.queryset = fields['photos'].child_relation.queryset.filter(user=user)
return fields
class Meta:
model = Story
fields = ('url', 'user', 'text', 'photos', 'feature', 'tags')
And my api.py is:
class StoryViewSet(viewsets.ModelViewSet):
serializer_class = StorySerializer
def get_queryset(self):
return self.request.user.story_set.all()
def perform_create(self, serializer):
serializer.save(user=self.request.user)
The results:
# JSON request doesn't work
IN: requests.post("http://localhost:8001/api/stories/",
auth=("user", "password",),
data=json.dumps({'text': 'NEW ONE!'}),
headers={'Content-type': 'application/json'}
).content
OUT: '{"photos":["This field is required."],"tags":["This field is required."]}'
# Form data request does work
IN: requests.post("http://localhost:8001/api/stories/",
auth=("user", "password",),
data={'text': 'NEW ONE!'},
).content
OUT: '{"url":"http://localhost:8001/api/stories/277/","user":"user","text":"NEW ONE!","photos":[],"feature":null,"tags":[]}'
The issue here isn't obvious at first, but it has to do with a shortcoming in form-data and how partial data is handled.
Form data has two special cases that Django REST framework has to handle
There is no concept of "null" or "empty" data for some inputs, including checkboxes and other inputs that allow for multiple selections.
There is no input type that supports multiple values for a single field, checkboxes being the one exception.
Both of these combine together to make it difficult to handle accepting form data within Django REST framework, so it has to handle a few things differently from most parsers.
If a field is not passed in, it is assumed to be None or the default value for the field. This is because inputs with no values are not passed along in the form data, so their key is missing.
If a single value is passed in for a multiple-value field, it will be treated like the one selected value. This is because there is no difference between a single checkbox selected out of many and a single checkbox at all in form data. Both of them are passed in as a single key.
But the same doesn't apply to JSON. Because you are not passing an empty list in for the photos and tags keys, DRF does not know what to give it for a default value and does not pass it along to the serializer. Because of this, the serializer sees that there is nothing passed in and triggers the validation error because the required field was not provided.
So the solution is to always provide all keys when using JSON (not including PATCH requests, which can be partial), even if they contain no data.

How to get Pylons formencode validator to ignore some fields

I have a form that has some input text boxes and well as some select boxes. I have validation working perfectly on the textboxes. I don't care if any of the select boxes are left defualt or not, but everytime I submit the form it goes to a pylons error page saying "Invalid: Please enter value for ..." But I don't want that to happen.
here is my validator function:
class Registration(formencode.Schema):
allow_extra_fields=True
first_name = formencode.validators.String(strip=True, not_empty=True)
last_name = formencode.validators.String(strip=True, not_empty=True)
address = formencode.validators.String(strip=True, not_empty=True)
phone = formencode.validators.PhoneNumber(strip=True, not_empty=True)
email = formencode.validators.Email(resolve_domain=True, not_empty=True)
messages = {
'tooLow': "You must be at least 18 in order to register for an event.",
'tooHigh': "You obviously are not that old. Please enter your actual age.",
}
age = formencode.validators.Int(min=18, max=999, not_empty=True, messages=messages)
I thought with allow_extra_fields = True it would allow for fields in the form that aren't supplied in the function to pass if left blank/default. I have select boxes named heard, frequency, and level that should be ignored.
Any help here would be greatly appreciated.
On your formencode.validators methods:
Use not_empty=False if your form is submitting the fields and the values are empty strings. The param not_empty false is how you say: empty is a valid value.
If the fields do not exist then use if_missing = None which will set your result to None.
I think you should add the following line to it
filter_extra_fields = True

Grails Sorting Issue

I have a grails app developed.
Herein, I have a page which accepts data and as per the data . goes to the list action, fires an sql, populates the data into reconciliationInstance object and displays it in list.gsp.
In my list.gsp, I have,
<g:sortableColumn property="access"
title="${message(code: 'reconciliationInstance.access.label', default: 'Access')}"
style="width: 10px" defaultOrder="desc"/>
However, when I click on the "Amount" heading, it takes me back to the list action again.
I have around 15 columns in the page and want to have sorting for all of them.
Am I missing something here??
To rectify this issue ,I wrote the below code.
Redirected to action sort. But theres something wrong here I believe.
def sort = {
if (!params.sort) params.sort = "title"
if (!params.order) params.order = "asc"
def reconciliationInstanceList = new ArrayList<Reconciliation>()
reconciliationInstanceList=session["reconciliationInstanceList"]
order(params.sort, params.order)
[reconciliationInstanceList: reconciliationInstanceList]
}
I have saved reconciliationInstanceList in a session.
Any Advice/Inputs?
My list action code is as below.
def list ={
//Taking parameters entered in the previous page
def odcNum=params.odcNum
def odcDate=params.odcDate
def date=null
def reconciliationInstance = new Reconciliation()
reconciliationInstance.properties=params
//Validation if all parameters have been entered by the user
if (reconciliationInstance.validate()) {
def results
SimpleDateFormat sdfSource = new SimpleDateFormat("dd-MMM-yyyy")
if(odcDate instanceof Date) {
date = sdfSource.format(odcDate);
}else{
date = odcDate
}
//Query to be fired. I have altered this query a bit. My actual query returns around 15 parameters
String odcData="select odc_access from odc_manager where odc_date=to_char('" + date + "') and odc_num like trim('" + odcNum + "')"
def reconciliationInstanceList = new ArrayList<Reconciliation>()
Sql sql = new Sql(dataSource)
results = sql.eachRow (odcData)
{
def reconciliation = new Reconciliation()
reconciliation.setAccess it.access
reconciliationInstanceList.add reconciliation
session["reconciliationInstanceList"]=reconciliationInstanceList
}
[reconciliationInstanceList: reconciliationInstanceList]
}
else {
render(view: "search", model: [reconciliationInstance: reconciliationInstance])
}
}
BTW I am a novice at grails. Therefore, you would find a bit of java in my code.
Somethings missing in my code? Therefore sort doesnt work. Inputs?
it should take you back to the list action, but the params passed to the action will let it know how to sort the resulting model.
the behavior is correct, I assume your code in the list action is not coded properly... You might want to include that code if you want additional guidance.
See sample list action
http://www.grails.org/GSP+Tag+-+sortableColumn
Found a work around for this. Passed the sort order (params.order) to the sql query and let the query do the sorting. Displayed the results on the gsp then.
If there's any other way, do let me know.

How to remember results from querying SQLAlchemy relations (to implement caching)?

Suppose I have a mapped class Article. It has a relation category that does a query each time I access it (article.category would issue a query to get the category or article).
How do I proxy the article.category call so that the result is queried from the database, then remembered and then returned?
Thanks, Boda Cydo.
Does SA really issue a query every time you access the relation in the same session? IMO, it should not happen, as the result should get cached automatically within the session.
In order to check that no SQL is issued, just turn on logging and see for yourself:
metadata.bind.echo = 'debug'
c = session.query(Child).first() # issues SELECT on your child table(s)
print "child: ", c
print "c.parent: ", c.parent # issues SELECT on your parent table, then prints
print "c.parent: ", c.parent # just prints (no SQL)
print "c.parent: ", c.parent # just prints (no SQL)
Shall your code work otherwise by default, please provide code snippet.
In case you really just need to cache the result, see below (very similar solution to another question you posted):
class MyChild(Base):
__tablename__ = 'MyChild'
id = Column(Integer, primary_key=True)
parent = relation('Parent')
# ... other mapped properties
def __init__(self):
_parent_cached = None
#property
def parent_cached(self):
if self._parent_cached is None:
self._parent_cached = self.parent
But in order to have the result when your object is detached from the session you must call this property before detaching. (Also it does not handle situation when the parent is None. Do you always have parent?).
The option with eager load is simplier and once you load the object, you should have the relation loaded already (key is to have lazy=False):
class MyChild(Base):
__tablename__ = 'MyChild'
id = Column(Integer, primary_key=True)
parent = relation('Parent', lazy=False)
# ... other mapped properties
...

Resources