Python django.contrib.messages 模块,SUCCESS 实例源码

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

项目: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
项目: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"))
项目:endorsementdb.com    作者:endorsementdb    | 项目源码 | 文件源码
def change_event(modeladmin, request, queryset):
    event_pk = request.POST['event']
    try:
        event = Event.objects.get(pk=event_pk)
    except Event.DoesNotExist:
        modeladmin.message_user(
            request,
            "Could not find event with pk {event_pk}".format(
                event_pk=event_pk
            ),
            messages.ERROR,
        )
        return

    queryset.update(event=event)

    modeladmin.message_user(
        request,
        "Added event {event} for {n} quotes".format(
            event=event.name,
            n=queryset.count(),
        ),
        messages.SUCCESS,
    )
项目: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')
项目: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}))
项目: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):

    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 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 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()
项目:tumanov_castleoaks    作者:Roamdev    | 项目源码 | 文件源码
def get(self, request, *args, **kwargs):
        code = request.GET.get('code', '')
        if not code:
            raise Http404

        config = SocialConfig.get_solo()
        redirect_uri = self.request.build_absolute_uri(resolve_url('admin_social_networks:instagram_token'))
        response = requests.post(
            'https://api.instagram.com/oauth/access_token',
            data={
                'grant_type': 'authorization_code',
                'client_id': config.instagram_client_id,
                'client_secret': config.instagram_client_secret,
                'redirect_uri': redirect_uri,
                'code': code,
            }
        )

        answer = response.json()
        if answer and 'access_token' in answer:
            SocialConfig.objects.update(instagram_access_token=answer['access_token'])
            add_message(request, SUCCESS, _('Instagram access_token updated successfully!'))
            return redirect('admin:social_networks_socialconfig_change')
        else:
            return HttpResponse(response.text)
项目:tumanov_castleoaks    作者:Roamdev    | 项目源码 | 文件源码
def get(self, request, *args, **kwargs):
        code = request.GET.get('code', '')
        if not code:
            raise Http404

        config = SocialConfig.get_solo()
        redirect_uri = self.request.build_absolute_uri(resolve_url('admin_social_networks:linkedin_token'))
        response = requests.post(
            'https://www.linkedin.com/oauth/v2/accessToken',
            data={
                'grant_type': 'authorization_code',
                'client_id': config.linkedin_client_id,
                'client_secret': config.linkedin_client_secret,
                'redirect_uri': redirect_uri,
                'code': code,
            }
        )

        answer = response.json()
        if answer and 'access_token' in answer:
            SocialConfig.objects.update(linkedin_access_token=answer['access_token'])
            add_message(request, SUCCESS, _('LinkedIn access_token updated successfully!'))
            return redirect('admin:social_networks_socialconfig_change')
        else:
            return HttpResponse(response.text)
项目: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)
项目: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')
项目:rudi    作者:lexxodus    | 项目源码 | 文件源码
def custom_mail_confirm(self, request):
        if request.method == "POST":
            form_id = request.session["mailform_id"]
            advisor = request.session["mailform_advisor_" + form_id]
            email_addresses = request.session[
                "mailform_addresses_" + form_id]
            body = request.session["mailform_body_" + form_id]
            subject = request.session["mailform_subject_" + form_id]
            sent_amount = mails.send_custom(
                advisor, email_addresses, subject, body)
            messages.add_message(
                request,
                messages.SUCCESS,
                "%s mails were sent successfully" % sent_amount)
            referer = request.session["mailform_referer_" + form_id]
            return HttpResponseRedirect(referer)
        else:
            return HttpResponseRedirect(reverse('admin:index'))
项目:passport    作者:SRELabs    | 项目源码 | 文件源码
def app_add(request):
    if request.method == 'POST':
        form = AppAddForm(request.POST)
        if form.is_valid():
            if not App.objects.filter(app_domain=form.cleaned_data['app_name']):
                f = form.save(commit=False)
                f.app_key = random_str()
                f.save()
                messages.add_message(request, messages.SUCCESS, '??????')
                return HttpResponseRedirect(reverse('app:app_list'))
            messages.add_message(request, messages.ERROR, '???????????????')
        messages.add_message(request, messages.ERROR, 'ERROR: ' + re.compile(r'<[^>]+>', re.S).sub('', str(form.errors)))
        return HttpResponseRedirect(reverse('app:app_add'))
    else:
        data = Policy.objects.all()
        return render_to_response('app/list.html', {'data': data}, context_instance=RequestContext(request))
项目:passport    作者:SRELabs    | 项目源码 | 文件源码
def user_otp(request, uid):
    msg = 'OTP?????'
    try:
        data = User.objects.get(pk=uid)
        profile = UserProfile.objects.get(user=data)
        profile.otp = pyotp.random_base32()
        profile.save()
        messages.add_message(request, messages.SUCCESS, msg)
        return HttpResponseRedirect(reverse('system:system_user_list'))
    except User.DoesNotExist:
        msg = '??????'
    except UserProfile.DoesNotExist:
        msg = '???????!'
        UserProfile(user=data, otp=pyotp.random_base32(), avatar='').save()
    except Exception, e:
        msg = '????: ' + e.message
    messages.add_message(request, messages.ERROR, msg)
    return HttpResponseRedirect(reverse('system:system_user_list'))
项目:passport    作者:SRELabs    | 项目源码 | 文件源码
def group_add(request):
    if request.method == 'POST':
        name = request.POST.get('name')
        permission = request.POST.getlist('permission')
        try:
            Group.objects.get(name=name)
            res, msg = False, 'GroupIsExists!'
        except Group.DoesNotExist:
            g = Group(name=name)
            g.permissions = permission
            g.save()
            # for p in permission:
            #     g.permissions.add(p)
            res, msg = True, 'Create Success!'
        if res:
            messages.add_message(request, messages.SUCCESS, msg)
        else:
            messages.add_message(request, messages.ERROR, msg)

        return HttpResponseRedirect(reverse('system:system_group_list'))
    else:
        data = Permission.objects.all()
        return render_to_response('system/group_create.html',
                                  {'data': data}, context_instance=RequestContext(request))
项目:passport    作者:SRELabs    | 项目源码 | 文件源码
def group_edit(request, gid):
    if request.method == 'POST':
        gid = request.POST.get('gid')
        name = request.POST.get('name')
        permission = request.POST.getlist('permission')
        try:
            g = Group.objects.get(pk=gid)
            g.name = name
            g.permissions = permission
            g.save()
            res, msg = True, 'role?edit success?'
        except User.DoesNotExist:
            res, msg = False, 'role?not exists?'
        if res:
            messages.add_message(request, messages.SUCCESS, msg)
        else:
            messages.add_message(request, messages.ERROR, msg)
        return HttpResponseRedirect(reverse('system:system_group_list'))
    else:
        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}, context_instance=RequestContext(request))
项目:passport    作者:SRELabs    | 项目源码 | 文件源码
def permit_add(request):
    """
    ????
    :param request:
    :return:
    """
    if request.method == 'POST':
        p = Permission()
        p.name = request.POST['name']
        p.codename = request.POST['codename']
        p.content_type_id = request.POST['content_type_id']
        p.save()
        res, msg = True, '???????name: ' + request.POST['name'] + ' ,codename' + request.POST['codename']

        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(reverse('system:system_permit_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))
项目:passport    作者:SRELabs    | 项目源码 | 文件源码
def permit_edit(request, pid):
    if request.method == 'POST':
        pid = request.POST.get('id')
        name = request.POST.get('name')
        try:
            g = Permission.objects.get(pk=pid)
            g.name = name
            g.save()
            res, msg = True, 'Success!'
        except Permission.DoesNotExist:
            res, msg = False, 'PermissionNotExists!'
        if res:
            messages.add_message(request, messages.SUCCESS, msg)
        else:
            messages.add_message(request, messages.ERROR, msg)
        return HttpResponseRedirect(reverse('system:system_permit_list'))
    else:
        data = Permission.objects.get(pk=pid)
        content_type_list = ContentType.objects.all()
        return render_to_response('system/permit_edit.html', {'data': data, 'content_type_list': content_type_list},
                                  context_instance=RequestContext(request))
项目:passport    作者:SRELabs    | 项目源码 | 文件源码
def permit_delete(request, pid):
    """
    ????
    :param pid:
    :param request:
    :return:
    """
    page = int(request.REQUEST.get('page', 1))
    try:
        Permission.objects.get(pk=pid).delete()
        msg = '???????codename?' + p.codename + ', name:' + str(p.name)
        messages.add_message(request, messages.SUCCESS, msg)
    except Permission.DoesNotExist:
        msg = 'PermissionNotExists'
        messages.add_message(request, messages.ERROR, msg)
    return HttpResponseRedirect(reverse('system:system_permit_list') + '?page=' + str(page))
项目:passport    作者:SRELabs    | 项目源码 | 文件源码
def user_add(request):
    form = UsersAddForm(request.POST)
    message_error = True
    msg = '??????'
    if form.is_valid():
        if not Users.objects.filter(users_name=form.cleaned_data['users_name']):
            m2 = hashlib.md5()
            m2.update(form.cleaned_data['users_password'])
            f = form.save(commit=False)
            f.users_password = m2.hexdigest()
            f.users_create_time = datetime.now()
            f.users_otp = pyotp.random_base32()
            f.save()
            msg = '????'
            message_error = False
    else:
        msg = 'ERROR: ' + re.compile(r'<[^>]+>', re.S).sub('', str(form.errors))
    if message_error:
        messages.add_message(request, messages.ERROR, msg)
        return HttpResponseRedirect(reverse('users:user_add'))
    else:
        messages.add_message(request, messages.SUCCESS, msg)
    return HttpResponseRedirect(reverse('users:user_list'))
项目:passport    作者:SRELabs    | 项目源码 | 文件源码
def user_active(request, users_name):
    if users_name:
        try:
            users = Users.objects.get(users_name=users_name)
            if users.users_active == 1:
                users.users_active = 0
                msg = '???????'
            else:
                users.users_active = 1
                msg = '???????'
            users.save()
            messages.add_message(request, messages.SUCCESS, msg)
        except Users.DoesNotExist:
            msg = '??????'
            messages.add_message(request, messages.SUCCESS, msg)
    return HttpResponseRedirect(reverse('users:user_list'))
项目:passport    作者:SRELabs    | 项目源码 | 文件源码
def policy_rule_add(request, rule_policy):
    if request.method == 'POST':
        form = PolicyRuleAddForm(request.POST)
        if form.is_valid():
            if not PolicyRule.objects.filter(rule_policy=rule_policy).filter(
                    rule_value=form.cleaned_data['rule_value']):
                f = form.save(commit=False)
                f.save()
                messages.add_message(request, messages.SUCCESS, '??????')
                return HttpResponseRedirect(reverse('policy:policy_rule_list', args=[rule_policy]))
            messages.add_message(request, messages.ERROR, '???????????????')
        messages.add_message(request, messages.ERROR,
                             'ERROR: ' + re.compile(r'<[^>]+>', re.S).sub('', str(form.errors)))
        return HttpResponseRedirect(reverse('policy:policy_rule_list', args=[rule_policy]))
    else:
        return render_to_response('policy/rule/list.html', {'rule_policy': rule_policy},
                                  context_instance=RequestContext(request))
项目:django-twilio-tfa    作者:rtindru    | 项目源码 | 文件源码
def post(self, *args, **kwargs):
        self.object = confirmation = self.get_object()
        confirmation.confirm(self.request)
        get_adapter(self.request).add_message(
            self.request,
            messages.SUCCESS,
            'account/messages/email_confirmed.txt',
            {'email': confirmation.email_address.email})
        if app_settings.LOGIN_ON_EMAIL_CONFIRMATION:
            resp = self.login_on_confirm(confirmation)
            if resp is not None:
                return resp
        # Don't -- allauth doesn't touch is_active so that sys admin can
        # use it to block users et al
        #
        # 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)
        return redirect(redirect_url)
项目:hydra    作者:Our-Revolution    | 项目源码 | 文件源码
def form_valid(self, form):      
        try:
            self.object = form.save()
            messages.add_message(self.request, messages.SUCCESS, "Your event has been created.")
            return super(ModelFormMixin, self).form_valid(form)

        except BaseException, e:
            if hasattr(e, '__iter__'):
                for exc in e:
                    messages.add_message(self.request, messages.ERROR, "Error creating your event -- %s" % exc[1][0])
                    if hasattr(form, exc[0]):
                        form.add_error(exc[0], exc[1][0])
            elif isinstance(e, UnicodeError):
                field =  e[1][e[1][0:e[3]].rfind('&')+1:e[1][0:e[3]].rfind('=')]
                messages.add_message(self.request, messages.ERROR, "Error creating your event -- You had some special characters in your %s field, please remove those and try again." % field)
                if field in form.fields:
                    form.add_error(field, "Please remove special characters and try again.")
            return super(EventCreate, self).form_invalid(form)
项目:hydra    作者:Our-Revolution    | 项目源码 | 文件源码
def form_valid(self, form):
        try:
            self.object = form.save()
            messages.add_message(self.request, messages.SUCCESS, "Your event has been updated.")
            return super(ModelFormMixin, self).form_valid(form)

        except BaseException, e:
            if hasattr(e, '__iter__'):
                for exc in e:
                    messages.add_message(self.request, messages.ERROR, "Error creating your event -- %s" % exc[1][0])
                    if hasattr(form, exc[0]):
                        form.add_error(exc[0], exc[1][0])
            elif isinstance(e, UnicodeError):
                field =  e[1][e[1][0:e[3]].rfind('&')+1:e[1][0:e[3]].rfind('=')]
                if field in form.fields:
                    form.add_error(field, "Please remove special characters and try again.")
                messages.add_message(self.request, messages.ERROR, "Error updating your event -- You had some special characters in your %s field, please remove those and try again." % field)
            return super(EventEdit, self).form_invalid(form)
项目:economy-game    作者:Aearsis    | 项目源码 | 文件源码
def token_input(request):
    if request.method == 'POST':
        try:
            f = TokenForm(request.POST)
            if f.is_valid():
                token = Token.get(f.cleaned_data['code'])
                token.use(request.team)
                messages.add_message(request, messages.SUCCESS, "Našel jsi %s!" % token.entity)
                return redirect("token:input")
        except Token.DoesNotExist:
            messages.add_message(request, messages.INFO, "Takový líste?ek neexistuje!")
        except (InvalidTransaction, TokenUnusableException) as e:
            messages.add_message(request, messages.WARNING, "%s" % e)
    else:
        f = TokenForm()

    return render(request, "tokens/input.html", {'form': f})
项目:economy-game    作者:Aearsis    | 项目源码 | 文件源码
def create_auction(request):
    AIFormSet = inlineformset_factory(Auction, AuctionedItem, form=AuctionedItemForm, can_delete=False, extra=1)
    if request.method == "POST":
        form = CreateAuctionForm(request.POST)
        formset = AIFormSet(request.POST)
        if form.is_valid() and formset.is_valid():
            try:
                data = form.cleaned_data
                data['auctioneditems'] = formset.cleaned_data
                auction = WhiteAuction.create(request.team, data)
                messages.add_message(request, messages.SUCCESS, "Aukce byla vytvo?ena.")
                Status.add("Tým %s práv? vystavil aukci!" % request.team.name, Status.SUCCESS)
                return redirect(reverse("detail", args=(auction.id,)))
            except InvalidTransaction as e:
                form.add_error(None, str(e))
    else:
        form = CreateAuctionForm()
        formset = AIFormSet()

    return render(request, "auctions/create_auction.html", {
        'form': form,
        'items': formset,
        'empty_item': formset.empty_form,
        'balance': request.team.balance_set.all(),
    })
项目:harnas    作者:harnasproject    | 项目源码 | 文件源码
def new(request, contest_id):
    if not request.user.has_perm('manage_contest',
                                 Contest.objects.get(pk=contest_id)):
        raise PermissionDenied
    else:
        form = NewsForm(request.POST)
        if form.is_valid():
            contest = Contest.objects.get(pk=contest_id)
            contest.news_set.create(
                title=form.data['title'],
                description=form.data['description'],
                contest=contest,
                author=request.user)
            messages.add_message(request,
                                 messages.SUCCESS,
                                 "New news has been created.")
        return HttpResponseRedirect(
            reverse('contest_details',
                    args=[contest_id]) + '?current_tab=news')
项目:harnas    作者:harnasproject    | 项目源码 | 文件源码
def delete(request, contest_id, news_id):
    if not request.user.has_perm('manage_contest',
                                 Contest.objects.get(pk=contest_id)):
        raise PermissionDenied
    else:
        try:
            news = News.objects.get(pk=news_id)
            news.delete()
            messages.add_message(request,
                                 messages.SUCCESS,
                                 "News deleted successfully.")
        except ObjectDoesNotExist:
            raise PermissionDenied
        return HttpResponseRedirect(
            reverse('contest_details',
                    args=[contest_id]) + '?current_tab=news')
项目:harnas    作者:harnasproject    | 项目源码 | 文件源码
def handle_testcase_form(request, task, testcase):
    form = TestCaseForm(request.POST, request.FILES, instance=testcase)
    if form.is_valid():
        testcase = form.save(commit=False)
        testcase.task = task
        testcase.run_order_id = TestCase.objects.filter(
                                    task_id__exact=task.pk).count()
        handle_testcase_files(testcase,
                              request.FILES['in_file'],
                              request.FILES['out_file'])
        testcase.save()
        messages.add_message(
            request,
            messages.SUCCESS,
            'Testcase %s saved successfully.' % testcase)
    return HttpResponseRedirect(reverse('task_details', args=[task.pk]) +
                                '?current_tab=test_cases')
项目:harnas    作者:harnasproject    | 项目源码 | 文件源码
def delete(request, contest_id, group_id):
    if not request.user.has_perm('manage_contest',
                                 Contest.objects.get(pk=contest_id)):
        raise PermissionDenied
        return HttpResponseRedirect(reverse('contest_details',
                                            args=[contest_id]))
    else:
        try:
            Group.objects.get(pk=group_id).delete()
            messages.add_message(request,
                                 messages.SUCCESS,
                                 "Group has been successfully deleted.")
        except ObjectDoesNotExist:
            messages.add_message(request,
                                 messages.ERROR,
                                 "Group does not exists.")
        return HttpResponseRedirect(reverse('contest_details',
                                            args=[contest_id]))
项目:harnas    作者:harnasproject    | 项目源码 | 文件源码
def fetch_task(request, contest_id):
    contest = Contest.objects.get(pk=contest_id)
    if not request.user.has_perm('manage_contest', contest):
        raise PermissionDenied
    elif request.method == 'POST':
        form = TaskFetchForm(request.POST)
        if form.is_valid():
            fetched_task = copy_task(form)
            fetched_task.contest = contest
            if save_task(fetched_task):
                messages.add_message(
                    request,
                    messages.SUCCESS,
                    'New task has been added to contest %s.' % contest.name)
                add_task_to_groups(contest, fetched_task)
            else:
                messages.add_message(
                    request,
                    messages.ERROR,
                    'Unable to fetch task %s. Please report this accident'
                    ' to administrator.' % fetched_task)

    return HttpResponseRedirect(
        reverse('contest_details', args=[contest_id]) + '?current_tab=tasks')
项目:django-cms-articles    作者:misli    | 项目源码 | 文件源码
def create_users(self, request, queryset):
        for author in queryset.all():
            if author.user:
                continue
            try:
                author.user = User.objects.create(
                    username=author.login,
                    email=author.email,
                    first_name=author.first_name or '',
                    last_name=author.last_name or '',
                )
                author.save()
            except Exception as e:
                self.message_user(request, _('Failed to create user {}: {}').format(author.login, e), messages.ERROR)
            else:
                self.message_user(request, _('Successfully created user {}').format(author.login), messages.SUCCESS)
项目:django-cms-articles    作者:misli    | 项目源码 | 文件源码
def find_users(self, request, queryset):
        for author in queryset.all():
            if author.user:
                continue

            try:
                author.user = User.objects.get(username=author.login)
            except User.DoesNotExist:
                pass

            if not author.user:
                author.user = User.objects.filter(email=author.email).first()

            if not author.user:
                author.user = User.objects.filter(first_name=author.first_name, last_name=author.last_name).first()

            if author.user:
                author.save()
                self.message_user(
                    request,
                    _('Successfully found user {} for author').format(author.user, author),
                    messages.SUCCESS)
            else:
                self.message_user(request, _('Failed to find user for author {}').format(author), messages.ERROR)
项目:website    作者:hackerspace-ntnu    | 项目源码 | 文件源码
def post(self, request, item_id=0):
        form = LoanForm(data=request.POST)
        if form.is_valid():
            loan_items = form.cleaned_data['items']
            del form.cleaned_data['items']

            loan = Loan.objects.create(**form.cleaned_data)
            loan.loanitem_set.add(*loan_items)
            loan.lender = request.user
            loan.loan_date = timezone.now()
            loan.save()

            messages.add_message(request, messages.SUCCESS, 'Lånet ble registrert')
            return HttpResponseRedirect(reverse('inventory:index'))

        self.context['form'] = form
        return HttpResponse(render(request, 'inventory/register_loan.html', self.context))
项目:dnomovie    作者:pureYun    | 项目源码 | 文件源码
def settings(request):
    user = request.user
    if request.method =='POST':
        form = ProfileForm(request.POST)
        if form.is_valid():
            webuser = Webuser.objects.get(user=user)
            webuser.job_title=form.cleaned_data.get('job_title')
            webuser.location=form.cleaned_data.get('location')
            webuser.url = form.cleaned_data.get('url')
            webuser.likestyle=form.cleaned_data.get('likestyle')
            webuser.sex=form.cleaned_data.get('sex')
            webuser.save()
            messages.add_message(request,messages.SUCCESS,u'??????????.')
    else:
        form = ProfileForm(instance=user,initial={
            'job_title':user.webuser.job_title,
            'url':user.webuser.url,
            'location':user.webuser.location,
            'sex':user.webuser.sex,
            'likestyle':user.webuser.likestyle
        })
    return render(request,'webuser/person_home_page_info.html',{'form':form})
项目:dnomovie    作者:pureYun    | 项目源码 | 文件源码
def addmovie(request):
    if request.method=='POST':
        form = MovieInfoForm(request.POST,request.FILES)
        if not form.is_valid():
            return render(request,'webuser/addmovie.html',{'form':form})
        else:
            moviename = form.cleaned_data.get('moviename')
            movieaddress = form.cleaned_data.get('movieaddress')
            downloadlink = form.cleaned_data.get('downloadlink')
            style = form.cleaned_data.get('style')
            language = form.cleaned_data.get('language')
            image = request.FILES['image']
            movie = Movie(moviename=moviename,movieaddress=movieaddress,downloadlink=downloadlink,
                          style=style,language=language,image=image,original=str(user.webuser.id))
            movie.save()
            messages.add_message(request,messages.SUCCESS,u'??????.')
    else:
        form = MovieInfoForm();
    return render(request,'webuser/addmovie.html',{'form':form})