Sequence number generation in odoo - odoo-11

I am using this code for sequence generation
class cardInfo(models.Model):
_name = "library.card"
card_number = fields.Char(String = "Card Number" , size = 7, Translate = True, readonly = True)
user_name = fields.Many2one('student.student',String = "Name")
card_type = fields.Selection([('s', 'Student'), ('l', 'Staff')] , String = "Card Type")
number_of_book_limit = fields.Integer(String = "No Of Book Limit" , default = 0)
#api.model
def create(self, vals):
seq = self.env['ir.sequence'].next_by_code('library.card.number') or '/'
vals['card_number'] = seq
return super(cardInfo, self).create(vals)
but i am getting only the '/' as sequence number.. why?

You need to create "ir.sequance" in xml file like,
<record id="seq_library_card" model="ir.sequence">
<field name="name">Library Card</field>
<field name="code">library.card</field>
<field name="prefix">LIB</field>
<field name="padding">5</field>
<field name="company_id" eval="False" />
</record>
In Py file you have to write like,
#api.model
def create(self, vals):
x = self.env['ir.sequence'].next_by_code('library.card') or '/'
vals['card_number'] = x
return super(LibraryCard, self).create(vals)

Related

Blender - Inserting a line of text using bpy

I'm designing a simple GUI for a Blender 2.80 plug-in. I've created a dialog box to enter some data:
class ExportFDSCloudHPC(Operator):
bl_idname = "..."
bl_label = "Dialog Box"
bl_description = "..."
data1 = bpy.props.StringProperty(
name = "Data 1",
default = "..."
)
data2 = bpy.props.StringProperty(
name = "Data 2",
default = "..."
)
data3 = bpy.props.StringProperty(
name = "Data 3",
default = "..."
)
def draw(self, context):
col = self.layout.column(align = True)
col.prop(self, "data1")
col = self.layout.column(align = True)
col.prop(self, "data2")
col = self.layout.column(align = True)
col.prop(self, "data3")
def execute(self, context):
...
I would like to add a line of text above Data 1 with a message that has the same length as the dialog box. It's possible?
Add label() in draw() as you adding column:
def draw(self, context):
self.layout.label(text="text")
col = self.layout.column(align = True)
Here is label documentation

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)

Convert a text to JSON

I have a text file say data.txt which contains content of format:
( {
city = Leesburg;
country = USA;
dob = "";
email = "email#domain.com";
firstName = "EricM.";
homePhone = "";
lastName = Abcdef;
mobilePhone = 12312312;
state = Virginia;
workPhone = 12312312;
},
{
city = "Mt. Uncle";
dob = "";
email = "";
firstName = first;
homePhone = "";
lastName = Berry;
mobilePhone = 234234;
state = MD;
workPhone = "";
}
)
require "json"
file = File.open("data.txt")
contents = file.read
hashes = contents.scan(/{(.*?)}/mx)
arr = []
hashes.each do |hash|
hashitems = hash[0].scan(/(\w+\s=\s.+?);/)
ahash = {}
hashitems.each do |hashitem|
itemarr = hashitem[0].split(" = ")
ahash[itemarr[0]] = itemarr[1]
end
arr << ahash
end
print JSON.dump(arr)
What I've done here is use two regex functions to break down your data into a Ruby object, then I've used the JSON library to dump the object to JSON.

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