def detail(request, event_id): event = get_object_or_404(Event, pk=event_id) if request.method == 'POST' and request.user in event.participants.all(): form = MessageForm(request.POST) if form.is_valid(): new_message = form.save(commit=False) new_message.chat = event.chat new_message.chat.last_activity = timezone.now() new_message.author = request.user new_message.chat.save() new_message.save() return redirect('events:detail', event_id=event_id) else: form = MessageForm() storage = messages.get_messages(request) context = {'event': event, 'messages': storage, 'form': form} return render(request, 'events/detail.html', context)
def authenticated_chat(request, model_key, owner_id): """ View for chat which is "read only" for unauthenticated and "writeable" for authenticated users. Requires **page** as **GET** parameter for page number. Last page will be used for default. owner_id: id of the owner model. model_key: one of the **KEY_KEY_TO_CHAT_OWNER** keys. """ ModelClass = KEY_TO_CHAT_OWNER[model_key] owner = get_object_or_404(ModelClass.objects, id=owner_id) if not owner.chat: raise Http404() if request.method == 'POST': if not request.user.is_authenticated(): return HttpResponseForbidden() form = MessageForm(request.POST, request.user, owner.chat) if form.is_valid(): form.save() return redirect('authenticated_chat', model_key=model_key, owner_id=owner.id) else: form = MessageForm() owner.chat.url = reverse('authenticated_chat', kwargs={ 'owner_id': owner_id, 'model_key': model_key, }) owner.chat.rss = reverse('open_rss', kwargs={ 'id': owner_id, 'model_key': model_key, }) return render(request, 'parts/chat_message_list.html', { 'form': form, 'chat': owner.chat, 'page': get_chat_page(owner.chat, request.GET.get('page')), })
def add_message(request, chat_id): form = MessageForm error = {} try: chat = Chat.objects.get(id=chat_id) except Chat.DoesNotExist: raise Http404 if request.method == "POST": form = MessageForm(request.POST) if form.is_valid(): f = form.save(commit=False) f.ip = "1.2.3.4" f.chat = chat f.save() if request.is_ajax(): error['error'] = 'False' return HttpResponse(simplejson.dumps(error)) else: return redirect('/messages/%s/' % (f.chat.id))
def sendMessage(request, participationID=None): # send message and redirect to the conversation form = MessageForm(request.POST) if form.is_valid(): messagetext = form.cleaned_data['message'] subject = 'Test email when new message is sent' message = 'This is the message content, if you read this the test has worked! Daijoubu!' from_email = settings.EMAIL_HOST_USER to_list = [settings.EMAIL_HOST_USER] send_mail(subject, message, from_email, to_list, fail_silently=False) if participationID: participation = ConversationParticipation.objects.get( pk=participationID) if request.user == participation.user: Message(conversation=participation.conversation, content=messagetext, sender=request.user).save() return redirect('chat:detail', participationID=participationID, conversationname=slugify( participation.get_conversation_name()) ) # TODO participation is niet altijd geinitialisseerd
def test_message_form_valid_data(self): """ Test form is valid with correct data """ form = MessageForm({ 'message': 'A test message', }) self.assertTrue(form.is_valid())
def create_message(request, chat_id=None): chat = get_object_or_404(Chat, id=chat_id) form = MessageForm(user=request.user, chat=chat, data=request.POST) if form.is_valid(): msg = form.save() return HttpResponseAjax(**msg.to_dict) else: return HttpResponseAjaxError(errors=form.errors)
def post(self, request, pk): form = MessageForm(data=request.POST) if form.is_valid(): message = form.save(commit=False) message.chat_id = pk message.author = self.request.user message.save() #new_message.delay(message.id, message.author, message.chat_id) return redirect(reverse('messages', kwargs={'pk': pk}))
def post(self, request, message_id, *args, **kwargs): message = Message.objects.get(id=message_id, author=request.user) form = MessageForm(request.POST) if form.is_valid(): message.message = form.cleaned_data.get('message') message.changed = True message.save() return redirect('chat', pk=message.chat_id)
def test_message_form_invalid_with_no_data(self): """ Test form is invalid with missing data Test form displays correct error message """ form = MessageForm({ 'message': '', }) self.assertFalse(form.is_valid()) self.assertEqual(form.errors['message'], ['This field is required.'])
def post(self, request, pk): chat = get_object_or_404(Chat, id=pk) if request.user in chat.members.all(): form = MessageForm(data=request.POST) if form.is_valid(): message = form.save(commit=False) message.chat_id = pk message.author = self.request.user message.save() new_message.apply_async(args=[ message.id, ], countdown=3600) return redirect(reverse('messages', kwargs={'pk': pk}))
class UserSendPageMessage(TemplateView): """ Пишем сообщения со страниц пользователей или разных списков. Если у пользователя есть друзья, то add_friend_message.html (возможность добавлять друзей), иначе add_message.html """ template_name = None def get(self, request, *args, **kwargs): from users.models import User from common.templates import get_my_template self.template_name = get_my_template("chat/message/add_message.html", request.user, request.META['HTTP_USER_AGENT']) self.user = User.objects.get(pk=self.kwargs["pk"]) return super(UserSendPageMessage, self).get(request, *args, **kwargs) def get_context_data(self, **kwargs): from chat.forms import MessageForm context = super(UserSendPageMessage, self).get_context_data(**kwargs) context["form"] = MessageForm() context["member"] = self.user return context def post(self, request, *args, **kwargs): from users.models import User from chat.models import Message from common.check.user import check_user_can_get_list from chat.forms import MessageForm from django.http import HttpResponse self.form, self.user, connections = MessageForm( request.POST), User.objects.get( pk=self.kwargs["pk"]), request.POST.getlist("chat_items") check_user_can_get_list(request.user, self.user) if request.is_ajax() and self.form.is_valid(): message = self.form.save(commit=False) if request.POST.get('text') or request.POST.get( 'attach_items') or request.POST.get('sticker'): _message = Message.get_or_create_chat_and_send_message( creator=request.user, user=self.user, text=message.text, voice=request.POST.get('voice'), attach=request.POST.getlist('attach_items'), sticker=request.POST.get('sticker')) return HttpResponse() else: from django.http import HttpResponseBadRequest return HttpResponseBadRequest()
def chat(request, pk): ride = get_object_or_404(Ride, pk=pk) if request.user.pk != ride.initiator.pk and request.user.pk != ride.driver.pk: return redirect('profile_summary') if request.method == "POST": form = MessageForm(request.POST) if form.is_valid(): message = form.save(commit=False) message.ride = ride message.user = request.user message.save() return redirect('chat', pk=ride.pk) else: form = MessageForm() return render(request, 'chat.html', {'form': form, 'ride': ride})
def home(request): request.user # On récupère les infos du user connecté last_messages = Message.objects.order_by('-date') # On récupère tous les messages if request.method == "POST": # Si le formulaire a été envoyé form = MessageForm(request.POST) # On récupère le formulaire choisi if form.is_valid(): pseudo = request.user.username # On récupère le pseudo du user connecté msg = request.POST.get('message', '') # On récupère le message du formulaire message = Message.objects.create(user=pseudo, content=msg) # On insère en base if message: # Si l'objet renvoyé n'est pas None last_messages = Message.objects.order_by('-date') else: # Sinon une erreur sera affichée error = True else: form = MessageForm() # On affiche le formulaire choisi return render(request, 'index.html', locals())
def team_chat(request, team): if request.method == 'POST': form = MessageForm(request.POST, request.user, team.chat) if form.is_valid(): form.save() return redirect('team_chat', team_id=team.id) else: form = MessageForm() page = get_chat_page(team.chat, request.REQUEST.get('page')) team.chat.url = reverse('team_chat', kwargs={'team_id': team.id}) team_rss = TeamChatFeed() team.owner_key = request.user.userprofile.external_read_auth team.chat.rss = team_rss.link(team) return render(request, 'parts/chat_message_list.html', { 'chat': team.chat, 'form': form, 'page': page, })
def post(self, request, *args, **kwargs): from chat.forms import MessageForm form = MessageForm(request.POST, request.FILES) if request.is_ajax() and form.is_valid( ) and request.user.is_administrator(): from chat.models import Message form_post = form.save(commit=False) Message.get_or_create_manager_chat_and_send_message( creator_pk=request.user.pk, text=form_post.text, voice=request.POST.get('voice'), attach=request.POST.getlist('attach_items')) return HttpResponse() else: return HttpResponseBadRequest()
def newMessage(request, userID=None, projectID=None): # if projectID is none, a new message to a user is requested user = request.user if userID: anonymous = False otherUser = get_object_or_404(User, pk=userID) # if userID is none, a conversation about a project is requested where the project owner is anonymous else: anonymous = True otherUser = get_object_or_404(Project, pk=projectID).owner if request.method == "POST": # a message is been send form = MessageForm(request.POST) if form.is_valid(): messagetext = form.cleaned_data['message'] participation = get_or_create_participation( user, otherUser, anonymous, projectID) Message.objects.create(conversation=participation.conversation, content=messagetext, sender=user) return redirect('chat:detail', participationID=participation.id, conversationname=slugify( participation.get_conversation_name())) else: # the page is loaded, ready to send a new message # if the conversation already exists, move to that conversation if conversation_exists(user, otherUser, anonymous): participation = get_or_create_participation( user, otherUser, anonymous) return redirect('chat:detail', participationID=participation.id, conversationname=slugify( participation.get_conversation_name())) else: # otherwise, prepare to receive a new message context = { 'messageForm': MessageForm(), } if userID: context['otherUser'] = get_object_or_404(User, pk=userID) else: context['project'] = get_object_or_404(Project, pk=projectID) return render(request, "chat/new_message.html", context)
def on_message(self, message): self.log('User message: {0}'.format(message)) data = {} data['message'] = urllib.unquote(message['message'].encode('utf-8')).decode("utf-8") form = MessageForm(data) if form.is_valid(): object = form.save(commit=False) object.sender_id = message['sender'] object.channel_id = message['channel'] object.save() message.clear() message['room'] = self._get_room_name(object.channel_id) message['action'] = 'new_message' message['result'] = render_to_string('chat/msg_detail.html', {'msg': object}) # parse url match = re.search(r'http://[a-zA-Z0-9]+\.[-a-zA-Z0-9_]+/*', object.message) if match: try: url = metadata_parser.MetadataParser(url=object.message) meta = url.metadata.get('meta') page = url.metadata.get('page') img = meta.get('og:image', None) title = urllib.unquote(page['title'].encode('utf-8')).decode("utf-8") message['result'] = render_to_string('chat/url_parse.html', {'img': img, 'title':title, 'obj': object}) except: pass else: message.clear() message['action'] = 'error' self.emit_to_room_with_me(object.channel_id, 'message', message) return True
def authenticated_chat(request, model_key, owner_id): """ View for chat which is "read only" for unauthenticated and "writeable" for authenticated users. Requires **page** as **GET** parameter for page number. Last page will be used for default. owner_id: id of the owner model. model_key: one of the **KEY_KEY_TO_CHAT_OWNER** keys. """ ModelClass = KEY_TO_CHAT_OWNER[model_key] owner = get_object_or_404(ModelClass.objects, id=owner_id) if not owner.chat: raise Http404() if request.method == 'POST': if not request.user.is_authenticated(): return HttpResponseForbidden() form = MessageForm(request.POST, request.user, owner.chat) if form.is_valid(): form.save() return redirect('authenticated_chat', model_key=model_key, owner_id=owner.id) else: form = MessageForm() owner.chat.url = reverse('authenticated_chat', kwargs={ 'owner_id': owner_id, 'model_key': model_key, }) owner.chat.rss = reverse('open_rss', kwargs={ 'id': owner_id, 'model_key': model_key, }) return render( request, 'parts/chat_message_list.html', { 'form': form, 'chat': owner.chat, 'page': get_chat_page(owner.chat, request.GET.get('page')), })
def post(self, request, *args, **kwargs): self.object = self.get_object() form = MessageForm(request.POST) if form.is_valid(): return self.form_valid(form) return self.form_invalid(form)