def get_dialog_or_create_new(same_sender_id, same_recipient_id): #Get sender and recipient sender = Mother.objects.get(id=same_sender_id) recipient = Mother.objects.get(id=same_recipient_id) #Try to get dialog via owner is sender, and interlocutor is recipient if Dialog.objects.filter(owner=sender).filter(interlocutor=recipient): print "dialog found in 1st step" return Dialog.objects.filter(owner=sender).filter(interlocutor=recipient).get() #Try to get dialog via owner is recipient, and interlocutor is sender if Dialog.objects.filter(owner=recipient).filter(interlocutor=sender): print "dialog found in 2th step" return Dialog.objects.filter(owner=recipient).filter(interlocutor=sender).get() #If dialog doesn`t create - return Dialog instance! print "dialog not found, create new" current_dialod = Dialog() current_dialod.owner = sender current_dialod.interlocutor = recipient current_dialod.save() return current_dialod
def send_message(request): did = int(request.POST.get('dialog_id')) username = request.POST.get('username') msg = request.POST.get('msg') if not request.user.is_authenticated() or not msg: return HttpResponse(json.dumps({"status": "failed"}), content_type="application/json") if not did: d = Dialog(first_user=request.user, second_user=get_user_model().objects.get(username=username)) d.save() else: d = Dialog.objects.get(id=did) newmsg = Message(dialog=d, sender=request.user, is_read=False, send_date=timezone.now(), text=msg) newmsg.save() return HttpResponse(json.dumps({"status": "ok", "date": "Just now" }), content_type="application/json")
def send_message_2(request, recipient): #Подготавливаем нужные нам данные current_user = get_current_user(request=request) recipient = Mother.objects.get(id=recipient) #Подготовка данных завершена #0 - Создаем сообщение if request.method == "POST": now = datetime.now() new_message = Messages() new_message.sender = get_current_user(request=request) new_message.recipient = recipient new_message.message_text = request.POST["message_text"] new_message.send_time = "%s/%s/%s %s:%s"%(now.day, now.month, now.year, now.minute, now.hour) new_message.save() #1 - Получаем диалог пользователя c выбранным собеседником try: #2 - Если такой диалог создан - добавляем сообщение в список сообщений диалога print "dialog " print "AAA" print current_user.email print recipient.email current_dialod = Dialog.objects.get(Q(owner=current_user), Q(interlocutor=recipient) | Q(owner=recipient), Q(interlocutor=current_user)) print current_dialod.id current_dialod.messages_box.add(new_message) current_dialod.save() except ObjectDoesNotExist: #3 - Если такой диалог НЕ создан - создаем и добавляем сообщение в список сообщений диалога print "dialog not found" current_dialod = Dialog() current_dialod.owner = current_user current_dialod.interlocutor = recipient current_dialod.save() current_dialod.messages_box.add(new_message) current_dialod.save() return render(request, "create_message.html", {"recipient": recipient.id})