Python django.contrib.messages 模块,add_message() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.contrib.messages.add_message()

项目:django-simplestore    作者:martinstastny    | 项目源码 | 文件源码
def form_valid(self, form):
        self.profile = form.save()
        self.request.session['user_cart'] = self.request.session.session_key

        user = authenticate(
            email=self.profile.email,
            password=self.request.POST['password1']
        )

        messages.add_message(
            self.request, messages.SUCCESS,
            'You were successfully logged in.'
        )

        login(self.request, user)
        return super(RegistrationFormView, self).form_valid(form)
项目:django-simplestore    作者:martinstastny    | 项目源码 | 文件源码
def form_valid(self, form):

        cart = get_cart(self.request, create=True)
        user = authenticate(email=self.request.POST['email'], password=self.request.POST['password'])

        if user is not None and user.is_active:
            self.request.session['user_cart'] = self.request.session.session_key
            login(self.request, user)

            if cart is not None:
                cart.user = Profile.objects.get(id=user.id)
                cart.save()
                messages.add_message(self.request, messages.SUCCESS, 'You were successfully logged in.')

            return super(AuthenticationForm, self).form_valid(form)

        else:
            response = super(AuthenticationForm, self).form_invalid(form)
            messages.add_message(self.request, messages.WARNING, 'Wrong email or password. Please try again')
            return response


# Logout View
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def message_user(self, request, message, level=messages.INFO, extra_tags='',
                     fail_silently=False):
        """
        Send a message to the user. The default implementation
        posts a message using the django.contrib.messages backend.

        Exposes almost the same API as messages.add_message(), but accepts the
        positional arguments in a different order to maintain backwards
        compatibility. For convenience, it accepts the `level` argument as
        a string rather than the usual level number.
        """

        if not isinstance(level, int):
            # attempt to get the level if passed a string
            try:
                level = getattr(messages.constants, level.upper())
            except AttributeError:
                levels = messages.constants.DEFAULT_TAGS.values()
                levels_repr = ', '.join('`%s`' % l for l in levels)
                raise ValueError('Bad message level string: `%s`. '
                        'Possible values are: %s' % (level, levels_repr))

        messages.add_message(request, level, message, extra_tags=extra_tags,
                fail_silently=fail_silently)
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
def message_user(self, request, message, level=messages.INFO, extra_tags='',
                     fail_silently=False):
        """
        Send a message to the user. The default implementation
        posts a message using the django.contrib.messages backend.

        Exposes almost the same API as messages.add_message(), but accepts the
        positional arguments in a different order to maintain backwards
        compatibility. For convenience, it accepts the `level` argument as
        a string rather than the usual level number.
        """
        if not isinstance(level, int):
            # attempt to get the level if passed a string
            try:
                level = getattr(messages.constants, level.upper())
            except AttributeError:
                levels = messages.constants.DEFAULT_TAGS.values()
                levels_repr = ', '.join('`%s`' % l for l in levels)
                raise ValueError(
                    'Bad message level string: `%s`. Possible values are: %s'
                    % (level, levels_repr)
                )

        messages.add_message(request, level, message, extra_tags=extra_tags, fail_silently=fail_silently)
项目:CoBL-public    作者:lingdb    | 项目源码 | 文件源码
def alter_profile(request, username=None):
    if username:
        the_user = get_object_or_404(User, username__exact=username)
    else:
        the_user = request.user
    if request.method == 'POST':
        redirect_url = reverse("view-profile-user", args=[the_user.username])
        form = UserAlterDetailsForm(request.POST)
        if "cancel" in form.data:  # has to be tested before data is cleaned
            return HttpResponseRedirect(redirect_url)
        assert form.is_valid()
        if form.is_valid():
            for key in form.cleaned_data:
                setattr(the_user, key, form.cleaned_data[key])
            the_user.save()
            msg = "Profile details changed"
            messages.add_message(request, messages.INFO, msg)
            return HttpResponseRedirect(redirect_url)
    else:
        # form = UserAlterDetailsForm(initial=the_user.__dict__)
        form = UserAlterDetailsForm(instance=the_user)
    return render_template(request, "profiles/alter_profile.html",
                           {"the_user": the_user,
                            "form": form})
项目:Scrum    作者:prakharchoudhary    | 项目源码 | 文件源码
def message_user(self, request, message, level=messages.INFO, extra_tags='',
                     fail_silently=False):
        """
        Send a message to the user. The default implementation
        posts a message using the django.contrib.messages backend.

        Exposes almost the same API as messages.add_message(), but accepts the
        positional arguments in a different order to maintain backwards
        compatibility. For convenience, it accepts the `level` argument as
        a string rather than the usual level number.
        """
        if not isinstance(level, int):
            # attempt to get the level if passed a string
            try:
                level = getattr(messages.constants, level.upper())
            except AttributeError:
                levels = messages.constants.DEFAULT_TAGS.values()
                levels_repr = ', '.join('`%s`' % l for l in levels)
                raise ValueError(
                    'Bad message level string: `%s`. Possible values are: %s'
                    % (level, levels_repr)
                )

        messages.add_message(request, level, message, extra_tags=extra_tags, fail_silently=fail_silently)
项目:travel_buddy    作者:bribenn    | 项目源码 | 文件源码
def register(request):
    check = User.objects.validateUser(request.POST)
    if request.method != 'POST':
        return redirect('/')
    if check[0] == False:
        for error in check[1]:
            messages.add_message(request, messages.INFO, error, extra_tags="registration")
            return redirect('/')
    if check[0] == True:
        #has password
        hashed_pw = bcrypt.hashpw(request.POST.get('password').encode(), bcrypt.gensalt())
        #create user
        user = User.objects.create(
            first_name = request.POST.get('first_name'),
            last_name = request.POST.get('last_name'),
            email = request.POST.get('email'),  
            password = hashed_pw,
        )

        #add user to session, logging them in
        request.session['user_id'] = user.id
        #route to user profile page
        return redirect('/user')
项目:EnglishDiary    作者:jupiny    | 项目源码 | 文件源码
def post(self, request, *args, **kwargs):
        verification_key = request.POST.get("verification_key")
        profile = get_object_or_404(Profile, verification_key=verification_key)
        user = profile.user

        # Renew user verification key
        profile.verification_key = generate_user_activation_key(user.id)
        profile.key_expires = set_expiration_date(settings.KEY_EXPIRES_DAY)
        profile.save()

        # Resend user verification email
        task = ResendVerificationEmailTask()
        task.delay(user.id)

        messages.add_message(
            request,
            messages.SUCCESS,
            settings.RESEND_EMAIL_VERIFICATION_MESSAGE,
        )

        return redirect(reverse("home"))
项目:autostew    作者:Autostew    | 项目源码 | 文件源码
def login_view(request):
    if request.POST:
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                messages.add_message(request, messages.SUCCESS, "Login successful.", extra_tags='success')
                return redirect('account:home')
            else:
                messages.add_message(request, messages.ERROR, "You account is disabled.", extra_tags='danger')
                return redirect('account:login')
        else:
            messages.add_message(request, messages.ERROR, "Your username and/or your password is incorrect.", extra_tags='warning')
            return redirect('account:login')
    else:
        if request.user.is_authenticated():
            return redirect('account:home')
        else:
            return render(request, 'autostew_web_account/login.html')
项目:autostew    作者:Autostew    | 项目源码 | 文件源码
def add_view(request):
    if request.POST:
        Server.objects.create(
            name=request.POST.get('name'),
            api_username=request.POST.get('api_username'),
            api_password=request.POST.get('api_password'),
            api_address=request.POST.get('api_address'),
            api_port=request.POST.get('api_port'),
            owner=request.user,
            max_member_count=32,
        )
        messages.add_message(
            request,
            messages.SUCCESS,
            "Your DS has been registered. It will be manually verified and activated, so please be patient as this may take some times (from hours up to some days if we are currently too busy).",
            extra_tags='success'
        )
        return redirect('account:home')
    else:
        return render(request, 'autostew_web_account/add_server.html')
项目:nrp    作者:django-rea    | 项目源码 | 文件源码
def is_open(self):
        code = self.request.REQUEST.get("code")
        if code:
            try:
                self.signup_code = SignupCode.check_in_signupcode(code)
            except SignupCode.InvalidCode:
                if not settings.ACCOUNT_OPEN_SIGNUP:
                    return False
                else:
                    if self.messages.get("invalid_signup_code"):
                        messages.add_message(
                            self.request,
                            self.messages["invalid_signup_code"]["level"],
                            self.messages["invalid_signup_code"]["text"] % {
                                "code": code
                            }
                        )
                    return True
            else:
                return True
        else:
            return settings.ACCOUNT_OPEN_SIGNUP
项目:nrp    作者:django-rea    | 项目源码 | 文件源码
def post(self, *args, **kwargs):
        self.object = confirmation = self.get_object()
        confirmation.confirm()
        user = confirmation.email_address.user
        user.is_active = True
        user.save()
        redirect_url = self.get_redirect_url()
        if not redirect_url:
            ctx = self.get_context_data()
            return self.render_to_response(ctx)
        if self.messages.get("email_confirmed"):
            messages.add_message(
                self.request,
                self.messages["email_confirmed"]["level"],
                self.messages["email_confirmed"]["text"] % {
                    "email": confirmation.email_address.email
                }
            )
        return redirect(redirect_url)
项目:steemprojects.com    作者:noisy    | 项目源码 | 文件源码
def edit_timeline(request, slug, template_name="package/timeline_form.html"):
    project = get_object_or_404(Project, slug=slug)
    if not request.user.profile.can_edit_package(project):
        return HttpResponseForbidden("permission denied")

    if request.POST:
        formset = TimelineEventFormSet(data=request.POST, project=project,)
    else:
        formset = TimelineEventFormSet(project=project, queryset=TimelineEvent.objects.filter(project=project))

    if formset.is_valid():
        formset.save()

        messages.add_message(request, messages.INFO, 'Project updated successfully')
        return HttpResponseRedirect(reverse("package", kwargs={"slug": project.slug}))

    return render(request, template_name, {
        "formset": formset,
        "package": project,
        "action": "Save",
    })
项目:steemprojects.com    作者:noisy    | 项目源码 | 文件源码
def edit_images(request, slug, template_name="package/images_form.html"):
    project = get_object_or_404(Project, slug=slug)
    if not request.user.profile.can_edit_package(project):
        return HttpResponseForbidden("permission denied")

    if request.POST:
        formset = ProjectImagesFormSet(data=request.POST, files=request.FILES, project=project,)
    else:
        formset = ProjectImagesFormSet(project=project, queryset=ProjectImage.objects.filter(project=project))

    if formset.is_valid():
        formset.save()

        messages.add_message(request, messages.INFO, 'Project updated successfully')
        return HttpResponseRedirect(reverse("package", kwargs={"slug": project.slug}))

    return render(request, template_name, {
        "formset": formset,
        "package": project,
        "action": "Save",
    })
项目:steemprojects.com    作者:noisy    | 项目源码 | 文件源码
def edit_grid(request, slug, template_name="grid/update_grid.html"):
    """View to modify the grid, handles GET and POST requests.
    This view requires user to be logged in.

    Template context:

    * ``form`` - instance of :class:`grid.forms.GridForm`
    """

    if not request.user.profile.can_edit_grid:
        return HttpResponseForbidden("permission denied")

    grid = get_object_or_404(Grid, slug=slug)
    form = GridForm(request.POST or None, instance=grid)

    if form.is_valid():
        grid = form.save()
        message = "Grid has been edited"
        messages.add_message(request, messages.INFO, message)
        return HttpResponseRedirect(reverse('grid', kwargs={'slug': grid.slug}))
    return render(request, template_name, {'form': form,  'grid': grid})
项目:nightreads    作者:avinassh    | 项目源码 | 文件源码
def post(self, request, pk):
        email_type = request.POST.get('type', '').lower()
        email_obj = Email.objects.get(pk=pk)
        if email_type == 'preview':
            send_email_obj(email_obj=email_obj, preview=True)
            m = 'Preview email has been sent!'
        else:
            email_obj.recipients = get_subscriber_emails(email_obj=email_obj)
            m = 'Email has been sent!'
            send_email_obj(email_obj=email_obj)
            email_obj.is_sent = True
            email_obj.targetted_users = len(email_obj.recipients)
            email_obj.save()
        messages.add_message(request, messages.INFO, m)
        return redirect(reverse(
            'admin:emails_email_change', args=(email_obj.id,)))
项目:portailva    作者:BdEINSALyon    | 项目源码 | 文件源码
def form_valid(self, form):
        self.request.user.set_password(form.data.get('password_new'))
        self.request.user.save()
        update_session_auth_hash(self.request, self.request.user)

        send_mail(
            template_html_name='mail/member/reset_password.html',
            template_text_name='mail/member/reset_password.text',
            context={},
            subject="Redéfinition de votre mot de passe",
            to=self.request.user.email
        )

        messages.add_message(self.request, messages.SUCCESS, "Votre mot de passe a été changé avec succès.")

        return redirect(reverse('homepage'))
项目:portailva    作者:BdEINSALyon    | 项目源码 | 文件源码
def post(self, request, *args, **kwargs):
        if not request.user.has_perm('file.manage_resources'):
            raise PermissionDenied

        parent = self._get_folder()
        form = ResourceFolderForm(folder=parent, data=self.request.POST)

        folder = ResourceFolder.objects.filter(parent=parent, name=form.data['name']).first()
        if folder is not None:
            messages.add_message(request, messages.ERROR, 'Un dossier existe déjà avec ce nom')
        else:
            folder = ResourceFolder.objects.create(
                name=form.data['name'],
                parent=parent
            )
            messages.add_message(request, messages.SUCCESS, 'Dossier créé')
        return redirect(reverse('resource-folder-list', kwargs={'folder_pk': folder.id}))
项目:wagtail_room_booking    作者:Tamriel    | 项目源码 | 文件源码
def post(self, *args, **kwargs):
        self.object = confirmation = self.get_object()
        confirmation.confirm()
        self.after_confirmation(confirmation)
        redirect_url = self.get_redirect_url()
        if not redirect_url:
            ctx = self.get_context_data()
            return self.render_to_response(ctx)
        if self.messages.get("email_confirmed"):
            messages.add_message(
                    self.request,
                    self.messages["email_confirmed"]["level"],
                    self.messages["email_confirmed"]["text"].format(**{
                        "email": confirmation.email_address.email
                    })
            )
        return redirect(redirect_url)
项目:club-suite    作者:fsxfreak    | 项目源码 | 文件源码
def post(self, request, *args, **kwargs):
    if 'resign' in request.POST:
      club = Club.objects.get(id=request.POST['club_id'])
      if club.remove_member(request.user, request.user):
        messages.add_message(request, messages.SUCCESS, 
          'Successfully resigned from %s.' % club.club_name)
      else:
        messages.add_message(request, messages.ERROR, 
          'Could not resign from %s.' % club.club_name)
    elif 'disband' in request.POST:
      club = Club.objects.get(id=request.POST['club_id'])
      club._clear_permissions()
      club.delete()
      messages.add_message(request, messages.SUCCESS, 
        'Sucessfully disbanded %s.' % club.club_name)

    clubs = request.user.get_clubs()
    return render(request, self.template_name, {'clubs' : clubs})
项目:club-suite    作者:fsxfreak    | 项目源码 | 文件源码
def post(self, request, club_id, *args, **kwargs):
    club = Club.objects.get(pk=club_id)
    old_club_name = club.club_name
    form = self.form_class(instance=club)

    if 'edit' in request.POST:
      form = self.form_class(request.POST, request.FILES, instance=club)
      if form.is_valid():
        club.update_group_names(old_club_name)
        club = form.save()

        return HttpResponseRedirect(reverse('suite:club_manage'))
      else:
        messages.add_message(request, messages.ERROR, 'Could not make changes to your club.')

    return render(request, self.template_name, { 'form' : form, 'club' : club })
项目:club-suite    作者:fsxfreak    | 项目源码 | 文件源码
def post(self, request, club_id, *args, **kwargs):
    form = self.form_class(request.POST)

    if form.is_valid():
      reason = form.cleaned_data.get('reason')
      club = Club.objects.get(pk=club_id)
      messages.add_message(request, messages.INFO, 'Your request has been sent! It is pending review.')

      if request.user not in club.members.all():
        if JoinRequest.objects.filter(cid=club, uid=request.user).count() <= 0:
          join_request = JoinRequest(cid=club, uid=request.user, reason=reason)
          join_request.save()

      redir = reverse('suite:club_view', args=[club_id])
      return HttpResponseRedirect(redir)

    return render(request, self.template_name, { 'form' : form })
项目:club-suite    作者:fsxfreak    | 项目源码 | 文件源码
def post(self, request, club_id, event_id, *args, **kwargs):
    club = suite.models.Club.objects.get(pk=club_id)
    event = suite.models.Event.objects.get(pk=event_id)
    form = self.form_class(instance=event)

    if 'edit' in request.POST:
      form = self.form_class(request.POST, request.FILES, instance=event)
      if form.is_valid():
        event = form.save()
        #print('valid')

        messages.add_message(request, messages.SUCCESS, 'Successfully edited event.')
        return HttpResponseRedirect(reverse('suite:club_view', 
          kwargs={'club_id': club.id }))
      else:
        messages.add_message(request, messages.ERROR, 'Could not make changes to your event.')

    return render(request, self.template_name, { 'form' : form, 
                                                 'club' : club,
                                                 'event' : event})
项目:club-suite    作者:fsxfreak    | 项目源码 | 文件源码
def post(self, request, club_id, *args, **kwargs):
    club = get_object_or_404(Club, pk=club_id)

    if 'delete' in request.POST:
      user_id = request.POST['delete']
      if not club.remove_member(request.user, User.objects.get(id=user_id)):
          messages.add_message(request, messages.ERROR, 'Cannot delete Yourself!')
    elif 'promote' in request.POST:
      user_id = request.POST['promote']
      act_on_user = User.objects.get(id=user_id)
      if not club.is_officer(act_on_user):
        club.promote_to_officer(request.user, act_on_user)
      elif club.is_officer(act_on_user):
        club.promote_officer_to_owner(request.user, act_on_user)
    elif 'demote' in request.POST:
      user_id = request.POST['demote']
      act_on_user = User.objects.get(id=user_id)
      if club.is_owner(act_on_user):
        if not club.demote_owner_to_officer(request.user, act_on_user):
            messages.add_message(request, messages.ERROR, 'You Cannot Demote Yourself!')
      elif club.is_officer(act_on_user):
        club.demote_from_officer(request.user, act_on_user)

    members = self.get_members(club)
    return render(request, self.template_name, {'club': club, 'members' : members})
项目:club-suite    作者:fsxfreak    | 项目源码 | 文件源码
def post(self, request):

    if 'details' in request.POST:
      form = EditProfileForm(request.POST, instance=request.user)
      if form.is_valid():
        form.save()
      else:
        messages.add_message(request, messages.ERROR, 'Could not edit account details.')

      form2 = PasswordChangeForm(user=request.user)
      args = {'form': form, 'form2': form2 }
      return render(request, 'account.html', args)

    elif 'password' in request.POST:
      form2 = PasswordChangeForm(user=request.user, data=request.POST)
      if form2.is_valid():
        form2.save()
        update_session_auth_hash(request, form2.user)
        messages.add_message(request, messages.SUCCESS, 'Sucessfully changed password.')
      else:
        messages.add_message(request, messages.ERROR, 'Password change unsuccessful.')

      form = EditProfileForm(instance=request.user)
      args = {'form': form, 'form2': form2 }
      return render(request, 'account.html', args)
项目:pureftp    作者:SRELabs    | 项目源码 | 文件源码
def server_add(request):
    """
    ?????
    :param request:
    :return:
    """
    msg = ''
    if request.method == 'POST':
        ftp_name = request.REQUEST.get('ftp_name', '')  # ???ID
        server_id = request.REQUEST.get('server_id', '')  # Redis??
        ftp_port = request.REQUEST.get('ftp_port', '')  # Redis??
        ftp_description = request.REQUEST.get('ftp_description', '')  # redis??
        ovs = OpsFtpServer(request.user)
        res, msg = ovs.server_add(ftp_name, server_id, ftp_port, ftp_description)
        if res:
            messages.add_message(request, messages.SUCCESS, 'FTP??????????????????????')
            return HttpResponseRedirect('/pureftp/s/list/')
    data = Server.objects.all()
    return render_to_response('pureftp/s_add.html',
                              {'data': data, 'msg': msg}, context_instance=RequestContext(request))
项目:pureftp    作者:SRELabs    | 项目源码 | 文件源码
def server_edit(request):
    msg = ''
    ftp_id = request.REQUEST.get('id', '')
    if request.method == 'POST':
        ftp_name = request.REQUEST.get('ftp_name', '')
        server_id = request.REQUEST.get('server_id', '')
        ftp_port = request.REQUEST.get('ftp_port', '')
        ftp_description = request.REQUEST.get('ftp_description', '')
        ovs = OpsFtpServer(request.user)
        res, msg = ovs.server_edit(ftp_id, ftp_name, server_id, ftp_port, ftp_description)
        if res:
            messages.add_message(request, messages.SUCCESS, 'FTP??????????????????????')
            return HttpResponseRedirect('/pureftp/s/list/')
    if ftp_id:
        data = FtpServer.objects.get(pk=ftp_id)
        server_list = Server.objects.all()
        return render_to_response('pureftp/s_edit.html',
                                  {'msg': msg, 'data': data, 'server_list': server_list},
                                  context_instance=RequestContext(request))
    else:
        messages.add_message(request, messages.ERROR, '???????????????????')
        return HttpResponseRedirect('/pureftp/s/list/')
项目:pureftp    作者:SRELabs    | 项目源码 | 文件源码
def server_del(request):
    """

    :param request:
    :return:
    """
    vpn_id = request.REQUEST.get('id', '')
    if vpn_id:
        ftp_server_info = FtpServer.objects.get(pk=vpn_id)
        account_num = FtpAccount.objects.filter(ftp_server=ftp_server_info).count()
        if account_num < 1:
            msg = 'FTP????????'
            FtpServer.objects.get(pk=vpn_id).delete()
            messages.add_message(request, messages.SUCCESS, msg)
        else:
            msg = '?????FTP????ERROR: ??SERVER?????????????????????????IP?'
            messages.add_message(request, messages.ERROR, msg)
    else:
        msg = 'ID?????????'
        messages.add_message(request, messages.ERROR, msg)
    return HttpResponseRedirect("/pureftp/s/list/")
项目:pureftp    作者:SRELabs    | 项目源码 | 文件源码
def user_edit(request):
    uid = request.REQUEST.get('uid', '')
    if request.method == 'POST':
        ops_server = OpsUser(request.user)
        res, msg = ops_server.user_edit(request.POST)
        # ????
        messages.add_message(request, messages.SUCCESS, msg)
        return HttpResponseRedirect('/system/u/list/')
    else:
        data = User.objects.get(pk=uid)
        # group
        groups = Group.objects.all()
        group = data.groups.all()
        # permission
        permissions = Permission.objects.all()
        permission = data.user_permissions.all()
        return render_to_response('system/edit.html',
                                  {'data': data, 'permission': permission,'permissions': permissions,'groups': groups,
                                   'group': group})
项目:pureftp    作者:SRELabs    | 项目源码 | 文件源码
def group_edit(request):
    if request.method == 'POST':
        # form = GroupEditForm(request.POST)
        # if form.is_valid():
        # cd = form.cleaned_data
        ops_server = OpsGroup(request.user)
        res, msg = ops_server.group_edit(request.POST)
        if res:
            messages.add_message(request, messages.SUCCESS, msg)
        else:
            messages.add_message(request, messages.ERROR, msg)
        return HttpResponseRedirect('/system/g/list/')
    else:
        gid = request.REQUEST.get('gid', '')
        data = Group.objects.get(pk=gid)
        group_perms = data.permissions.all()
        all_perms = Permission.objects.all()
        return render_to_response('system/group_edit.html',
                                  {'data': data, 'group_perms': group_perms,
                                   'all_perms': all_perms})
项目:pureftp    作者:SRELabs    | 项目源码 | 文件源码
def permit_add(request):
    """
    ????
    :param request:
    :return:
    """
    if request.method == 'POST':
        ops_permit = OpsPermit(request.user)
        res, msg = ops_permit.permit_add(request.POST)
        page = int(request.REQUEST.get('page', 1))
        if res:
            messages.add_message(request, messages.SUCCESS, msg)
        else:
            messages.add_message(request, messages.ERROR, msg)
        return HttpResponseRedirect('/system/p/list/?page=' + str(page))
    else:
        content_type_list = ContentType.objects.all()
        return render_to_response('system/permit_add.html', {'content_type_list': content_type_list},
                                  context_instance=RequestContext(request))
项目:CommunityCellularManager    作者:facebookincubator    | 项目源码 | 文件源码
def addcard(request):
    if request.method == 'POST':
        token = request.POST['stripe_token[id]']
        user_profile = UserProfile.objects.get(user=request.user)
        network = user_profile.network
        if network.update_card(token):
            messages.add_message(request, messages.INFO, "addcard_saved",
                    extra_tags="billing_resp_code")
            return redirect("/dashboard/billing")
        else:
            # The card has been declined
            messages.add_message(request, messages.ERROR,
                    "addcard_stripe_declined", extra_tags="billing_resp_code")
            return redirect("/dashboard/billing")
    else:
        return HttpResponseBadRequest()
项目:CommunityCellularManager    作者:facebookincubator    | 项目源码 | 文件源码
def addmoney(request):
    if request.method == 'POST':
        amt = cents2mc(int(float(request.POST['amount']) * 100))
        user_profile = UserProfile.objects.get(user=request.user)
        network = user_profile.network
        try:
            charge = network.authorize_card(amt, "credit", "Add Credit")
            network.add_credit(amt)
            network.capture_charge(charge.id)
            messages.add_message(request, messages.SUCCESS,
                                 "addmoney_stripe_success",
                                 extra_tags="billing_resp_code")
            return redirect("/dashboard/billing")
        except stripe.StripeError:
            logger.error("Failed to add money, stripe.CardError: %s", request)
            messages.add_message(request, messages.WARNING,
                                 "addmoney_stripe_error",
                                 extra_tags="billing_resp_code")
            return redirect("/dashboard/billing")
    else:
        return HttpResponseBadRequest()
项目:simple-django-login-and-register    作者:egorsmkv    | 项目源码 | 文件源码
def form_valid(self, form):
        if settings.ENABLE_USER_ACTIVATION:
            user = form.save(commit=False)
            user.is_active = False
            user.save()

            send_activation_email(self.request, user)

            messages.add_message(self.request, messages.SUCCESS,
                                 _('You are registered. To activate the account, follow the link sent to the mail.'))
        else:
            form.save()

            username = form.cleaned_data.get('username')
            raw_password = form.cleaned_data.get('password1')

            user = authenticate(username=username, password=raw_password)
            login(self.request, user)

            messages.add_message(self.request, messages.SUCCESS, _('You are successfully registered!'))

        return super(SignUpView, self).form_valid(form)
项目:simple-django-login-and-register    作者:egorsmkv    | 项目源码 | 文件源码
def get_redirect_url(self, *args, **kwargs):
        assert 'code' in kwargs

        act = get_object_or_404(Activation, code=kwargs['code'])

        # Activate user's profile
        user = act.user
        user.is_active = True
        user.save()

        # Remove activation record, it is unneeded
        act.delete()

        messages.add_message(self.request, messages.SUCCESS, _('You have successfully activated your account!'))
        login(self.request, user)

        return super(ActivateView, self).get_redirect_url()
项目:simple-django-login-and-register    作者:egorsmkv    | 项目源码 | 文件源码
def form_valid(self, form):
        user = self.request.user

        email = form.cleaned_data.get('email')
        email = email.lower()

        if hasattr(settings, 'EMAIL_ACTIVATION_AFTER_CHANGING') and settings.EMAIL_ACTIVATION_AFTER_CHANGING:
            send_activation_change_email(self.request, user, email)

            messages.add_message(self.request, messages.SUCCESS,
                                 _('To complete the change of mail, click on the link sent to it.'))
        else:
            user.email = email
            user.save()

            messages.add_message(self.request, messages.SUCCESS, _('Email successfully changed.'))

        return super(ChangeEmailView, self).form_valid(form)
项目:Gypsy    作者:benticarlos    | 项目源码 | 文件源码
def message_user(self, request, message, level=messages.INFO, extra_tags='',
                     fail_silently=False):
        """
        Send a message to the user. The default implementation
        posts a message using the django.contrib.messages backend.

        Exposes almost the same API as messages.add_message(), but accepts the
        positional arguments in a different order to maintain backwards
        compatibility. For convenience, it accepts the `level` argument as
        a string rather than the usual level number.
        """
        if not isinstance(level, int):
            # attempt to get the level if passed a string
            try:
                level = getattr(messages.constants, level.upper())
            except AttributeError:
                levels = messages.constants.DEFAULT_TAGS.values()
                levels_repr = ', '.join('`%s`' % l for l in levels)
                raise ValueError(
                    'Bad message level string: `%s`. Possible values are: %s'
                    % (level, levels_repr)
                )

        messages.add_message(request, level, message, extra_tags=extra_tags, fail_silently=fail_silently)
项目:open-notices    作者:memespring    | 项目源码 | 文件源码
def form_valid(self, form):
      alert = models.Alert()
      alert.location = form.cleaned_data['location']
      if self.request.user.is_authenticated:

          #save alert
          alert.user = self.request.user
          alert.save()

          #create a success message
          messages.add_message(self.request, messages.SUCCESS, success_message)

          return redirect(reverse('alert-list'))
      else:
        self.request.session['new-alert'] = serialize('geojson', [alert],
          fields=('location',))

        return redirect(reverse('create-alert-user'))
项目:open-notices    作者:memespring    | 项目源码 | 文件源码
def form_valid(self, form):

        #create user
        UserModel = get_user_model()
        user = UserModel(email=form.cleaned_data['email'])
        user.set_password(form.cleaned_data['password'])
        user.save()

        #sign new user in
        login(self.request, user)

        #get the location out of the session
        location = json.loads(self.request.session['new-alert'])

        #save alert
        alert = models.Alert()
        alert.location = json.dumps(location['features'][0]['geometry'])
        alert.user = user
        alert.save()

        #create a success message
        messages.add_message(self.request, messages.SUCCESS, success_message)

        return redirect(reverse('alert-list'))
项目:open-notices    作者:memespring    | 项目源码 | 文件源码
def form_valid(self, form):
        #add the dates to the existing data in the sessions
        notice = form.save(commit=False)
        serializer = NoticeSerializer(notice)
        session_data = self.request.session['new-notice']
        session_data['starts_at'] = serializer.data['starts_at']
        session_data['ends_at'] = serializer.data['ends_at']
        session_data['timezone'] = serializer.data['timezone']

        #save
        serializer = NoticeSerializer(data=session_data)
        if serializer.is_valid():
            notice = serializer.save(user=self.request.user)
            messages.add_message(self.request, messages.SUCCESS, 'Your notice has been posted')
            return redirect(notice)
        else:
            messages.add_message(self.request, messages.ERROR, 'Sorry, something went wrong')
项目:DjangoBlog    作者:0daybug    | 项目源码 | 文件源码
def message_user(self, request, message, level=messages.INFO, extra_tags='',
                     fail_silently=False):
        """
        Send a message to the user. The default implementation
        posts a message using the django.contrib.messages backend.

        Exposes almost the same API as messages.add_message(), but accepts the
        positional arguments in a different order to maintain backwards
        compatibility. For convenience, it accepts the `level` argument as
        a string rather than the usual level number.
        """

        if not isinstance(level, int):
            # attempt to get the level if passed a string
            try:
                level = getattr(messages.constants, level.upper())
            except AttributeError:
                levels = messages.constants.DEFAULT_TAGS.values()
                levels_repr = ', '.join('`%s`' % l for l in levels)
                raise ValueError('Bad message level string: `%s`. '
                        'Possible values are: %s' % (level, levels_repr))

        messages.add_message(request, level, message, extra_tags=extra_tags,
                fail_silently=fail_silently)
项目:vishleva.com    作者:webmalc    | 项目源码 | 文件源码
def export(self, request, queryset):
        """
        Download selected photos as ZIP
        """
        zip_subdir = 'photos'
        zip_filename = '{}.zip'.format(zip_subdir)
        zip_file = os.path.join(settings.MEDIA_ROOT, PHOTOLOGUE_DIR,
                                zip_filename)
        try:
            os.remove(zip_file)
        except OSError:
            pass

        with zipfile.ZipFile(zip_file, "a") as zf:
            for photo in queryset.all():
                path = photo.image.path
                if os.path.isfile(path):
                    fdir, fname = os.path.split(path)
                    zip_path = os.path.join(zip_subdir, fname)
                    zf.write(path, zip_path)

        link = 'Photos download link: <a href="{0}?v={1}">{0}</a>'.format(
            urllib.parse.urljoin(settings.MEDIA_URL,
                                 PHOTOLOGUE_DIR + '/' + zip_filename), time())
        messages.add_message(request, messages.INFO, mark_safe(link))
项目:django_ecommerce    作者:rick-ey    | 项目源码 | 文件源码
def contact(request):
    if request.method == 'POST':
        form = ContactView(request.POST)
        if form.is_valid():
            our_form = form.save(commit=False)
            our_form.save()
            messages.add_message(
                request, messages.INFO,
                'Your message has been sent. Thank you.'
            )
            return HttpResponseRedirect('/')
    else:
        form = ContactView()
    t = loader.get_template('contact/contact.html')
    c = RequestContext(request, {'form': form, })
    return HttpResponse(t.render(c))
项目:fieldsight-kobocat    作者:awemulya    | 项目源码 | 文件源码
def stage_add_form(request, pk=None):
    stage = get_object_or_404(
        Stage, pk=pk)
    if stage.stage.site:
        instance = FieldSightXF(site=stage.stage.site, is_staged=True, is_scheduled=False, stage=stage)
        if request.method == 'POST':
            form = AssignFormToStageForm(request.POST, instance=instance)
            if form.is_valid():
                form.save()
                messages.add_message(request, messages.INFO, 'Form Assigned Successfully.')
                return HttpResponseRedirect(reverse("forms:stages-detail", kwargs={'pk': stage.stage.id}))
        else:
            form = AssignFormToStageForm(instance=instance)
        return render(request, "fsforms/stage_add_form.html", {'form': form, 'obj': stage})
    else:
        if request.method == 'POST':
            form = AssignFormToStageForm(request.POST)
            if form.is_valid():
                form.save()
                messages.add_message(request, messages.INFO, 'Form Assigned Successfully.')
                return HttpResponseRedirect(reverse("forms:stages-detail", kwargs={'pk': stage.stage.id}))
        else:
            form = AssignFormToStageForm()
        return render(request, "fsforms/stage_add_form.html", {'form': form, 'obj': stage})
项目:fieldsight-kobocat    作者:awemulya    | 项目源码 | 文件源码
def add_proj_manager(request, pk):
    obj = get_object_or_404(
        Project, pk=pk)
    group = Group.objects.get(name__exact="Project Manager")
    role_obj = UserRole(project=obj, group=group)
    scenario = 'Assign'
    if request.method == 'POST':
        form = SetProjectManagerForm(data=request.POST, instance=role_obj, request=request)
        if form.is_valid():
            role_obj = form.save(commit=False)
            user_id = request.POST.get('user')
            role_obj.user_id = int(user_id)
            role_obj.save()
        messages.add_message(request, messages.INFO, 'Project Manager Added')
        return HttpResponseRedirect(reverse("fieldsight:project-dashboard", kwargs={'pk': obj.pk}))
    else:
        form = SetProjectManagerForm(instance=role_obj, request=request)
    return render(request, "fieldsight/add_project_manager.html", {'obj':obj,'form':form, 'scenario':scenario})
项目:fieldsight-kobocat    作者:awemulya    | 项目源码 | 文件源码
def add_supervisor(request, pk):
    obj = get_object_or_404(
        Site, pk=int(pk))
    group = Group.objects.get(name__exact="Site Supervisor")
    role_obj = UserRole(site=obj, group=group)
    if request.method == 'POST':
        form = SetSupervisorForm(data=request.POST, instance=role_obj, request=request)
        if form.is_valid():
            role_obj = form.save(commit=False)
            user_id = request.POST.get('user')
            role_obj.user_id = int(user_id)
            role_obj.save()
        messages.add_message(request, messages.INFO, 'Site Supervisor Added')
        return HttpResponseRedirect(reverse("fieldsight:site-dashboard", kwargs={'pk': obj.pk}))
    else:
        form = SetSupervisorForm(instance=role_obj, request=request)
    return render(request, "fieldsight/add_supervisor.html", {'obj':obj,'form':form})
项目:fieldsight-kobocat    作者:awemulya    | 项目源码 | 文件源码
def add_central_engineer(request, pk):
    obj = get_object_or_404(
        Project, pk=pk)
    group = Group.objects.get(name__exact="Reivewer")
    role_obj = UserRole(project=obj, group=group)
    scenario = 'Assign'
    if request.method == 'POST':
        form = SetProjectRoleForm(data=request.POST, instance=role_obj, request=request)
        if form.is_valid():
            role_obj = form.save(commit=False)
            user_id = request.POST.get('user')
            role_obj.user_id = int(user_id)
            role_obj.save()
        messages.add_message(request, messages.INFO, 'Reviewer Added')
        return HttpResponseRedirect(reverse("fieldsight:project-dashboard", kwargs={'pk': obj.pk}))
    else:
        form = SetProjectRoleForm(instance=role_obj, request=request,)
    return render(request, "fieldsight/add_central_engineer.html", {'obj':obj,'form':form, 'scenario':scenario})
项目:fieldsight-kobocat    作者:awemulya    | 项目源码 | 文件源码
def add_project_role(request, pk):
    obj = get_object_or_404(
        Project, pk=pk)
    role_obj = UserRole(project=obj)
    scenario = 'Assign People'
    form = SetProjectRoleForm(instance=role_obj, request=request)
    if request.method == 'POST':
        form = SetProjectRoleForm(data=request.POST, instance=role_obj, request=request)
        if form.is_valid():
            role_obj = form.save(commit=False)
            user_id = request.POST.get('user')
            role_obj.user_id = int(user_id)
            role_obj.save()
            messages.add_message(request, messages.INFO, '{} Added'.format(role_obj.group.name))
            return HttpResponseRedirect(reverse("fieldsight:project-dashboard", kwargs={'pk': obj.pk}))
    existing_staffs = obj.get_staffs
    return render(request, "fieldsight/add_central_engineer.html", {'obj':obj,'form':form, 'scenario':scenario,
                                                                    "existing_staffs":existing_staffs})
项目:wanblog    作者:wanzifa    | 项目源码 | 文件源码
def message_user(self, request, message, level=messages.INFO, extra_tags='',
                     fail_silently=False):
        """
        Send a message to the user. The default implementation
        posts a message using the django.contrib.messages backend.

        Exposes almost the same API as messages.add_message(), but accepts the
        positional arguments in a different order to maintain backwards
        compatibility. For convenience, it accepts the `level` argument as
        a string rather than the usual level number.
        """

        if not isinstance(level, int):
            # attempt to get the level if passed a string
            try:
                level = getattr(messages.constants, level.upper())
            except AttributeError:
                levels = messages.constants.DEFAULT_TAGS.values()
                levels_repr = ', '.join('`%s`' % l for l in levels)
                raise ValueError('Bad message level string: `%s`. '
                        'Possible values are: %s' % (level, levels_repr))

        messages.add_message(request, level, message, extra_tags=extra_tags,
                fail_silently=fail_silently)
项目:tabmaster    作者:NicolasMinghetti    | 项目源码 | 文件源码
def message_user(self, request, message, level=messages.INFO, extra_tags='',
                     fail_silently=False):
        """
        Send a message to the user. The default implementation
        posts a message using the django.contrib.messages backend.

        Exposes almost the same API as messages.add_message(), but accepts the
        positional arguments in a different order to maintain backwards
        compatibility. For convenience, it accepts the `level` argument as
        a string rather than the usual level number.
        """

        if not isinstance(level, int):
            # attempt to get the level if passed a string
            try:
                level = getattr(messages.constants, level.upper())
            except AttributeError:
                levels = messages.constants.DEFAULT_TAGS.values()
                levels_repr = ', '.join('`%s`' % l for l in levels)
                raise ValueError('Bad message level string: `%s`. '
                        'Possible values are: %s' % (level, levels_repr))

        messages.add_message(request, level, message, extra_tags=extra_tags,
                fail_silently=fail_silently)