• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python utils.get_datetime_now函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中userena.utils.get_datetime_now函数的典型用法代码示例。如果您正苦于以下问题:Python get_datetime_now函数的具体用法?Python get_datetime_now怎么用?Python get_datetime_now使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了get_datetime_now函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: delete_message

def delete_message(request):
    """删除消息"""
    message_pks = request.POST.getlist('message_pks')
    if message_pks:
        # Check that all values are integers.
        valid_message_pk_list = set()
        for pk in message_pks:
            try: valid_pk = int(pk)
            except (TypeError, ValueError): pass
            else:
                valid_message_pk_list.add(valid_pk)

        # Delete all the messages, if they belong to the user.
        now = get_datetime_now()
        changed_message_list = set()
        for pk in valid_message_pk_list:
            message = get_object_or_404(MessageRecipient, pk=pk).message
            # Check if the user is the owner
            if message.sender == request.user:
                message.sender_deleted_at = now
                 
                message.save()
                changed_message_list.add(message.pk)

            # Check if the user is a recipient of the message
            if request.user in message.recipients.all():
                mr = message.messagerecipient_set.get(user=request.user,
                                                      message=message)
                mr.deleted_at = now
                mr.save()
                changed_message_list.add(message.pk)

        if changed_message_list:
            messages.success(request, u"删除消息成功") 
    return redirect("oa_message_list")
开发者ID:nuannuanwu,项目名称:weixiao,代码行数:35,代码来源:message.py


示例2: read

    def read(self, request,):
        """
        与某人的沟通记录

        ``GET`` `messages/history/ <http://192.168.1.222:8080/v1/messages/history>`_

        :param uid:
            用户 id
        """
        params = request.GET
        user_id = request.GET.get("uid")
        try:
            recipient = User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return rc.NOT_HERE

        messages = Message.objects.get_conversation_between(request.user,
                                                        recipient)

       # Update all the messages that are unread.
        message_pks = [m.pk for m in messages]
        unread_list = MessageRecipient.objects.filter(message__in=message_pks,
                                                      user=request.user,
                                                      read_at__isnull=True)
        now = get_datetime_now()
        unread_list.update(read_at=now)
        return query_range_filter(params, messages, "messages")
开发者ID:nuannuanwu,项目名称:weixiao,代码行数:27,代码来源:message.py


示例3: delete

    def delete(self, request):
        """
        删除一条信息

        ``POST`` `messages/destroy/ <http://192.168.1.222:8080/v1/messages/destroy>`_

        :param id:
            该信息的 id
        """
        message_id = request.POST.get("id")
        if not message_id:
            return rc.BAD_REQUEST

        try:
            message = Message.objects.get(pk=message_id)
        except Message.DoesNotExist:
            return rc.NOT_HERE

        now = get_datetime_now()
        if message.sender == request.user:
            message.sender_deleted_at = now
            message.save()

        if request.user in message.recipients.all():
            mr = message.messagerecipient_set.get(user=request.user,
                                                  message=message)
            mr.deleted_at = now
            mr.save()

        return rc.accepted({"result": True})
开发者ID:nuannuanwu,项目名称:weixiao,代码行数:30,代码来源:message.py


示例4: _update_unread_messages

 def _update_unread_messages(self, queryset):
     message_pks = [m.pk for m in queryset]
     unread_list = MessageRecipient.objects.filter(
         message__in=message_pks, user=self.request.user, read_at__isnull=True
     )
     now = get_datetime_now()
     unread_list.update(read_at=now)
开发者ID:iterativ,项目名称:django-userena,代码行数:7,代码来源:views.py


示例5: create_user

    def create_user(self, username, email, password, active=False,
                    send_email=True, first_name=None, last_name=None):
        """
        A simple wrapper that creates a new :class:`User`.

        :param username:
            String containing the username of the new user.

        :param email:
            String containing the email address of the new user.

        :param password:
            String containing the password for the new user.

        :param active:
            Boolean that defines if the user requires activation by clicking 
            on a link in an e-mail. Defaults to ``False``.

        :param send_email:
            Boolean that defines if the user should be sent an email. You could
            set this to ``False`` when you want to create a user in your own
            code, but don't want the user to activate through email.

        :return: :class:`User` instance representing the new user.

        """
        now = get_datetime_now()

        new_user = User.objects.create_user(username, email, password)
        new_user.is_active = active
        if first_name is not None:
            new_user.first_name = first_name
        if last_name is not None:
            new_user.last_name = last_name
        new_user.save()

        userena_profile = self.create_userena_profile(new_user)

        # All users have an empty profile
        profile_model = get_profile_model()
        try:
            new_profile = new_user.get_profile()
        except profile_model.DoesNotExist:
            new_profile = profile_model(user=new_user)
            new_profile.save(using=self._db)

        # Give permissions to view and change profile
        for perm in ASSIGNED_PERMISSIONS['profile']:
            assign(perm[0], new_user, new_profile)

        # Give permissions to view and change itself
        for perm in ASSIGNED_PERMISSIONS['user']:
            assign(perm[0], new_user, new_user)

        if send_email:
            userena_profile.send_activation_email()
 
        return new_user
开发者ID:adamfeuer,项目名称:django-userena,代码行数:58,代码来源:managers.py


示例6: message_detail

def message_detail(request, username, page=1, paginate_by=10,
                   template_name="umessages/message_detail.html",
                   extra_context=None, **kwargs):
    """
    Returns a conversation between two users

    :param username:
        String containing the username of :class:`User` of whom the
        conversation is with.

    :param page:
        Integer of the active page used for pagination. Defaults to the first
        page.

    :param paginate_by:
        Integer defining the amount of displayed messages per page.
        Defaults to 50 messages per per page.

    :param extra_context:
        Dictionary of variables that will be made available to the template.

    :param template_name:
        String of the template that is rendered to display this view.

    If the result is paginated, the context will also contain the following
    variables.

    ``paginator``
        An instance of ``django.core.paginator.Paginator``.

    ``page_obj``
        An instance of ``django.core.paginator.Page``.

    """
    recipient = get_object_or_404(User,
                                  username__iexact=username)
    queryset = Message.objects.get_conversation_between(request.user,
                                                        recipient)

    # Update all the messages that are unread.
    message_pks = [m.pk for m in queryset]
    unread_list = MessageRecipient.objects.filter(message__in=message_pks,
                                                  user=request.user,
                                                  read_at__isnull=True)
    now = get_datetime_now()
    unread_list.update(read_at=now)

    if not extra_context: extra_context = dict()
    extra_context['recipient'] = recipient
    return list_detail.object_list(request,
                                   queryset=queryset,
                                   paginate_by=paginate_by,
                                   page=page,
                                   template_name=template_name,
                                   extra_context=extra_context,
                                   template_object_name="message",
                                   **kwargs)
开发者ID:barszczmm,项目名称:django-easy-userena,代码行数:57,代码来源:views.py


示例7: post

    def post(self, request):
        user = request.user
        new_email = request.data.get('email', None)

        try:

            if not new_email:
                raise AccountException(constants.INVALID_PARAMETERS)
            if new_email.lower() == user.email:
                raise AccountException(constants.EMAIL_NOT_CHANGED)
            if User.objects.filter(email__iexact=new_email):
                raise AccountException(constants.EMAIL_IN_USE)

            # the following is a rewritten version of user.userena_signup.change_email(new_email)
            user.userena_signup.email_unconfirmed = new_email
            salt, hash = generate_sha1(user.username)
            user.userena_signup.email_confirmation_key = hash
            user.userena_signup.email_confirmation_key_created = get_datetime_now()
            user.userena_signup.save()

            # the purpose is rewriting the following part where the emails are sent out
            email_change_url = settings.USER_BASE_URL +\
                settings.MAIL_EMAIL_CHANGE_CONFIRM_URL.format(user.userena_signup.email_confirmation_key)

            context = {
                'user': user,
                'email_change_url': email_change_url
            }

            # mail to new email account
            mails.send_mail(
                subject_template_name=settings.MAIL_CHANGE_EMAIL_NEW_SUBJECT,
                email_template_name=settings.MAIL_CHANGE_EMAIL_NEW_TEXT,
                html_email_template_name=settings.MAIL_CHANGE_EMAIL_NEW_HTML,
                to_email=user.userena_signup.email_unconfirmed,
                from_email=settings.BEAM_MAIL_ADDRESS,
                context=context
            )

            context['support'] = settings.BEAM_SUPPORT_MAIL_ADDRESS
            context['new_email'] = user.userena_signup.email_unconfirmed

            # mail to old email account
            mails.send_mail(
                subject_template_name=settings.MAIL_CHANGE_EMAIL_OLD_SUBJECT,
                email_template_name=settings.MAIL_CHANGE_EMAIL_OLD_TEXT,
                html_email_template_name=settings.MAIL_CHANGE_EMAIL_OLD_HTML,
                to_email=user.email,
                from_email=settings.BEAM_MAIL_ADDRESS,
                context=context
            )
            return Response()

        except AccountException as e:
            return Response({'detail': e.args[0]}, status=status.HTTP_400_BAD_REQUEST)
开发者ID:fbenke,项目名称:BeamPay,代码行数:55,代码来源:views.py


示例8: unread_count

    def unread_count(self, request):
        """
        获取某个用户的各种消息未读数

        ``GET`` `remind/unread_count/ <http://192.168.1.222:8080/v1/remind/unread_count>`_

        """
        user = request.user
        class_id = request.GET.get("class_id")
        try:
            teacher = user.teacher
            if teacher:
                tile_count = 0
                push_tile_count = 0
        except Teacher.DoesNotExist:
            tile_count = Tile.objects.count_unread_tiles_for(user)
            push_tile_count = Tile.objects.count_unread_push_tiles_for(user)
        
        if class_id:
            now = get_datetime_now()
            try:
                group = Group.objects.get(pk=class_id)
            except Group.DoesNotExist:
                return rc.NOT_HERE
            
            group_user = []
            teacher_user = [t.user for t in group.teachers.all()]
            group_user.extend(teacher_user)
            
            student_user = [s.user for s in group.students.all()]
            group_user.extend(student_user)
            
            messages_count = MessageRecipient.objects.filter(user=user,read_at__isnull=True,message__sent_at__lte=now,\
                                       deleted_at__isnull=True,message__sender__in=group_user).count()
            
        else:
            messages_count = MessageRecipient.objects.count_unread_messages_for(request.user)
        
        unread_contact = {}
        try:
            unread_list = MessageRecipient.objects.filter(user=request.user,read_at__isnull=True,deleted_at__isnull=True)
            unread_list.update(no_need_send=1)

            for m in unread_list:
                sender_id = m.message.sender.id
                unread_contact.setdefault(sender_id,0)  
            for m in unread_list:
                sender_id = m.message.sender.id
                unread_contact[sender_id] += 1
        except:
            pass
        
        notify_count = Notification.objects.count_notify_group(user)    
        return {"messages": messages_count,'tile_count':tile_count,'push_tile_count':push_tile_count,'notify_count':notify_count,'messages_info':unread_contact}
开发者ID:nuannuanwu,项目名称:weixiao,代码行数:54,代码来源:message.py


示例9: activation_key_expired

    def activation_key_expired(self):
        """
        Checks if activation key is expired.

        Returns ``True`` when the ``activation_key`` of the user is expired and
        ``False`` if the key is still valid.

        The key is expired when it's set to the value defined in
        ``USERENA_ACTIVATED`` or ``activation_key_created`` is beyond the
        amount of days defined in ``USERENA_ACTIVATION_DAYS``.

        """
        expiration_days = datetime.timedelta(days=userena_settings.USERENA_ACTIVATION_DAYS)
        expiration_date = self.user.date_joined + expiration_days
        the_datetime_now = get_datetime_now()
        get_datetime_now_is_aware = is_aware(the_datetime_now)
        expiration_date_is_aware = is_aware(expiration_date)
        if is_aware(the_datetime_now) and is_naive(expiration_date):
            expiration_date = pytz.utc.localize(expiration_date) 
        if self.activation_key == userena_settings.USERENA_ACTIVATED:
            return True
        if get_datetime_now() >= expiration_date:
            return True
        return False
开发者ID:shafiquejamal,项目名称:django-userena,代码行数:24,代码来源:models.py


示例10: upload_to_mugshot

def upload_to_mugshot(instance, filename):
    """
    Uploads a mugshot for a user to the ``USERENA_MUGSHOT_PATH`` and saving it
    under unique hash for the image. This is for privacy reasons so others
    can't just browse through the mugshot directory.

    """
    extension = filename.split('.')[-1].lower()
    salt, hash = generate_sha1(instance.id)
    path = userena_settings.USERENA_MUGSHOT_PATH % {'username': instance.user.username,
                                                    'id': instance.user.id,
                                                    'date': instance.user.date_joined,
                                                    'date_now': get_datetime_now().date()}
    return '%(path)s%(hash)s.%(extension)s' % {'path': path,
                                               'hash': hash[:10],
                                               'extension': extension}
开发者ID:MarvelICY,项目名称:django-userena,代码行数:16,代码来源:models.py


示例11: upload_to_mugshot

def upload_to_mugshot(instance, filename):
    """
    Uploads a mugshot for a user to the ``USERENA_MUGSHOT_PATH`` and saving it
    under unique hash for the image. This is for privacy reasons so others
    can't just browse through the mugshot directory.

    """
    extension = filename.split(".")[-1].lower()
    salt, hash = generate_sha1(instance.id)
    path = userena_settings.USERENA_MUGSHOT_PATH % {
        "username": instance.user.username,
        "id": instance.user.id,
        "date": instance.user.date_joined,
        "date_now": get_datetime_now().date(),
    }
    return "%(path)s%(hash)s.%(extension)s" % {"path": path, "hash": hash[:10], "extension": extension}
开发者ID:gobelins,项目名称:django-userena,代码行数:16,代码来源:models.py


示例12: user_message_history

def user_message_history(request, user_id,compose_form=ComposeForm,\
                    success_url=None,template_name="oa/message_history.html"):
    """消息记录"""
    recipient = User.objects.get(id=user_id)
    
    queryset = Message.objects.get_conversation_between(request.user,
                                                        recipient).filter(is_send=True)
    # history 页面可以直接发送信息
    initial_data = dict() 
    initial_data["to"] = recipient
    form = compose_form(initial=initial_data)
    # 发布私信
    if request.method == "POST":
        form = compose_form(request.POST)
        if form.is_valid():
#             requested_redirect = request.REQUEST.get("next", False)
            message = form.save(request.user)
            message.is_send = True
            message.save()
            recipients = form.cleaned_data['to']
            if userena_settings.USERENA_USE_MESSAGES:
                messages.success(request, _('Message is sent.'),fail_silently=True)

#             return redirect("oa_message_history")

    # Update all the messages that are unread.
    page = int(request.GET.get("page", '1'))
    start = (page - 1) * 10
    end = page * 10 
    message_pks = [m.pk for m in queryset[start:end]]
    
    
    unread_list = MessageRecipient.objects.filter(message__in=message_pks,
                                                  user=request.user,
                                                  read_at__isnull=True)
    now = get_datetime_now()
    unread_list.update(read_at=now)

    ctx = dict()
    ctx['recipient'] = recipient
    ctx["form"] = form

    message_list = queryset
    ctx.update({"message_list":message_list})
    return render(request, template_name, ctx)
开发者ID:nuannuanwu,项目名称:weixiao,代码行数:45,代码来源:message.py


示例13: upload_to_thumbnail

def upload_to_thumbnail(instance, filename):
    """
    103,143
    Uploads a thumbnail for a user to the ``EBOOK_THUMBNAIL_PATH`` and saving it
    under unique hash for the image. This is for privacy reasons so others
    can't just browse through the mugshot directory.

    """
    #extension = filename.split('.')[-1].lower()
    extension = 'jpg_103'  
    salt, hash = generate_sha1(instance.id)
    path = ebook_settings.EBOOK_THUMBNAIL_PATH % {'username': instance.created_by.username,
                                                    'id': instance.created_by.id,
                                                    'date': instance.created_by.date_joined,
                                                    'date_now': get_datetime_now().date()}
    return 'thumbnail/products/%(path)s_%(hash)s.%(extension)s' % {'path': path,
                                               'hash': hash[:10],
                                               'extension': extension}
开发者ID:jerryxing98,项目名称:Tully,代码行数:18,代码来源:models.py


示例14: reissue_activation

def reissue_activation(activation_key):
    '''
    Rewritten version of UserenaSignup.objects.reissue_activation()
    to customize the sent email
    '''

    try:
        userena = UserenaSignup.objects.get(activation_key=activation_key)
    except UserenaSignup.objects.model.DoesNotExist:
        return None
    try:
        salt, new_activation_key = generate_sha1(userena.user.username)
        userena.activation_key = new_activation_key
        userena.save(using=UserenaSignup.objects._db)
        userena.user.date_joined = get_datetime_now()
        userena.user.save(using=UserenaSignup.objects._db)
        return new_activation_key
    except Exception:
        return None
开发者ID:fbenke,项目名称:BeamRemit,代码行数:19,代码来源:views.py


示例15: update_unread_message

def update_unread_message(request,):
	try:		
		userid = request.GET['userid']
		recipientid = request.GET['recipientid']

		user = get_object_or_404(User,pk=userid)
		recipient = get_object_or_404(User,pk=recipientid)

		# 找到 user 发给 recipient 的消息。
		queryset = Message.objects.filter(Q(sender=user, recipients=recipient,
	                                 messagerecipient__deleted_at__isnull=True))
	    
		message_pks = [m.pk for m in queryset]
	    
	    # 更新 user 发给 recipient 的未读消息
		unread_list = MessageRecipient.objects.filter(message__in=message_pks,
	                                                  user=recipient,
	                                                  read_at__isnull=True)
		now = get_datetime_now()
		unread_list.update(read_at=now)
		return ajax_ok('消息发送成功')
	except:
		return ajax_error('消息发送失败')
开发者ID:nuannuanwu,项目名称:weixiao,代码行数:23,代码来源:default.py


示例16: change_email

    def change_email(self, email):
        """
        Changes the email address for a user.

        A user needs to verify this new email address before it becomes
        active. By storing the new email address in a temporary field --
        ``temporary_email`` -- we are able to set this email address after the
        user has verified it by clicking on the verification URI in the email.
        This email gets send out by ``send_verification_email``.

        :param email:
            The new email address that the user wants to use.

        """
        self.email_unconfirmed = email

        salt, hash = generate_sha1(self.user.username)
        self.email_confirmation_key = hash
        self.email_confirmation_key_created = get_datetime_now()
        self.save()

        # Send email for activation
        self.send_confirmation_email()
开发者ID:nuannuanwu,项目名称:weixiao,代码行数:23,代码来源:models.py


示例17: reissue_activation

    def reissue_activation(self, activation_key):
        """
        Creates a new ``activation_key`` resetting activation timeframe when
        users let the previous key expire.

        :param activation_key:
            String containing the secret SHA1 activation key.

        """
        try:
            userena = self.get(activation_key=activation_key)
        except self.model.DoesNotExist:
            return False
        try:
            salt, new_activation_key = generate_sha1(userena.user.username)
            userena.activation_key = new_activation_key
            userena.save(using=self._db)
            userena.user.date_joined = get_datetime_now()
            userena.user.save(using=self._db)
            userena.send_activation_email()
            return True
        except Exception:
            return False
开发者ID:bioinformatics-ua,项目名称:django-userena,代码行数:23,代码来源:managers.py


示例18: message_remove

def message_remove(request, undo=False):
    """
    A ``POST`` to remove messages.

    :param undo:
        A Boolean that if ``True`` unremoves messages.

    POST can have the following keys:

        ``message_pks``
            List of message id's that should be deleted.

        ``next``
            String containing the URI which to redirect to after the keys are
            removed. Redirect defaults to the inbox view.

    The ``next`` value can also be supplied in the URI with ``?next=<value>``.

    """
    message_pks = request.POST.getlist('message_pks')
    redirect_to = request.REQUEST.get('next', False)

    if message_pks:
        # Check that all values are integers.
        valid_message_pk_list = set()
        for pk in message_pks:
            try: valid_pk = int(pk)
            except (TypeError, ValueError): pass
            else:
                valid_message_pk_list.add(valid_pk)

        # Delete all the messages, if they belong to the user.
        now = get_datetime_now()
        changed_message_list = set()
        for pk in valid_message_pk_list:
            message = get_object_or_404(Message, pk=pk)

            # Check if the user is the owner
            if message.sender == request.user:
                if undo:
                    message.sender_deleted_at = None
                else:
                    message.sender_deleted_at = now
                message.save()
                changed_message_list.add(message.pk)

            # Check if the user is a recipient of the message
            if request.user in message.recipients.all():
                mr = message.messagerecipient_set.get(user=request.user,
                                                      message=message)
                if undo:
                    mr.deleted_at = None
                else:
                    mr.deleted_at = now
                mr.save()
                changed_message_list.add(message.pk)

        # update contact last message
        recipient_id = request.POST.get('recipient', False)
        if recipient_id:
            recipient = get_object_or_404(User, pk=recipient_id)
            if recipient:
                if message.sender == request.user:
                    to_user = recipient
                    from_user = request.user
                else:
                    to_user = request.user
                    from_user = recipient

                message_list = Message.objects.get_conversation_between(request.user, recipient)[:1]
                print message_list,"==============="
                if message_list:
                    for one in message_list:
                        print one,"oooooooooooo"
                        MessageContact.objects.update_contact(request.user,recipient,one)
                else:
                    contact = MessageContact.objects.get(Q(from_user=request.user, to_user=recipient))
                    print contact,"===========2222222"
                    if contact:
                        contact.delete()


        # Send messages
        if (len(changed_message_list) > 0) and userena_settings.USERENA_USE_MESSAGES:
            if undo:
                message = ungettext('Message is succesfully restored.',
                                    'Messages are succesfully restored.',
                                    len(changed_message_list))
            else:
                message = ungettext('Message is successfully removed.',
                                    'Messages are successfully removed.',
                                    len(changed_message_list))


    if request.is_ajax():
        return ajax_ok(message)
    else:
        messages.success(request, message, fail_silently=True)
        if redirect_to: return redirect(redirect_to)
        else: return redirect(reverse('userena_umessages_list'))
开发者ID:nuannuanwu,项目名称:weixiao,代码行数:100,代码来源:message.py


示例19: message_remove

def message_remove(request, undo=False):
    """
    """
    message_pks = request.POST.getlist('message_pks')
    if message_pks:
        # Check that all values are integers.
        valid_message_pk_list = set()
        for pk in message_pks:
            try: valid_pk = int(pk)
            except (TypeError, ValueError): pass
            else:
                valid_message_pk_list.add(valid_pk)

        # Delete all the messages, if they belong to the user.
        now = get_datetime_now()
        changed_message_list = set()
        print valid_message_pk_list,'valid_message_pk_list'
        for pk in valid_message_pk_list:
            message = get_object_or_404(Message, pk=pk)

            # Check if the user is the owner
            if message.sender == request.user:
                if undo:
                    message.sender_deleted_at = None
                else:
                    message.sender_deleted_at = now
                message.save()
                changed_message_list.add(message.pk)

            # Check if the user is a recipient of the message
            if request.user in message.recipients.all():
                mr = message.messagerecipient_set.get(user=request.user,
                                                      message=message)
                if undo:
                    mr.deleted_at = None
                else:
                    mr.deleted_at = now
                mr.save()
                changed_message_list.add(message.pk)

        # update contact last message
        recipient_id = request.POST.get('recipient', False)
        if recipient_id:
            recipient = get_object_or_404(User, pk=recipient_id)
            if recipient:
                if message.sender == request.user:
                    to_user = recipient
                    from_user = request.user
                else:
                    to_user = request.user
                    from_user = recipient

                message_list = Message.objects.get_conversation_between(request.user, recipient)[:1]
                if message_list:
                    for one in message_list:
                        MessageContact.objects.update_contact(request.user,recipient,one)
                else:
                    contact = MessageContact.objects.get(Q(from_user=request.user, to_user=recipient))
                    if contact:
                        contact.delete()


        # Send messages
        if (len(changed_message_list) > 0) and userena_settings.USERENA_USE_MESSAGES:
            if undo:
                message = ungettext('Message is succesfully restored.',
                                    'Messages are succesfully restored.',
                                    len(changed_message_list))
            else:
                message = ungettext('Message is successfully removed.',
                                    'Messages are successfully removed.',
                                    len(changed_message_list))
开发者ID:nuannuanwu,项目名称:weixiao,代码行数:72,代码来源:message.py


示例20: message_remove

def message_remove(request, undo=False):
    """
    A ``POST`` to remove messages.

    :param undo:
        A Boolean that if ``True`` unremoves messages.

    POST can have the following keys:

        ``message_pks``
            List of message id's that should be deleted.

        ``next``
            String containing the URI which to redirect to after the keys are
            removed. Redirect defaults to the inbox view.

    The ``next`` value can also be supplied in the URI with ``?next=<value>``.

    """
    message_pks = request.POST.getlist("message_pks")
    redirect_to = request.GET.get(REDIRECT_FIELD_NAME, request.POST.get(REDIRECT_FIELD_NAME, False))

    if message_pks:
        # Check that all values are integers.
        valid_message_pk_list = set()
        for pk in message_pks:
            try:
                valid_pk = int(pk)
            except (TypeError, ValueError):
                pass
            else:
                valid_message_pk_list.add(valid_pk)

        # Delete all the messages, if they belong to the user.
        now = get_datetime_now()
        changed_message_list = set()
        for pk in valid_message_pk_list:
            message = get_object_or_404(Message, pk=pk)

            # Check if the user is the owner
            if message.sender == request.user:
                if undo:
                    message.sender_deleted_at = None
                else:
                    message.sender_deleted_at = now
                message.save()
                changed_message_list.add(message.pk)

            # Check if the user is a recipient of the message
            if request.user in message.recipients.all():
                mr = message.messagerecipient_set.get(user=request.user, message=message)
                if undo:
                    mr.deleted_at = None
                else:
                    mr.deleted_at = now
                mr.save()
                changed_message_list.add(message.pk)

        # Send messages
        if (len(changed_message_list) > 0) and userena_settings.USERENA_USE_MESSAGES:
            if undo:
                message = ungettext(
                    "Message is succesfully restored.", "Messages are succesfully restored.", len(changed_message_list)
                )
            else:
                message = ungettext(
                    "Message is successfully removed.", "Messages are successfully removed.", len(changed_message_list)
                )

            messages.success(request, message, fail_silently=True)

    if redirect_to:
        return redirect(redirect_to)
    else:
        return redirect(reverse("userena_umessages_list"))
开发者ID:iterativ,项目名称:django-userena,代码行数:75,代码来源:views.py



注:本文中的userena.utils.get_datetime_now函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python utils.get_gravatar函数代码示例发布时间:2022-05-27
下一篇:
Python utils.generate_sha1函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap