Django запрос - подключить класс пользователя к классу OnetoOnefield для Telegram Bot - PullRequest
0 голосов
/ 21 июня 2020
• 1000 ) - Для этого мне нужен ИДЕНТИФИКАТОР ПОЛЬЗОВАТЕЛЯ

Поскольку существует несколько пользователей, я сохранил chat_id в созданной мной новой модели, которая связана с моделью User с одним полем:

User = get_user_model()

class TelegramProfile(models.Model):
    name = models.CharField(default="",max_length=200,blank=True,unique=True)
    user = models.OneToOneField(User,on_delete=models.CASCADE,related_name="user_id")
    telegram_chat_id = models.CharField(max_length=40,default="",editable=True,blank=True,unique=True)
   
    def __str__(self):
        return str(self.name)

Моя модель пользователя - это встроенная модель:

class User(auth.models.User, auth.models.PermissionsMixin):

def __str__(self):
    return f"@{self.username}"

Итак, в моем файле views.py у меня есть функция, с помощью которой я получаю сообщение (другой класс модели под названием Recipe - я идентифицирую его по первичному key) и chat_id, который принадлежит определенному c пользователю:

  def bot(request,msg,chat_id,token=my_token):
        bot=telegram.Bot(token=token)
        bot.send_message(chat_id=chat_id, text=msg)



  def home(request,pk):
      recipe = get_object_or_404(Recipe,pk=pk)
      user = request.user
      chat_id = User.objects.get(TelegramProfile.telegram_chat_id,user) #with this query I try to grab the chat_id of the logged in user
      ingredients = recipe.ingredients
      ingredients = ingredients.split("<p>")
      ingredients = "\n".join(ingredients)
      ingredients = strip_tags(ingredients)
      bot(request,ingredients,chat_id)
      return render(request,"recipes/send_recipe.html")

Итак, мой вопрос:

-Как мне сделать запрос для chat_id, чтобы: chat_id из Speci c logged в User будет вызываться, поэтому я могу вставить его в функцию бота, чтобы отправить сообщение на этот конкретный c id?

Я все еще новичок в django, поэтому я все еще изучаю q ueries, заранее большое спасибо !!!

1 Ответ

0 голосов
/ 28 июня 2020

РЕДАКТИРОВАТЬ: смог решить сам:

def send_recipe(request, pk):
  try:
    if request.method == "POST":
        data_option = str(request.POST[
                              "testselect"])  # testselect is the select form in recipe_detail.html with which I select 1 of the 2 options
        if data_option == "Ingredients":
            recipe = get_object_or_404(Recipe, pk=pk)
            recipe_name = recipe.name.upper()
            ingredients = recipe.ingredients
            ingredients = ingredients.split("<p>")
            ingredients = "\n".join(ingredients)
            ingredients = strip_tags(ingredients)
            message = f"{recipe_name}: \n {ingredients}"

            user = TelegramProfile.objects.get(
                user=request.user)  # use get instead of filter! filter returns the name but can t use it as object, with get I get the object and I can use the attributes on it!
            chat_id = user.telegram_chat_id
            bot(request, message, chat_id)
            return render(request, "recipes/send_recipe.html")
        elif data_option == "Ingredients & Description":
            recipe = get_object_or_404(Recipe, pk=pk)
            recipe_name = recipe.name.upper()  # recipe name
            ingredients = recipe.ingredients
            ingredients = ingredients.split("<p>")
            ingredients = "\n".join(ingredients)
            ingredients = strip_tags(
                ingredients)  # we grab recipes ingredients and mute them, split at p tag, then add a new line and join them then remove tags
            recipe_description = recipe.description
            recipe_description = recipe_description.split("<p>")
            recipe_description = "\n".join(recipe_description)
            recipe_description = strip_tags(recipe_description)
            message = f"{recipe_name}: \n {ingredients} \n \n {recipe_description}"

            user = TelegramProfile.objects.get(user=request.user)
            chat_id = user.telegram_chat_id
            bot(request, message, chat_id)
            return render(request, "recipes/send_recipe.html")
    else:
        return render(request, "recipes/create_telegram.html")
  except Exception:
    return render(request, "recipes/create_telegram.html")
...