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

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

Related

discord py 'keyerror' (discord components, slash commands)

I'm trying to use the bot by adding a slash command and a button. For once, the slash command is working as intended. But every time I run the command, I get a warning like that. I'm not sure what the problem is. It's a part of the code.
Ignoring exception in on_socket_response
Traceback (most recent call last):
File "/home/yuna21724/.local/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "/home/yuna21724/.local/lib/python3.8/site-packages/discord_buttons_plugin/__main__.py", line 17, in soclistener
await self.emit(data["data"]["custom_id"], data)
KeyError: 'custom_id'
import discord
import asyncio
import SeagamiCommandsListening
import SeagamiNotice
import SeagamiCharacter
from discord_buttons_plugin import *
from discord.ext import commands
from discord_buttons_plugin import *
from discord_slash import SlashCommand
from discord import Intents
from discord_components.client import DiscordComponents
token = ""
seagami = commands.Bot(command_prefix='.', intents = Intents.all())
slash = SlashCommand(seagami, sync_commands = True)
buttons = ButtonsClient(seagami)
#seagami.event
async def on_ready():
DiscordComponents(seagami)
await seagami.change_presence(status=discord.Status.online)
print('[알림]디스코드 봇 서비스가 시작되었습니다...',
seagami.user.name)
while True:
if SeagamiNotice.a['title'] == SeagamiNotice.b['title']:
print('')
else:
embed = discord.Embed(color = 0x2F3136)
embed.add_field(name = "```🌷로스트아크 공지사항```",
value = "``🌷로스트아크 점검 시, 봇의 기능이 제한됩니다.``", inline =
False)
embed.add_field(name = f"```👑
{SeagamiNotice.a['title']}```", value = '``📕 추가 정보를 확인하려면
아래의 바로가기 버튼을 눌러주세요.``', inline = False)
components_notice = [Button(label = "바로가기", style =
5, url = f"{SeagamiNotice.a['Link']}")]
await
seagami.get_channel(int(878004091505221643)).send(embed = embed,
components = components_notice)
await asyncio.sleep(335)
#seagami.event
async def on_member_join(member):
message_ = "<#{}>".format(str(member.id))
embed = discord.Embed(color = 0x2F3136)
embed.add_field(name = "```🌷환영해요.```", value = f"``🌷
``{message_}``님, 새가미와 아이들에 오신 걸 환영합니다.``", inline =
False)
buttons = [Button(label = "역할 받기", style = 2, custom_id =
"role")]
await seagami.get_channel(int(879993490996600852)).send(embed =
embed, components = buttons)
await
member.add_roles(seagami.get_guild(int(870543165004849152)).get_role(int(
870552731419566111)))
#slash.slash(name="입장", description="새가미 봇이 음성채널로 이동합니
다.", guild_ids=[870543165004849152])
async def in_voice(ctx: SlashCommand):
try:
if (ctx.channel.id == int(878003511961464883)):
await
SeagamiCommandsListening.commands_Listening.in_(ctx)
await ctx.reply('``🌷``새가미 봇이 음성채널로 이동하였습니
다.')
except:
await ctx.reply('``🌷``해당 명령어는 여기서 사용할 수 없습니
다.')
#slash.slash(name="퇴장", description="새가미 봇이 음성채널에서 퇴장
합니다.", guild_ids=[870543165004849152])
async def out_voice(ctx: SlashCommand):
try:
if (ctx.channel.id == int(878003511961464883)):
await
`enter code here`SeagamiCommandsListening.commands_Listening.out_(ctx)
await ctx.reply('``🌷``새가미 봇이 음성채널에서 퇴장하였습
니다.')
except:
await ctx.reply('``🌷``해당 명령어는 여기서 사용할 수 없습니
다.')
#slash.slash(name="재생", description="새가미 봇을 통해 노래를 재생할
수 있습니다.", guild_ids=[870543165004849152])
async def play_voice(ctx: SlashCommand, 링크):
try:
if (ctx.channel.id == int(878003511961464883)):
await
SeagamiCommandsListening.commands_Listening.play_(ctx, 링크)
await ctx.reply('``🌷``신청하신 노래를 ``1회``재생 합니
다.')
await buttons.send(
content = "아래의 버튼을 눌러 ``👑명령어``를 사용하실 수 있습니다.",
channel = ctx.channel.id,
components = [
ActionRow([
Button(label = "일시 정지", style = 1, custom_id = "button_pause"),
Button(label = "다시 듣기", style = 3, custom_id = "button_resume"),
Button(label = "그만 듣기", style = 4, custom_id = "button_stop")
]
)])
except:
await ctx.reply('해당 명령어는 여기서 사용할 수 없습니다.')
#slash.slash(name="반복재생", description="새가미 봇을 통해 노래를 반복 재생할 수 있습니다.", guild_ids=[870543165004849152])
async def replay_voice(ctx: SlashCommand, 링크):
try:
if (ctx.channel.id == int(878003511961464883)):
await SeagamiCommandsListening.commands_Listening.replay_(ctx, 링크)
await ctx.reply('``🌷``신청하신 노래를 반복 재생 합니다.')
await buttons.send(
content = "아래의 버튼을 눌러 ``👑명령어``를 사용하실 수 있습니다.",
channel = ctx.channel.id,
components = [
ActionRow([
Button(label = "일시 정지", style = 1, custom_id = "button_pause"),
Button(label = "다시 듣기", style = 3, custom_id = "button_resume"),
Button(label = "그만 듣기", style = 4, custom_id = "button_stop")
]
)])
except:
await ctx.reply('해당 명령어는 여기서 사용할 수 없습니다.')
#slash.slash(name="검색", description="캐릭터 정보를 검색 할 수 있습니다.", guild_ids=[870543165004849152])
async def search_(ctx: SlashCommand, 캐릭터명):
if (ctx.channel.id == int(882916863779168267)):
await SeagamiCharacter.search_info.info_(ctx, 캐릭터명)
if SeagamiCharacter.code['code'] != '100':
embed = discord.Embed(color = 0x2F3136)
embed.add_field(name = f"> ```🌷{SeagamiCharacter.name_['name']}```", value = f"> ``🌷{SeagamiCharacter.class_info['class']}``", inline = False)
embed.add_field(name = "```📕캐릭터 레벨```", value = f"``Lv. {SeagamiCharacter.Level_['Level'][8:]}``", inline = True)
embed.add_field(name = "```📕원정대 레벨```", value = f"``Lv. {SeagamiCharacter.expedition_Level['expedition'][9:]}``", inline = True)
embed.add_field(name = "```📕아이템 레벨```", value = f"``Lv. {SeagamiCharacter.item_Level['item_Level'][12:]}``", inline = True)
embed.add_field(name = "> ```🔯특성```", value = "> ``🔯펫 효과가 적용 된 특성입니다.``", inline = False)
embed.add_field(name = "```🔯치명```", value = f"``{SeagamiCharacter.ability_battle['ability_battle1']}``", inline = True)
embed.add_field(name = "```🔯특화```", value = f"``{SeagamiCharacter.ability_battle['ability_battle3']}``", inline = True)
embed.add_field(name = "```🔯제압```", value = f"``{SeagamiCharacter.ability_battle['ability_battle5']}``", inline = True)
embed.add_field(name = "```🔯신속```", value = f"``{SeagamiCharacter.ability_battle['ability_battle7']}``", inline = True)
embed.add_field(name = "```🔯인내```", value = f"``{SeagamiCharacter.ability_battle['ability_battle9']}``", inline = True)
embed.add_field(name = "```🔯숙련```", value = f"``{SeagamiCharacter.ability_battle['ability_battle11']}``", inline = True)
embed.add_field(name = "> ```👑각인```", value = "> ``👑현재 사용중인 각인입니다.``", inline = False)
try:
for count in range(8):
embed.add_field(name = "```👑각인```", value = f"``{SeagamiCharacter.ability_engrave[f'ability_engrave{count}']}``", inline = True)
except:
components_ = [[
Button(label = "바로가기", style = 5, url = f'https://lostark.game.onstove.com/Profile/Character/{캐릭터명}')
]]
await ctx.reply(f'``🌷{캐릭터명}``검색이 완료되었습니다.')
await seagami.get_channel(int(882916863779168267)).send(embed = embed, components = components_)
else:
await ctx.reply('``🌷``로스트아크 점검 중 입니다.')
SeagamiCharacter.code['code'] = '200'
else:
await ctx.reply('해당 명령어는 여기서 사용할 수 없습니다.')
#buttons.click
async def button_pause(ctx):
await SeagamiCommandsListening.commands_Listening.pause_()
await ctx.reply('``🌷``노래가 일시 정지 되었습니다.')
#buttons.click
async def button_resume(ctx):
await SeagamiCommandsListening.commands_Listening.resume_()
await ctx.reply('``🌷``노래가 다시 재생 되고 있습니다.')
#buttons.click
async def button_stop(ctx):
await SeagamiCommandsListening.commands_Listening.stop_()
await ctx.reply('``🌷``재생중인 노래를 종료 하였습니다.')
seagami.run(token)
enter image description here
enter image description here
enter image description here
enter image description here
A KeyError is raised when a mapping (dictionary) key is not found in the set of existing keys.
If you're unsure why you're getting a KeyError, here are some things you can do
Print out the dictionary to see what's in it
Check that the key is what you intend it to be
If you want to provide a default for a value when the key isn't in the dictionary, you can use dict.get which defaults to None
>>> person["pets"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'pets'
>>> person.get("pets")
>>> person.get("pets", [])
[]
Docs:
https://docs.python.org/3/library/exceptions.html#KeyError%3E
https://docs.python.org/3/library/stdtypes.html#dict.get%3E
Helpful link: https://realpython.com/python-keyerror/%3E
I believe the cause of your error was the 3rd party package you installed called discord_buttons_plugin, which as far as I can tell requires you to add a custom_id to all buttons except the ButtonType().Link. In your _search command, you've forgot to add it, which causes an error in the package's code. Try adding a custom_id to the button there.
Long Story Short
Try adding a custom_id in your button component in the _search command.

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", {})

What makes an on-change functions before clicking?

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 :)

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