I'm new to creating telegram bots with Django. I selected python-telegram-bot library for creating bots with Django.
I've created a Django model, named as category:
class category(models.Model):
name = models.CharField(max_length=250)
category_id = models.IntegerField()
def __str__(self):
return self.name
and product:
class product(models.Model):
product_category = models.ForeignKey(category, on_delete=models.SET_NULL, blank=True, null=True)
name = models.CharField(max_length=250)
cost = models.FloatField()
img = models.ImageField()
def __str__(self):
return self.name
Successfully created InlineKeyboardButtons and placed id of each product model object to each button, with these functions:
def product(update: Update, context: CallbackContext):
query = update.callback_query.data
product_button_list = []
for each in product.objects.select_related().filter(product_category_id = query):
product_button_list.append(InlineKeyboardButton(each.name, callback_data=each.id))
reply_markup = InlineKeyboardMarkup(build_menu(product_button_list,n_cols=2))
update.callback_query.message.edit_text("Mahsulotni tanlang!", reply_markup=reply_markup)
def build_menu(buttons,n_cols,header_buttons=None,footer_buttons=None):
menu = [buttons[i:i + n_cols] for i in range(0, len(buttons), n_cols)]
if header_buttons:
menu.insert(0, header_buttons)
if footer_buttons:
menu.append(footer_buttons)
return menu
When the user selects a button named as the name of the product model object, I am receiving the correct id of the product model object, tested with printing the query:
def product_info(update: Update, context: CallbackContext):
query = update.callback_query.data
print(query)
obj = product.objects.filter(pk=query)
print(obj)
Question: How to reply Django product model object's fields including its image to the user according to the user's chosen product?
Like:
You have chosen a product:
Image of the product
Name of the product
Cost of the product
Here is the answer, I have successed so far:
filename = 'path_until_media_folder' + str(obj.img.url)
update.callback_query.bot.send_photo(update.effective_chat.id, photo=open(filename, 'rb'))