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 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 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 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 send_message(request, user_id): if request.method == 'POST': form = MessageForm(request.POST) message = form.save(commit=False) message.sender = request.user receiver = User.objects.get(id=user_id) message.receiver = receiver message.save() return HttpResponseRedirect(reverse("chat:chat_room"))
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 get_context_data(self, **kwargs): from chat.forms import MessageForm context = super(UserMessageEdit, self).get_context_data(**kwargs) context["object"] = self.message context["form"] = MessageForm(instance=self.message) return context
def post(self, request, *args, **kwargs): from chat.models import Message, Chat from chat.forms import MessageForm chat, form_post = Chat.objects.get(pk=self.kwargs["pk"]), MessageForm( request.POST, request.FILES) if request.POST.get('text') or request.POST.get( 'attach_items') or request.POST.get( 'sticker') or request.POST.get('transfer'): message = form_post.save(commit=False) new_message = Message.send_message( chat=chat, creator=request.user, repost=None, text=message.text, sticker=request.POST.get('sticker'), parent=request.POST.get('parent'), transfer=request.POST.getlist('transfer'), attach=request.POST.getlist('attach_items')) from common.templates import render_for_platform return render_for_platform(request, 'chat/message/message.html', {'object': new_message}) from django.http import HttpResponseBadRequest return HttpResponseBadRequest()
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 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 view_tournament(request, tournament_id): tournament = get_object_or_404(Tournament.objects, id=tournament_id) default_competition_start = int( max(to_timestamp(tournament.first_datetime), to_timestamp(datetime.now()))) is_event_owner = is_owner(tournament, request.user) context = { 'tournament': tournament, 'is_owner': is_event_owner, 'default_competition_start': default_competition_start, 'chat_form': MessageForm(), } if request.user.is_authenticated(): template_name = 'authenticated_tournament.html' if not is_event_owner: managed_tags = Tag.objects.filter( id__in=get_managed_tag_ids(request.user)) context.update({ 'can_add_tags': managed_tags.exclude( id__in=tournament.tags.values_list('id', flat=True)), 'managed_tags': managed_tags, }) else: template_name = 'unauthenticated_tournament.html' return render(request, template_name, context)
def view_team(request, team): return render( request, 'view_team.html', { 'team': team, 'is_owner': is_in_share_tree(request.user, team.owner), 'chat_form': MessageForm(), 'page_number': request.GET.get('page'), })
def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = MessageForm() messages = Message.objects.filter( room=context['object']).order_by('-datetime')[:50] context['messages'] = messages[::-1] return context
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 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 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 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 MaintRequestDetail(request, id): """ Display detail view of particular maintenance request. Allow for landlord to assign cost to tenant/landlord """ # get relevant maintenance request maint_request = get_object_or_404(MaintRequest, id=id) # get chat messages chat_messages = ChatMessage.objects.filter(maint_request=maint_request) # check current user rental is the property relevant to the maintenance request if request.user.profile.rental == maint_request.property_ref: # message form instance for message section message_form = MessageForm() if request.method == 'POST': # the landlord can update the cost of the maintenance request if 'cost' in request.POST: assign_cost_form = MaintenanceQuoteForm(request.POST, request.FILES, instance=maint_request) if assign_cost_form.is_valid(): assign_cost_form.save() messages.success(request, 'Cost of work updated') return redirect('maint-detail', id=id) # the landlord can update the status of the request elif 'status' in request.POST: status_form = StatusUpdateForm(request.POST, instance=maint_request) if status_form.is_valid(): status_form.save() messages.success(request, 'Status of request updated') return redirect('maint-detail', id=id) assign_cost_form = MaintenanceQuoteForm(instance=maint_request) status_form = StatusUpdateForm(instance=maint_request) context = { 'maint_request': maint_request, 'chat_messages': chat_messages, 'message_form': message_form, 'assign_cost_form': assign_cost_form, 'status_form': status_form, } return render(request, 'maintenance/maint_detail.html', context) else: # if current user rental does not match related property raise PermissionDenied()
def get(self, request, *args, **kwargs): self.object = self.get_object() form = MessageForm() chat_user = get_object_or_404(User, pk=kwargs["user_pk"]) non_chat_users = User.objects.exclude( id__in=self.object.users.all().values_list('id', flat=True)) context = self.get_context_data(object=self.object, form=form, chat_user=chat_user, non_chat_users=non_chat_users) return self.render_to_response(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 chat_form(request, user_id): if request.is_ajax(): queryset = User.objects.filter(id=user_id) if queryset.exists(): user = queryset.first() form = MessageForm() html = render_to_string("chat-form.html", { "user": user, "form": form }, request=request) return HttpResponse(html) else: return HttpResponseRedirect(reverse("chat:user_list"))
def post(self, request, *args, **kwargs): from chat.models import Message, Chat from chat.forms import MessageForm from django.http import HttpResponse chat, form_post = Chat.objects.get(pk=self.kwargs["pk"]), MessageForm( request.POST) message = form_post.save(commit=False) Message.save_draft_message( chat=chat, creator=request.user, text=message.text, parent=request.POST.get('parent'), attach=request.POST.getlist('attach_items'), transfer=request.POST.getlist('transfer'), ) return HttpResponse()
def MaintRequestDetail(request, id): """ If user has current rental assigned to their profile. Display detail view of particular maintenance request. Allow for landlord to assign cost to tenant/landlord """ maint_request = get_object_or_404(MaintRequest, id=id) chat_messages = ChatMessage.objects.filter( maint_request=maint_request) # get chat messages if request.user.profile.rental == maint_request.property_ref: message_form = MessageForm() if request.method == 'POST': if 'cost' in request.POST: assign_cost_form = MaintenanceQuoteForm(request.POST, request.FILES, instance=maint_request) if assign_cost_form.is_valid(): assign_cost_form.save() messages.success(request, 'Cost of work updated') return redirect('maint-detail', id=id) elif 'status' in request.POST: status_form = StatusUpdateForm(request.POST, instance=maint_request) if status_form.is_valid(): status_form.save() messages.success(request, 'Status of request updated') return redirect('maint-detail', id=id) assign_cost_form = MaintenanceQuoteForm(instance=maint_request) status_form = StatusUpdateForm(instance=maint_request) context = { 'maint_request': maint_request, 'chat_messages': chat_messages, 'message_form': message_form, 'assign_cost_form': assign_cost_form, 'status_form': status_form, } return render(request, 'maintenance/maint_detail.html', context) else: raise PermissionDenied()
def get(self, request, pk): chat = get_object_or_404(Chat, id=pk) if request.user in chat.members.all(): chat.messages.filter(is_read=False).exclude( author=request.user).update(is_read=True) chat_messages = chat.messages.all() paginator = Paginator(chat_messages, settings.PAGE_SIZE_MESSAGE, orphans=settings.PAGE_SIZE_MESSAGE) page = request.GET.get('page', paginator.num_pages) chat_messages = paginator.get_page(page) return render(request, 'chat.html', context={ 'user': request.user, 'chat': chat, 'chat_messages': chat_messages, 'form': MessageForm() })
def index(request): """ 'Calendar' page. Processes both authenticated and none-authenticated requests. """ if 'force-login' in request.GET and request.flavour == 'mobile' and not request.user.is_authenticated( ): return render(request, 'login.html') tags_provider = get_tags_provider(request) tags = tags_provider.get_tags() popular_tags, other_tags = tags_provider.get_other_tags() return render( request, 'index.html', { 'tags': tags, 'popular_tags': popular_tags, 'other_tags': other_tags, 'show_login': '******' in request.GET, 'base_tag': settings.BASE_TAG and Tag.objects.get(id=settings.BASE_TAG), 'chat_form': MessageForm(), })
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 user_messages_view(request, conv=None): if not request.user.is_authenticated: return redirect('login') if conv is None: return redirect('conversations') user = request.user conversation = user.profile.conversations.filter(name=conv)[0] form = MessageForm() if request.method == "POST": message = request.POST['message'] new_message = MessageModel(conversation=conversation, message=message) new_message.save() user.profile.messages.add(new_message) return render( request, 'accounts/user_messages.html', { 'profile_photo': request.user.profile.image, 'conversation': conversation, "message_form": form, })