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", {})
Related
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.
I am trying to implement this api but the code says error every single time.
My code so far:
#client.command()
async def mean(ctx,word):
response = requests.get(f"https://api.dictionaryapi.dev/api/v2/entries/en/{word}")
if response.status_code == 404:
await ctx.send("No such word")
return
else:
wordx = response.json()
the_dictionary = wordx[0]
meanings = the_dictionary['meanings']
definitions = meanings[0]
definition = definitions['definitions']
meaningg = definition[0]
meaning = meaningg['definition']
example = meaningg.get('example',['None'])
synonymslist = meaningg.get("synonyms",['None'])
if isinstance(synonymslist,str):
synonymslist = [synonymslist]
pass
synonyms = ','.join(synonymslist)
deffinal= discord.Embed(title=f"`{word.upper()}`")
deffinal.add_field(name = "Definition", value=f"{meaning}")
deffinal.add_field(name = 'Example', value = f"{example}")
deffinal.add_field(name = "Synonyms", value = f"{synonyms}")
await ctx.channel.send(embed = deffinal)
Here is the error message:
Your error does not come from the API call to the dictionary api, but rather from your call to the discord api.
The error message says discord.errors.HTTPException: [...] In embed.fields.2.value: This field is required.
So the error comes from an empty field in your embed! The field has index 2 so it is actually the third field (Synonyms) which is causing the problem.
You can simply check if a string is empty, before even adding the field. And if it is empty, just don't add it.
deffinal= discord.Embed(title=f"`{word.upper()}`")
if meaning:
deffinal.add_field(name = "Definition", value=f"{meaning}")
if example:
deffinal.add_field(name = 'Example', value = f"{example}")
if synonyms:
deffinal.add_field(name = "Synonyms", value = f"{synonyms}")
#client.command()
async def mean(ctx,word):
response = requests.get(f"https://api.dictionaryapi.dev/api/v2/entries/en/{word}")
if response.status_code == 404:
await ctx.send("No such word")
return
else:
wordx = response.json()
the_dictionary = wordx[0]
meanings = the_dictionary['meanings']
definitions = meanings[0]
definition = definitions['definitions']
meaningg = definition[0]
meaning = meaningg['definition']
example = meaningg.get('example',['None'])
synonymslist = meaningg.get("synonyms",['None'])
if isinstance(synonymslist,str):
synonymslist = [synonymslist]
pass
synonyms = ','.join(synonymslist)
deffinal= discord.Embed(title=f"`{word.upper()}`")
if meaning:
deffinal.add_field(name = "Definition", value=f"{meaning}")
if example:
deffinal.add_field(name = 'Example', value = f"{example}")
if synonyms:
deffinal.add_field(name = "Synonyms", value = f"{synonyms}")
await ctx.channel.send(embed = deffinal)
Adding to itzFlubby answer, using requests will be blocking read more which means if you block for too long then your bot will freeze since it has not stopped the function’s execution at that point to do other things.
Here is the final code, also I changed the format a bit to make it easier to read.
# import aiohttp
#bot.command()
async def mean(ctx, word):
async with aiohttp.ClientSession() as session:
async with session.get(f"https://api.dictionaryapi.dev/api/v2/entries/en/{word}") as r:
if r.status == 200:
info = await r.json()
else:
return await ctx.reply("No such word")
the_dictionary = info[0]['meanings'][0]['definitions'][0]
definition = the_dictionary.get('definition')
example = the_dictionary.get('example')
synonymslist = the_dictionary.get("synonyms")
# if only one synonym is avaliable
if isinstance(synonymslist, str):
synonymslist = [synonymslist]
synonyms = '\n'.join(synonymslist)
deffinal = discord.Embed(title=f"`{word.upper()}`")
if definition:
deffinal.add_field(name="Definition", value=f"```{definition}```")
if example:
deffinal.add_field(name='Example', value=f"```{example}```")
if synonyms:
deffinal.add_field(name="Synonyms", value=f"```{synonyms}```")
await ctx.reply(embed=deffinal)
So basicly the person is trying to guess whats the name of the anime! What I want it to do is to ingore the case sentativity! How can I do that? Here is the code:
#client.command()
async def work(ctx):
await open_account(ctx.author)
users = await get_bank_data()
user = ctx.author
def check(m):
return m.author.id == ctx.author.id
Question1 = 'https://upload.wikimedia.org/wikipedia/en/thumb/d/dc/DARLING_in_the_FRANXX%2C_second_key_visual.jpg/220px-DARLING_in_the_FRANXX%2C_second_key_visual.jpg'
Question2 = 'http://www.j1studios.com/wordpress/wp-content/uploads/Trinity-Seven-Header-001-20160707.jpg'
Question3 = 'https://www.animenewsnetwork.com/hotlink/images/encyc/A18170-2511174083.1466822675.jpg'
Question4 = 'https://www.animenewsnetwork.com/hotlink/images/encyc/A16344-911899268.1425205899.jpg'
Question5 = 'https://www.theanimedaily.com/wp-content/uploads/2020/06/20061004422210.jpg'
Question6 = 'https://th.bing.com/th/id/OIP.zvtbvP4JZNrrlAKPnclMpwHaEK?pid=Api&rs=1&adlt=strict'
Question7 = 'https://mangathrill.com/wp-content/uploads/2020/01/pjimage-1-4.jpg'
Question8 = 'https://th.bing.com/th/id/OIP.xV_2srfdOhEre9Vua-u6zAHaFb?pid=Api&rs=1&adlt=strict'
Question9 = 'https://img1.looper.com/img/gallery/the-untold-truth-of-hunter-x-hunter/intro-1591800144.jpg'
Question10 = 'https://i1.wp.com/static.anidub.com/blog/2014/09/Seirei-Tsukai-no-Blade-Dance.jpg'
questionlist = [Question1, Question2, Question3, Question4, Question5, Question6, Question7, Question8, Question9, Question10]
question = random.choice(questionlist)
await ctx.send("What is the title name of this anime?")
await asyncio.sleep(1)
await ctx.send(question)
msg = await client.wait_for('message', check=check)
await msg.lower()
if question == Question1:
if msg.content == "darling in the franxx":
earnings = random.randrange(300, 500)
await ctx.send(f"You did good! You got an earning of **{earnings}** coins!")
else:
earnings = random.randrange(0, 200)
await ctx.send(f"Did you even try? You got **{earnings}** coins!")
msg = await client.wait_for('message', check=check) returns you the discord.Message class. And discord.Message has no attribute lower(). But it has content, content returns the string value of the message.
And also await msg.lower() is a weird usage, it's not a coroutine so you can't await it.
So you can simply do:
msg = await client.wait_for('message', check=check)
msg_content = msg.content.lower()
if question == Question1:
if msg_content == "darling in the franxx":
earnings = random.randrange(300, 500)
await ctx.send(f"You did good! You got an earning of **{earnings}** coins!")
else:
earnings = random.randrange(0, 200)
await ctx.send(f"Did you even try? You got **{earnings}** coins!")
And also, I suggest you to put questions and question list out of the command, it becomes more optimized.
I am using Elastic search 6.1 version
My data is appending correctly and I am adding '\n' at the end of the request.
My code is as follows:
def insert_in_bulk(self, filee, rtype):
U = urljoin(self.args.host, "/_bulk")
body = []
f = open(filee)
for line in f:
action = {
'index' :{
'_index' : self.args.index,
'_type' : rtype,
}
}
item = {
'word' : line.strip()
}
body.append(json.dumps(action))
body.append(json.dumps(item))
f.close()
body = '\n'.join(body)+'\n'
success = False
try:
r = requests.post(U, data=body)
self.log.info("after request")
if r.status_code == 200:
success = True
r = r.json()
self.log.info("inserted %s items of type = %s", self.args.index , rtype)
except (SystemExit, KeyboardInterrupt): raise
except:
self.log.exception("during bulk index")
if not success:
self.log.error("failed to index records of type = %s", rtype)
I am using the python to connect to elastic search.
I got the answer from this link
Bulk index document from JSON file into ElasticSearch
I have to pass the header to the request as application/x-ndjson.
Though it is quite some time question is asked, but i want to give a solution that has worked for me in most case,
def insert_in_bulk(self, filee, rtype):
U = urljoin(self.args.host, "/_bulk")
body = []
f = open(filee)
for line in f:
action = {
'index' :{
'_index' : self.args.index,
'_type' : rtype,
}
}
item = {
'word' : line.strip()
}
body.append(json.dumps(action))
body.append(json.dumps(item))
f.close()
payload = ""
for l in body:
payload = payload + f"{l} \n"
data = payload.encode('utf-8')
r = requests.post(U, data=data, headers={"Content-Type": "application/x-ndjson"})
print(r.text)
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