What makes an on-change functions before clicking? - odoo-8

Please, i work with on_change and get_inputs.
Here is my code:
PYTHON:
def get_inputs(self, cr, uid,ids, convention_id, company_id, context=None):
ret = []
if convention_id == False:
My_error_Msg = 'Please, select your CONVENTION'
raise osv.except_osv(_("Error!"), _(My_error_Msg))
return False
else:
obj = self.pool.get('seetek.convention.categorie.line')
obj_ids = obj.search(cr, uid, [('convention_id', '=', convention_id)])
res = obj.read(cr, uid, obj_ids, ['nom','nature','id'], context)
for r in res :
inputs = {
'company_convention_categorie_id': r['id'],
'company_id': company_id,
'nom': r['nom'],
'nature': r['nature'],
'actif': True,
}
ret.append(inputs)
return ret
def on_change_convention_id(self, cr, uid, ids, convention_id, company_id, context=None):
res = {'value':{line_ids': self.get_inputs(cr, uid, ids, convention_id, company_id, context=context),
}
}
return res
XML:
<field name="convention_ids" on_change="on_change_convention_id(convention_ids,company_ids)" attrs="{'invisible': [('company_ids','=',False)]}"/>
My question is that, before i click on the convention_ids field the get_inputs functions and give me all the values??
Please, who can help?!

I have found the solution to my problem.
In fact the get_inputs function was perfect and there was no problem.
The issue that makes the problem coming is in the on_change.
Si i have changed it to the code bellow and it works perfectly:
def on_change_conventions_id(self, cr, uid, ids, convention_id, company_id, context=None):
if company_id == False:
My_error_Msg = 'Please, select your COMPANY'
raise osv.except_osv(_("Error!"), _(My_error_Msg))
else:
print company_id
print convention_id
res = {'value':{'seetek_line_ids': self.get_inputs(cr, uid, ids, convention_id, company_id, context=context),
}
}
return res
Thanks a lot & Regards :)

Related

Get values from nested hash

I have this Hash that I use store values and if the values are not found to get default values:
AMOUNT = {
EUR: {
eps: { AT: 1_00 },
safetypay: { PE: 15_000_00, CR: 5_000_00, BE: 15_000_00, },
przelewy24: 5_00,
qiwi: 5_00,
bcmc: { AT: 1_00, BE: 1_00 },
giropay: { DE: 1_00 },
ideal: { NL: 1_00 },
mybank: { IT: 1_00, FR: 1_00 },
},
CZK: {
trustpay: { CZ: 20_00 }
}
}.with_indifferent_access
I would like to get values based on the keys so I tried this:
def amount_for(payment_type, country, currency)
payment_amount = AMOUNT.dig(currency, payment_type, country) if payment_type.is_a?(Hash)
payment_amount ||= AMOUNT.dig(currency, payment_type)
payment_amount ||= 1
end
But I get for result not number but {"AT"=>100, "BE"=>100}. If I remove the check if payment_type.is_a?(Hash) I get exception Integer does not have #dig method (RuntimeError)
Do you know how I can solve this issue?
payment_type will be e.g. "AT" - it's the argument you pass into your function, it will never be a Hash.
This rewrite should do what you want:
def amount_for(payment_type, country = nil, currency = nil)
path = [payment_type, country, currency].compact
obj = AMOUNT
obj = obj[path.shift] while Hash === obj && !path.empty?
return obj || 1
end
Alternately, this is rather similar to the code you wrote:
def amount_for(payment_type, country = nil, currency = nil)
tmp = AMOUNT.dig(payment_type, country, currency)
return tmp if tmp
tmp = AMOUNT.dig(payment_type, country)
return tmp if tmp
tmp = AMOUNT.dig(payment_type)
return tmp if tmp
return 1
end

django rest framework:In Serializer how to show the field properties also

I have model:
class Ingredient(models.Model):
KILOGRAM = 'kg'
LITER = 'ltr'
PIECES = 'pcs'
MUNITS_CHOICES = (
(KILOGRAM, 'Kilogram'),
(LITER, 'Liter'),
(PIECES, 'Pieces'),
)
name = models.CharField(max_length=200,unique=True,null=False)
slug = models.SlugField(unique=True)
munit = models.CharField(max_length=10,choices=MUNITS_CHOICES,default=KILOGRAM)
rate = models.DecimalField(max_digits=19, decimal_places=2,validators=[MinValueValidator(0)],default=0)
typeofingredient = models.ForeignKey(TypeOfIngredient, related_name='typeof_ingredient',null=True, blank=True,on_delete=models.PROTECT)
density_kg_per_lt = models.DecimalField(max_digits=19, decimal_places=2,verbose_name='Density (kg/lt)',null=True,blank=True,validators=[MinValueValidator(0)])
density_pcs_per_kg = models.DecimalField(max_digits=19, decimal_places=2,verbose_name='Density (pcs/kg)',null=True,blank=True,validators=[MinValueValidator(0)])
density_pcs_per_lt = models.DecimalField(max_digits=19, decimal_places=2,verbose_name='Density (pcs/lt)',null=True,blank=True,validators=[MinValueValidator(0)])
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
When i get the api i also want to get field types like char, decimal, datetime etc
Something like the below api result, is it possible. Because i am using reactJs as frontend, i have tell the input what kind of field it can accept and also helps in sorting by text or number
{
"id": {value: 1,type: number},
"name": {value: "adark",type: charfield},
"rate": {value: "12.00",type: decimal},
"updated": {value: "2017-07-14T10:51:47.847171Z",type: datetime},
.......so on
}
The Corresponding Serializer would be as follows:
class IngredientSerializer(serializers.ModelSerializer):
name = serializers.SerializerMethodField()
rate = serializers.SerializerMethodField()
updated = serializers.SerializerMethodField()
class Meta:
model = Ingredient
fields = ('name', 'rate', 'updated')
def get_name(self, obj):
response = dict()
response['value'] = obj.name
response['type'] = obj.name.get_internal_type()
return Response(response)
def get_rate(self, obj):
response = dict()
response['value'] = obj.rate
response['type'] = obj.rate.get_internal_type()
return Response(response)
def get_updated(self, obj):
response = dict()
response['value'] = obj.updated
response['type'] = obj.updated.get_internal_type()
return Response(response)

How to redirect with ajax django

The problem i am facing over here is that i am not able to see the cartempty page when items count is 0.
here is the view
if request.is_ajax():
if request.POST.get('action') == 'remove':
cart_item.delete()
if cart_item.cart.items.count() == 0:
return render(request , "carts/cartempty.html", {})
else:
try:
total = cart_item.line_item_total
except:
total = None
try:
original_total = cart_item.cart.original_total
except:
original_total = None
try:
final_total = cart_item.cart.final_total
except:
final_total = None
try:
total_items = cart_item.cart.items.count()
except:
total_items = 0
data = {
"line_total": total,
"original_total": original_total,
"final_total" :final_total,
"total_items": total_items
}
return JsonResponse(data)
How can i redirect to cartempty page using ajax?
Just guessing. Did you try?
return render_to_response('carts/cartempty.html', context_instance=RequestContext(request))
OR
return HttpResponseRedirect("/carts/cartempty/")
instead of:
return render(request , "carts/cartempty.html", {})

Odoo : How to display the "Force Availability" by dynamically?

I'm trying to display the "Force Availability" dynamically when SO Transfering. I did as following, but not working. How do I do?
def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=True, toolbar=False, submenu=False):
result = super(StockPicking, self).fields_view_get(cr, uid, view_id, view_type, context, toolbar, submenu)
if view_type == 'form':
obj_so_settings = self.pool.get('sale.config.settings')
so_config_ids = obj_so_settings.search(cr, uid, [], limit=1, order='id DESC', context=context)
if so_config_ids:
so_settings = obj_so_settings.browse(cr, uid, so_config_ids[0], context=context)
if so_settings.remove_force_availability:
result.update({'arch': result['arch']
+ '<xpath expr="//button[#name=\'force_assign\']" position="attributes">'
'<attribute name="invisible">1</attribute></xpath>'})
else:
pass
return result
result['arch'] is holding the whole stock_picking form data.
finally I got it
from lxml import etree
def fields_view_get(self, cr, uid, view_id=None, view_type=False, context=None, toolbar=False, submenu=False):
if not context:
context = {}
res = super(custom_stock_pick, self).fields_view_get(cr, uid, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar, submenu=submenu)
if view_type == 'form':
remove_force_availability = False
so_settings_obj = self.pool.get('sale.config.settings')
so_config_ids = so_settings_obj.search(cr, uid, [], limit=1, order='id DESC', context=context)
if so_config_ids:
so_settings = so_settings_obj.browse(cr, uid, so_config_ids[0], context=context)
remove_force_availability = so_settings.group_remove_force_availability
if remove_force_availability:
if res['name'] == 'stock.picking.form':
doc = etree.fromstring(res['arch'])
nodes = doc.findall(".//*[#name='force_assign']")
for node in nodes:
parent = node.getparent()
parent.remove(node)
res['arch'] = etree.tostring(doc)
return res

Creating object in django model form with foreign key

I am inserting a new record in my model form where my model is child form containing a foriegn key. When I am submitting the form it give error it should be instance of the foriegn key.
Here is my model
class MMEditidState(models.Model):
state_id = models.IntegerField(primary_key = True)
state_dremelid = models.ForeignKey(MMDremelDump, db_column = 'state_dremelid')
assignee = models.CharField(max_length = 50)
state = models.CharField(max_length = 50)
role = models.CharField(max_length = 50)
date = models.DateTimeField()
class Meta:
db_table = u'mm_editid_state'
def __unicode__(self):
return u'%s %s' % (self.state_dremelid, self.assignee)
class MMEditidErrors(models.Model):
error_id = models.IntegerField(primary_key = True)
error_stateid = models.ForeignKey(MMEditidState, db_column = 'error_stateid')
feature_type = models.CharField(max_length = 20)
error_type = models.CharField(max_length = 20)
error_nature = models.CharField(max_length = 50, null = True)
error_details = models.CharField(max_length = 50)
error_subtype = models.CharField(max_length = 200)
date = models.DateTimeField()
class Meta:
db_table = u'mm_editid_errors'
def __str__(self):
return "%s" % (self.error_dremelid)
def __unicode__(self):
return u'%s' % (self.error_dremelid)
Here is my View
def qcthisedit(request, get_id):
if request.method == "POST":
form = forms.MMEditidErrorForm(get_id, request.POST)
if form.is_valid():
form.save()
return http.HttpResponseRedirect('/mmqc/dremel_list/')
else:
form = forms.MMEditidErrorForm(get_id)
return shortcuts.render_to_response('qcthisedit.html',locals(),
context_instance = context.RequestContext(request))
Here is my form
class MMEditidErrorForm(forms.ModelForm):
def __init__(self,get_id, *args, **kwargs):
super(MMEditidErrorForm, self).__init__(*args, **kwargs)
dremel = MMEditidState.objects.filter(pk=get_id).values('state_id')
dremelid = int(dremel[0]['state_id'])
self.fields['error_stateid'] = forms.IntegerField(initial = dremelid,
widget = forms.TextInput(
attrs{'readonly':'readonly'}))
feature_type = forms.TypedChoiceField(choices = formfields.FeatureType)
error_type = forms.TypedChoiceField(choices = formfields.ErrorType)
error_nature = forms.TypedChoiceField(choices = formfields.ErrorNature)
error_details = forms.TypedChoiceField(choices = formfields.ErrorDetails)
error_subtype = forms.TypedChoiceField(choices = formfields.ErrorSubType)
class Meta:
model = models.MMEditidErrors
exclude = ('error_id','date')
When I submit the form I am getting the error
Cannot assign "1": "MMEditidErrors.error_stateid" must be a "MMEditidState" instance.
So I have added line
get_id = MMEditidState.objects.get(pk = get_id)
Now I am getting the below mentioned error
int() argument must be a string or a number, not 'MMEditidState'
in form = forms.MMEditidErrorForm(get_id, request.POST)
Can someone help on this
Thanks
Vikram
I have solved this problem by simply using the custom forms instead of model forms. While storing the data in the database, I managed myself in the views.py

Resources