Odoo v7 to v8 translation - python-2.7

I am converting OpenERP code from version 7 to version 8 and I have come across a weird structure. In version 7 we can use fields, function and one of the attributes is store. The store function allows current field to be updated when fields of other objects are changed.
In the new API, the store function only accepts 'True' or 'False'. I was wondering if I have inherit other models and modify their fields so they perform a value update of model in question using "onchange"

Nope, in Odoo 8 store function is working fine. you can search add-ons and find some interesting examples, Understand from it.
Some example I found in online
[http://www.odoo.yenthevg.com/saving-and-resizing-images-in-odoo-8/]
go through it.

In v8 their is no fields.function field and with that we also do not need store with fields pararms, but you can achieve same thing very easily by using [#depends][1] decorator , which does same thing as store with field does.
```
#openerp.api.depends(*args)
Return a decorator that specifies the field dependencies of a "compute" method (for new-style function fields).
```
so you can say that you field to be calculated on change of some field change.

Related

Python/Django model dictionary allows one type of update, but not another

I am working on some Django/Python code.
Basically, the backend of my code gets sent a dict of parameters named 'p'. These values all come off Django models.
When I tried to override them as such:
p['age']=25
I got a 'model error'. Yet, if I write:
p.age=25
it works fine.
My suspicion is that, internally, choice #1 tries to set a new value to an instance of a class created by Django that objects to being overridden, but internally Python3 simply replaces the Django instance with a "new" attribute of the same name ('age'), without regard for the prior origin, type, or class of what Django created.
All of this is in a RESTful framework, and actually in test code. So even if I am right I don't believe it changes anything for me in reality.
But can anyone explain why one type of assignment to an existing dict works, and the other fails?
p is a class, not a dict. Django built it that way.
But, as such, one approach (p.age) lets you change an attribute of the object in the class.

Specify typing for Django field in model (for Pylint)

I have created custom Django model-field subclasses based on CharField but which use to_python() to ensure that the model objects returned have more complex objects (some are lists, some are dicts with a specific format, etc.) -- I'm using MySQL so some of the PostGreSql field types are not available.
All is working great, but Pylint believes that all values in these fields will be strings and thus I get a lot of "unsupported-membership-test" and "unsubscriptable-object" warnings on code that uses these models. I can disable these individually, but I would prefer to let Pylint know that these models return certain object types. Type hints are not helping, e.g.:
class MealPrefs(models.Model):
user = ...foreign key...
prefs: dict[str, list[str]] = \
custom_fields.DictOfListsExtendsCharField(
default={'breakfast': ['cereal', 'toast'],
'lunch': ['sandwich']},
)
I know that certain built-in Django fields return correct types for Pylint (CharField, IntegerField) and certain other extensions have figured out ways of specifying their type so Pylint is happy (MultiSelectField) but digging into their code, I can't figure out where the "magic" specifying the type returned would be.
(note: this question is not related to the INPUT:type of Django form fields)
Thanks!
I had a look at this out of curiosity, and I think most of the "magic" actually comes for pytest-django.
In the Django source code, e.g. for CharField, there is nothing that could really give a type hinter the notion that this is a string. And since the class inherits only from Field, which is also the parent of other non-string fields, the knowledge needs to be encoded elsewhere.
On the other hand, digging through the source code for pylint-django, though, I found where this most likely happens:
in pylint_django.transforms.fields, several fields are hardcoded in a similar fashion:
_STR_FIELDS = ('CharField', 'SlugField', 'URLField', 'TextField', 'EmailField',
'CommaSeparatedIntegerField', 'FilePathField', 'GenericIPAddressField',
'IPAddressField', 'RegexField', 'SlugField')
Further below, a suspiciously named function apply_type_shim, adds information to the class based on the type of field it is (either 'str', 'int', 'dict', 'list', etc.)
This additional information is passed to inference_tip, which according to the astroid docs, is used to add inference info (emphasis mine):
astroid can be used as more than an AST library, it also offers some
basic support of inference, it can infer what names might mean in a
given context, it can be used to solve attributes in a highly complex
class hierarchy, etc. We call this mechanism generally inference
throughout the project.
astroid is the underlying library used by Pylint to represent Python code, so I'm pretty sure that's how the information gets passed to Pylint. If you follow what happens when you import the plugin, you'll find this interesting bit in pylint_django/.plugin, where it actually imports the transforms, effectively adding the inference tip to the AST node.
I think if you want to achieve the same with your own classes, you could either:
Directly derive from another Django model class that already has the associated type you're looking for.
Create, and register an equivalent pylint plugin, that would also use Astroid to add information to the class so that Pylint know what to do with it.
I thought initially that you use a plugin pylint-django, but maybe you explicitly use prospector that automatically installs pylint-django if it finds Django.
The checker pylint neither its plugin doesn't check the code by use information from Python type annotations (PEP 484). It can parse a code with annotations without understanding them and e.g. not to warn about "unused-import" if a name is used in annotations only. The message unsupported-membership-test is reported in a line with expression something in object_A simply if the class A() doesn't have a method __contains__. Similarly the message unsubscriptable-object is related to method __getitem__.
You can patch pylint-django for your custom fields this way:
Add a function:
def my_apply_type_shim(cls, _context=None): # noqa
if cls.name == 'MyListField':
base_nodes = scoped_nodes.builtin_lookup('list')
elif cls.name == 'MyDictField':
base_nodes = scoped_nodes.builtin_lookup('dict')
else:
return apply_type_shim(cls, _context)
base_nodes = [n for n in base_nodes[1] if not isinstance(n, nodes.ImportFrom)]
return iter([cls] + base_nodes)
into pylint_django/transforms/fields.py
and also replace apply_type_shim by my_apply_type_shim in the same file at this line:
def add_transforms(manager):
manager.register_transform(nodes.ClassDef, inference_tip(my_apply_type_shim), is_model_or_form_field)
This adds base classes list or dict respectively, with their magic methods explained above, to your custom field classes if they are used in a Model or FormView.
Notes:
I thought also about a plugin stub solution that does the same, but the alternative with "prospector" seems so complicated for SO that I prefer to simply patch the source after installation.
Classes Model or FormView are the only classes created by metaclasses, used in Django. It is a great idea to emulate a metaclass by a plugin code and to control the analysis simple attributes. If I remember, MyPy, referenced in some comment here, has also a plugin mypy-django for Django, but only for FormView, because writing annotations for django.db is more complicated than to work with attributes. - I was trying to work on it for one week.

Prestashop admin orders controller

I would like to ask about this controller.
In past versions like 1.5 I could find it in admin/tabs and add additional functions.
In 1.6 version I can`t find any admin classes files. So I should edit controllers/admin/AdminOrdersController yes?
elseif(isset($_POST['submitInvoice'])){
if ($this->tabAccess['edit'] === '1')
{
mysql_query('UPDATE `'._DB_REFIX_.'orders` SET `invoice_number` = \''.$_POST['invoice_number'].'\',`order_date` = \''.$_POST['order_date'].'\', `changed_invoice`=1, `manager`=\''.$cookie->firstname.' '.$cookie->lastname.'\', `changedStatus`= \''.$_POST['changedStatus'].'\' WHERE `id_order` = '.$_GET['id_order']);
}
}
I add this code to update some values like invoice number or order date. But I can`t to update this. Got same date and number. Is it bad method to update or what?
You should always use modules and hooks to modify PrestaShop logic if possible
If you need to override a function and there is nor suitable hook, you should use overrides: override/controllers/admin/AdminOrderController.php. Contents of this files should look like : AdminOrderController extends AdminOrderControllerCore. If you're unsure what I mean, you should try searching for any override classes in overide folder.
You code is extremely unsafe. You should at least use Db::getInstance()->execute($sql);.
You code might not be working because you are writing you values somewhere in the middle of a function, and the Order is an object, which mean that possibly the Order object is saved after you wrote you values to database. When the order object is saved, it overwrites your values

When are Strong Parameters used?

I understand strong parameters are used in cases where we are creating an object and putting it into our database. For example,
User.create(params[:user]) would have to be User.create(params.require(:user).permit(:name, :email, :password).
This is standard and simple to understand, however, are strong parameters required when updating a column or a few attributes in a model?
current_user.update_attributes(params[:user]). Does that have to be current_user.update_attributes(params.require(:user).permit(:name, :email, :password).
Lastly, I don't think it is needed for this case:
current_user.update_column(authentication_token: nil), but would it have needed to be updated if instead we had params = { authentication_token: nil }, and did current_user.update_column(params)?
Any time you pass an instance of ActionController::Parameters to one of the mass assignment apis (new, create, update_attributes, update etc.) you need to permit the appropriate fields.
In a controller the params method returns an instance of ActionController::Parameters, as are any hashes contained within it, so you need to use permit.
If you do
params = { foo: bar }
record.update_attributes(params) or
record.update_attributes(foo: bar)
Then you're passing a normal hash and so you don't need to use permit
Are strong parameters required when updating a column or a few
attributes in a model?
Yes, if the model is being updated with values from the end-user. Never trust the user input.
Suppose the current_user model has a 'role_id' column, which could be 1 for super user, 2 for normal user and 3 for guest. If you don't sanitize the parameters, the end-user could easily forge a request to gain privileges and compromise your application security.
Regarding your last question, you're right. You don't need strong parameters to update the record with values you already know.
I experimented on Rails 4 environment with both update and update_attributes method calls, and I received identical errors for both method calls: ActiveModel::ForbiddenAttributesError in PeopleController#update . In the controller I used #person.update(params[:person]) and #person.update_attributes(params[:person]); so that’s why it says PeopleController in the error message.
Based on the API documentation, it looks like in Rails 4 update_attributes is alias for update. So I guess update_attributes does the same thing as update method in Rails 4:
update_attributes(attributes) public
Alias for ActiveRecord::Persistence#update
Therefore, both update and update_attributes methods have to use strong parameters to update database. I also tested update_attributes method with strong parameters: #person.update_attributes(person_parameters) and it worked
updated
About update_attribute and update_column methods. I just tested those for the very first time through a controller, and with those methods you don’t need to use strong parameters inside of controller ( which was a bit surprise to me), even when you are using params (user provided values). So with update_attribute and update_column methods you can update database without using strong parameters.

Getting error while reading salesforce custom field type Rich Textarea

I am using salesforce.cfc (downloded from Riaforge) to integrate coldfusion with salesforce.
<cfset latestProductList = salesforce.queryObject("SELECT Id, Name, Description__c, Price__c, ProductImage__c FROM Product__c") />
I have created one custom object named "Product__c". This object have one custom field "ProductImage__c" type "Rich TextArea". When i an trying to get product without this custom field it is run, but when i am trying to get product with this field i am getting below error:
"INVALID_FIELD: Name, Description__c, Price__c, ProductImage__c FROM Product__c ^ ERROR at Row:1:Column:44 No such column 'ProductImage__c' on entity 'Product__c'. If you are attempting to use a custom field, be sure to append the '__c' after the custom field name. Please reference your WSDL or the describe call for the appropriate names. "
But i have this field. attached screen image of salesforce below.
Thanks,
Arun
A quick look at Salesforce CFC shows that it hasn't been updated in a while. The file SalesForce.cfc is pointing at:
https://www.salesforce.com/services/Soap/u/11.1
That's version 11.1 of the API, which is quite old and is long before rich text fields came into existence.
You might be able to fix this issue by simply updating the reference in SalesForce.cfc to the latest version of the API by changing
https://www.salesforce.com/services/Soap/u/11.1
to
https://www.salesforce.com/services/Soap/u/28.0
in that file, although there's a pretty good likelihood that that will break something else, since version 28.0 will have lots of new stuff that SalesForce.cfc is not coded to handle.
In any case, your problem is in fact the API version that you're using. In cases like this, when a field type did not exist as of a certain API version, then that field is invisible for that version. In your case, your rich text field is invisible for your API version, 11.1.