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

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

项目:pyconjp-website    作者:pyconjp    | 项目源码 | 文件源码
def speaker_create_token(request, token):
    speaker = get_object_or_404(Speaker, invite_token=token)
    request.session["pending-token"] = token
    if request.user.is_authenticated():
        # check for speaker profile
        try:
            existing_speaker = request.user.speaker_profile
        except ObjectDoesNotExist:
            pass
        else:
            del request.session["pending-token"]
            additional_speakers = ProposalBase.additional_speakers.through
            additional_speakers._default_manager.filter(
                speaker=speaker
            ).update(
                speaker=existing_speaker
            )
            messages.info(request, "You have been associated with all pending "
                "talk proposals")
            return redirect("dashboard")
    else:
        if not request.user.is_authenticated():
            return redirect("account_login")
    return redirect("speaker_create")
项目:django_velespi    作者:aysedilekk    | 项目源码 | 文件源码
def register(request):
    form = RegistrationForm()

    if request.method == 'POST':
        form = RegistrationForm(request.POST)

        if form.is_valid():
            form.save()

            messages.info(
                request,
                'Kayit basarili. Simdi login olabilirsiniz.'
            )

            return redirect('login')

    return render(request, 'register.html', {
        'form': form,
    })
项目:django_velespi    作者:aysedilekk    | 项目源码 | 文件源码
def login(request):
    form = LoginForm()

    if request.method == 'POST':
        form = LoginForm(request.POST)

        if form.is_valid():
            auth_login(request, form.user)
            messages.info(
                request,
                'Giris yaptiniz.'
            )

            if request.GET.get('next'):
                return redirect(request.GET['next'])

    return render(request, 'login.html', {
        'form': form
    })
项目:django_velespi    作者:aysedilekk    | 项目源码 | 文件源码
def new_place(request):
    form = PlaceCreationForm()

    if request.method == "POST":
        form = PlaceCreationForm(request.POST)
        if form.is_valid():
            form.instance.user = request.user
            form.save()
            messages.info(
                request,
                'Tebrikler. Yer bildiriminiz ba?ar?yla al?nd?. '
                'Editör onay?ndan geçtikten sonra yay?nlanacakt?r.'
            )
            return redirect('/')

    return render(
        request,
        'new_place.html',
        {
            'form': form,
        }
    )
项目:CoBL-public    作者:lingdb    | 项目源码 | 文件源码
def get_canonical_language_list(language_list=None, request=None):
    """Returns a LanguageList object"""
    try:
        if language_list is None:
            language_list = LanguageList.objects.get(name=LanguageList.DEFAULT)
        elif language_list.isdigit():
            language_list = LanguageList.objects.get(id=language_list)
        else:
            language_list = LanguageList.objects.get(name=language_list)
    except LanguageList.DoesNotExist:
        if request:
            messages.info(
                request,
                "There is no language list matching"
                " '%s' in the database" % language_list)
        raise Http404
    return language_list
项目:CoBL-public    作者:lingdb    | 项目源码 | 文件源码
def get_canonical_meaning_list(meaning_list=None, request=None):
    """Returns a MeaningList object"""
    try:
        if meaning_list is None:
            meaning_list = MeaningList.objects.get(name=MeaningList.DEFAULT)
        elif meaning_list.isdigit():
            meaning_list = MeaningList.objects.get(id=meaning_list)
        else:
            meaning_list = MeaningList.objects.get(name=meaning_list)
    except MeaningList.DoesNotExist:
        if request:
            messages.info(
                request,
                "There is no meaning list matching"
                " '%s' in the database" % meaning_list)
        raise Http404
    return meaning_list
项目:CoBL-public    作者:lingdb    | 项目源码 | 文件源码
def handle(self, request):
        language = Language.objects.get(ascii_name=self.data['language'])
        meanings = Meaning.objects.exclude(
            id__in=set(Lexeme.objects.filter(
                language=language).values_list(
                    'meaning_id', flat=True))).all()
        if meanings:
            with transaction.atomic():
                for m in meanings:
                    Lexeme.objects.create(language=language, meaning=m)
            messages.info(
                request,
                "Added lexemes for meanings: " +
                ", ".join([m.gloss for m in meanings]))
        else:
            messages.info(
                request,
                'There is at least one lexeme '
                'for every meaning in the database.')
项目:SpongeAuth    作者:lukegb    | 项目源码 | 文件源码
def remove(request, device_id):
    device_qs = (
        twofa.models.Device.objects
        .active_for_user(request.user).select_subclasses())
    device = get_object_or_404(device_qs, pk=device_id)
    if not device.can_delete():
        messages.error(
            request, _('The "%(auth_name)s" authenticator cannot be removed.') % {'auth_name': device.name()})
        return redirect('twofa:list')

    device.deleted_at = timezone.now()
    device.save()

    messages.success(
        request, _('The "%(auth_name)s" authenticator has been removed from your account.') % {
            'auth_name': device.name()})
    if not twofa.models.Device.objects.active_for_user(request.user).exclude_backup().exists():
        request.user.twofa_enabled = False
        request.user.save()
        messages.info(
            request, _('Since you removed the last authenticator from your account, '
                       'two-factor authentication has now been disabled.'))
    return redirect('twofa:list')
项目:SpongeAuth    作者:lukegb    | 项目源码 | 文件源码
def verify_step2(request, uidb64, token):
    bytes_uid = urlsafe_base64_decode(uidb64)
    try:
        uid = int(bytes_uid)
    except ValueError:
        raise SuspiciousOperation('verify_step2 received invalid base64 user ID: {}'.format(
            bytes_uid))
    if uid != request.user.id:
        raise PermissionDenied('UID mismatch - user is {}, request was for {}'.format(
            request.user.id, uid))
    user = get_object_or_404(models.User, pk=uid)
    if not verify_token_generator.check_token(user, token):
        raise Http404('token invalid')

    if not user.email_verified:
        user.email_verified = True
        user.save()
        messages.success(request, _('Your email has been verified successfully. Thanks!'))
    else:
        messages.info(request, _('Your email address has already been verified.'))
    return redirect('index')
项目:DCRM    作者:82Flex    | 项目源码 | 文件源码
def delete_job(request, queue_index, job_id):
    queue_index = int(queue_index)
    queue = get_queue_by_index(queue_index)
    job = Job.fetch(job_id, connection=queue.connection)

    if request.method == 'POST':
        # Remove job id from queue and delete the actual job
        queue.connection._lrem(queue.key, 0, job.id)
        job.delete()
        messages.info(request, _('You have successfully deleted %s') % job.id)
        return redirect('rq_jobs', queue_index)

    context_data = admin.site.each_context(request)
    context_data.update({
        'title': _("Delete Job"),
        'queue_index': queue_index,
        'job': job,
        'queue': queue,
    })
    return render(request, 'django_rq/delete_job.html', context_data)
项目:DCRM    作者:82Flex    | 项目源码 | 文件源码
def requeue_job_view(request, queue_index, job_id):
    queue_index = int(queue_index)
    queue = get_queue_by_index(queue_index)
    job = Job.fetch(job_id, connection=queue.connection)

    if request.method == 'POST':
        requeue_job(job_id, connection=queue.connection)
        messages.info(request, _('You have successfully requeued %s') % job.id)
        return redirect('rq_job_detail', queue_index, job_id)

    context_data = {
        'queue_index': queue_index,
        'job': job,
        'queue': queue,
    }
    return render(request, 'django_rq/delete_job.html', context_data)
项目:DCRM    作者:82Flex    | 项目源码 | 文件源码
def clear_queue(request, queue_index):
    queue_index = int(queue_index)
    queue = get_queue_by_index(queue_index)

    if request.method == 'POST':
        try:
            queue.empty()
            messages.info(request, _('You have successfully cleared the queue %s') % queue.name)
        except ResponseError as e:
            if 'EVALSHA' in e.message:
                messages.error(request,
                               _('This action is not supported on Redis versions < 2.6.0, '
                                 'please use the bulk delete command instead'))
            else:
                raise e
        return redirect('rq_jobs', queue_index)

    context_data = admin.site.each_context(request)
    context_data.update({
        'title': _("Clear Queue"),
        'queue_index': queue_index,
        'queue': queue,
    })
    return render(request, 'django_rq/clear_queue.html', context_data)
项目:DCRM    作者:82Flex    | 项目源码 | 文件源码
def requeue_all(request, queue_index):
    queue_index = int(queue_index)
    queue = get_queue_by_index(queue_index)
    jobs = queue.get_jobs()

    if request.method == 'POST':
        # Confirmation received
        for job in jobs:
            requeue_job(job.id, connection=queue.connection)

        messages.info(request, _('You have successfully requeued all %d jobs!') % len(jobs))
        return redirect('rq_jobs', queue_index)

    context_data = admin.site.each_context(request)
    context_data.update({
        'title': _("Requeue All"),
        'queue_index': queue_index,
        'queue': queue,
        'total_jobs':len(jobs),
    })
    return render(request, 'django_rq/requeue_all.html', context_data)
项目:djangocms-reversion2    作者:Blueshoe    | 项目源码 | 文件源码
def add_view(self, request, form_url='', extra_context=None):
        language = request.GET.get('language')
        draft_pk = request.GET.get('draft')
        page = get_object_or_404(Page, pk=draft_pk)

        # check if the current user may view the revision
        # -> if the user may see the page
        user = get_current_user()
        if not user_can_change_page(user, page):
            messages.error(request, _('Missing permission to edit this page which is necessary in order to create a '
                                      'page version.'))
            prev = request.META.get('HTTP_REFERER')
            if prev:
                return redirect(prev)
            else:
                raise Http404

        if page.page_versions.filter(active=True, dirty=False, language=language).count() > 0:
            messages.info(request, _('This page is already revised.'))
            return self.render_close_frame()

        return super(PageVersionAdmin, self).add_view(request, form_url=form_url, extra_context=extra_context)
项目:django-lb-workflow    作者:vicalloy    | 项目源码 | 文件源码
def detail(request, pk, template_name=None, ext_ctx={}):
    instance = ProcessInstance.objects.get(pk=pk)
    views = import_wf_views(instance.process.code)
    is_print = ext_ctx.get('is_print')
    __ext_param_process = getattr(views, '__ext_param_process', None)
    ctx = {}
    ctx.update(ext_ctx)

    if not can_view_wf(instance, request.user, ext_param_process=__ext_param_process):
        messages.info(request, 'No permission to view this process')
        return redirect(reverse('wf_my_wf'))

    user_wf_info = user_wf_info_as_dict(instance.content_object, request.user)
    ctx.update(user_wf_info)

    if not is_print and instance.cur_node.can_edit \
            and instance.cur_node.audit_view_type == 'edit' \
            and ext_ctx['task'] and instance.cur_node.resolution == 'started':
        return redirect(reverse('wf_edit', args=[instance.pk]))
    detail_func = getattr(views, 'detail', _default_detail)
    ret = detail_func(request, instance, ext_ctx=ctx)
    if isinstance(ret, dict):
        ret.update(ctx)
        return _default_detail(request, instance, ret, template_name)
    return ret
项目:django-bom    作者:mpkasp    | 项目源码 | 文件源码
def upload_file_to_part(request, part_id):
    try:
        part = Part.objects.get(id=part_id)
    except ObjectDoesNotExist:
        messages.error(request, "No part found with given part_id.")
        return HttpResponseRedirect(reverse('error'))

    if request.method == 'POST':
        form = FileForm(request.POST, request.FILES)
        if form.is_valid():
            partfile = PartFile(file=request.FILES['file'], part=part)
            partfile.save()
            return HttpResponseRedirect(reverse('part-info', kwargs={'part_id': part_id}) + '#specs')

    messages.error(request, "Error uploading file.")
    return HttpResponseRedirect(reverse('error'))
项目:PonyConf    作者:PonyConf    | 项目源码 | 文件源码
def volunteer_email(request):
    volunteers = Volunteer.objects.filter(pk__in=request.session.get('volunteer-email-list', []))
    if not volunteers.exists():
        messages.error(request, _('Please select some volunteers.'))
        return redirect('volunteer-list')
    form = SendVolunteerMailForm(request.POST or None, initial=request.session.get('volunteer-email-stored'), volunteers=volunteers)
    if request.method == 'POST' and form.is_valid():
        subject = form.cleaned_data['subject']
        body = form.cleaned_data['body']
        request.session['volunteer-email-stored'] = {'subject': subject, 'body': body}
        if form.cleaned_data['confirm']:
            sent = volunteer_email_send(volunteers, subject, body)
            messages.success(request, _('%(count)d mails have been sent.') % {'count': sent})
            del request.session['volunteer-email-list']
            return redirect('volunteer-list')
        else:
            messages.info(request, _('Your ready to send %(count)d emails.') % {'count': volunteers.count()})
    else:
        form.fields.pop('confirm')
    return render(request, 'cfp/staff/volunteer_email.html', {
        'volunteers': volunteers,
        'form': form,
    })
项目:PonyConf    作者:PonyConf    | 项目源码 | 文件源码
def talk_email(request):
    talks = Talk.objects.filter(pk__in=request.session.get('talk-email-list', []))
    count = talks.annotate(speakers_count=Count('speakers', distinct=True)).aggregate(Sum('speakers_count'))['speakers_count__sum']
    if not talks.exists():
        messages.error(request, _('Please select some talks.'))
        return redirect('talk-list')
    form = SendTalkMailForm(request.POST or None, initial=request.session.get('talk-email-stored'), talks=talks)
    if request.method == 'POST' and form.is_valid():
        subject = form.cleaned_data['subject']
        body = form.cleaned_data['body']
        request.session['talk-email-stored'] = {'subject': subject, 'body': body}
        if form.cleaned_data['confirm']:
            sent = talk_email_send(talks, subject, body)
            messages.success(request, _('%(count)d mails have been sent.') % {'count': sent})
            del request.session['talk-email-list']
            return redirect('talk-list')
        else:
            messages.info(request, _('Your ready to send %(count)d emails.') % {'count': count})
    else:
        form.fields.pop('confirm')
    return render(request, 'cfp/staff/talk_email.html', {
        'talks': talks,
        'form': form,
    })
项目:PonyConf    作者:PonyConf    | 项目源码 | 文件源码
def speaker_email(request):
    speakers = Participant.objects.filter(pk__in=request.session.get('speaker-email-list', []))
    if not speakers.exists():
        messages.error(request, _('Please select some speakers.'))
        return redirect('participant-list')
    form = SendSpeakerMailForm(request.POST or None, initial=request.session.get('speaker-email-stored'), speakers=speakers)
    if request.method == 'POST' and form.is_valid():
        subject = form.cleaned_data['subject']
        body = form.cleaned_data['body']
        request.session['speaker-email-stored'] = {'subject': subject, 'body': body}
        if form.cleaned_data['confirm']:
            sent = speaker_email_send(speakers, subject, body)
            messages.success(request, _('%(count)d mails have been sent.') % {'count': sent})
            del request.session['speaker-email-list']
            return redirect('participant-list')
        else:
            messages.info(request, _('Your ready to send %(count)d emails.') % {'count': speakers.count()})
    else:
        form.fields.pop('confirm')
    return render(request, 'cfp/staff/speaker_email.html', {
        'speakers': speakers,
        'form': form,
    })
项目:ploghub    作者:ploggingdev    | 项目源码 | 文件源码
def post(self, request, *args, **kwargs):
        form = self.form_class(request.POST, initial={'email' : request.user.email, 'about' : request.user.userprofile.about})
        if form.is_valid():
            if form.has_changed():
                user = request.user

                for field in form.changed_data:
                    if field == 'email':
                        if form.cleaned_data[field] != '' and User.objects.filter(email=form.cleaned_data[field]).exclude(id=user.id).exists():
                            messages.error(request, "Email address is already in use")
                            return redirect(reverse('ploghubapp:profile'))
                    setattr(user, field, form.cleaned_data[field])
                user.save()
                user.userprofile.about = form.cleaned_data['about']
                user.userprofile.save()
                messages.success(request, "Profile has been updated")
                return redirect(reverse('ploghubapp:profile'))
            else:
                messages.info(request, "Data has not been changed")
                return redirect(reverse('ploghubapp:profile'))
        else:
            messages.error(request, "Invalid form data")
            return redirect(reverse('ploghubapp:profile'))
项目:DjStarter    作者:mijkal    | 项目源码 | 文件源码
def index(request):
    signupForm = SignupForm()
    signinForm = SigninForm()
    context = {
        'signupForm': signupForm,
        'signinForm': signinForm,
        'message': messages.debug(request, 'Bleh!')
        }

    # messages.debug(request, '%s SQL statements were executed.' % count)
    # messages.info(request, 'Three credits remain in your account.')
    # messages.success(request, 'Profile details updated.')
    # messages.warning(request, 'Your account expires in three days.')

    # messages.error(request, 'Bleh!')

    return render(request, 'user/index.html', context)
项目:pretalx    作者:pretalx    | 项目源码 | 文件源码
def form_valid(self, form):
        form.save()
        permission = self.object
        user = User.objects.get(pk=form.cleaned_data.get('user_id'))
        perm = EventPermission.objects.filter(user=user, event=permission.event).exclude(pk=permission.pk).first()
        event = permission.event

        if perm:
            if permission.is_orga:
                perm.is_orga = True
            if permission.is_reviewer:
                perm.is_reviewer = True
            perm.save()
            permission.delete()
            permission = perm

        permission.user = user
        permission.save()
        permission.event.log_action('pretalx.invite.orga.accept', person=user, orga=True)
        messages.info(self.request, _('You are now part of the event team!'))

        login(self.request, user, backend='django.contrib.auth.backends.ModelBackend')
        return redirect(event.orga_urls.base)
项目:fieldsight-kobocat    作者:awemulya    | 项目源码 | 文件源码
def add_sub_stage(request, pk=None):
    stage = get_object_or_404(
        Stage, pk=pk)
    if request.method == 'POST':
        form = AddSubSTageForm(data=request.POST, request=request)
        if form.is_valid():
            child_stage = form.save(commit=False)
            child_stage.stage = stage
            child_stage.project = stage.project
            child_stage.site = stage.site
            child_stage.group = stage.group
            child_stage.save()
            form = int(form.cleaned_data.get('form',0))
            if form:
                if stage.site:
                    FieldSightXF.objects.create(xf_id=form, is_staged=True, stage=child_stage,site=stage.site)
                else:
                    FieldSightXF.objects.create(xf_id=form, is_staged=True, stage=child_stage,project=stage.project)
            messages.info(request, 'Sub Stage {} Saved.'.format(child_stage.name))
            return HttpResponseRedirect(reverse("forms:stages-detail", kwargs={'pk': stage.id}))
    order = Stage.objects.filter(stage=stage).count() + 1
    instance = Stage(name="Sub Stage"+str(order), order=order)
    form = AddSubSTageForm(instance=instance, request=request)
    return render(request, "fsforms/add_sub_stage.html", {'form': form, 'obj': stage})
项目:fieldsight-kobocat    作者:awemulya    | 项目源码 | 文件源码
def project_edit_schedule(request, id):
    schedule = get_object_or_404(
        Schedule, pk=id)
    if request.method == 'POST':
        form = ScheduleForm(data=request.POST, instance=schedule, request=request)
        if form.is_valid():
            form.save()
            xf = int(form.cleaned_data.get('form', 0))
            if xf:
                if FieldSightXF.objects.filter(project=schedule.project, schedule=schedule, is_scheduled=True).exists():
                    fs_xform = FieldSightXF.objects.get(project=schedule.project, schedule=schedule, is_scheduled=True)
                    if fs_xform.xf.id != xf:
                        fs_xform.xf_id = xf
                        fs_xform.save()
                else:
                    FieldSightXF.objects.create(
                        xf_id=xf, is_scheduled=True,schedule=schedule,project=schedule.project, is_deployed=True)
            messages.info(request, 'Schedule {} Saved.'.format(schedule.name))
            return HttpResponseRedirect(reverse("forms:project-survey", kwargs={'project_id': schedule.project.id}))
    form = ScheduleForm(instance=schedule, request=request)
    if FieldSightXF.objects.filter(schedule=schedule).exists():
        if FieldSightXF.objects.get(schedule=schedule).xf:
            form.fields['form'].initial= FieldSightXF.objects.get(schedule=schedule).xf.id
    return render(request, "fsforms/schedule_form.html",
                  {'form': form, 'obj': schedule.project, 'is_project':True, 'is_general':False, 'is_edit':True})
项目:fieldsight-kobocat    作者:awemulya    | 项目源码 | 文件源码
def deploy_stages(request, id):
    project = Project(pk=id)
    sites = project.sites.all()
    main_stages = project.stages.filter(stage__isnull=True)
    with transaction.atomic():
        Stage.objects.filter(site__project=project).delete()
        FieldSightXF.objects.filter(is_staged=True, site__project=project).delete()
        for main_stage in main_stages:
            for site in sites:
                send_message_stages(site)
                site_main_stage = Stage(name=main_stage.name, order=main_stage.order, site=site,
                                   description=main_stage.description)
                site_main_stage.save()
                project_sub_stages = Stage.objects.filter(stage__id=main_stage.pk)
                for project_sub_stage in project_sub_stages:
                    site_sub_stage = Stage(name=project_sub_stage.name, order=project_sub_stage.order, site=site,
                                   description=project_sub_stage.description, stage=site_main_stage)
                    site_sub_stage.save()
                    if FieldSightXF.objects.filter(stage=project_sub_stage).exists():
                        fsxf = FieldSightXF.objects.filter(stage=project_sub_stage)[0]
                        FieldSightXF.objects.get_or_create(is_staged=True, xf=fsxf.xf, site=site,
                                                           fsform=fsxf, stage=site_sub_stage, is_deployed=True)

    messages.info(request, 'Stages Form Deployed to Sites')
    return HttpResponseRedirect(reverse("forms:setup-project-stages", kwargs={'id': id}))
项目:fieldsight-kobocat    作者:awemulya    | 项目源码 | 文件源码
def fill_form_type(request, pk=None):
    field_sight_form = get_object_or_404(
        FieldSightXF, pk=pk)
    if request.method == 'POST':
        form = FormTypeForm(request.POST)
        if form.is_valid():
            form_type = form.cleaned_data.get('form_type', '3')
            form_type = int(form_type)
            messages.info(request, 'Form Type Saved.')
            if form_type == 3:
                return HttpResponseRedirect(reverse("forms:library-forms-list"))
            elif form_type == 2:
                field_sight_form.is_scheduled = True
                field_sight_form.save()
                return HttpResponseRedirect(reverse("forms:fill_details_schedule", kwargs={'pk': field_sight_form.id}))
            else:
                field_sight_form.is_staged = True
                field_sight_form.save()
                return HttpResponseRedirect(reverse("forms:fill_details_stage", kwargs={'pk': field_sight_form.id}))
    else:
        form = FormTypeForm()
    return render(request, "fsforms/stage_or_schedule.html", {'form': form, 'obj': field_sight_form})
项目:django-danceschool    作者:django-danceschool    | 项目源码 | 文件源码
def dispatch(self, request, *args, **kwargs):
        '''
        Require session data to be set to proceed, otherwise go back to step 1.
        Because they have the same expiration date, this also implies that the
        TemporaryRegistration object is not yet expired.
        '''
        if REG_VALIDATION_STR not in request.session:
            return HttpResponseRedirect(reverse('registration'))

        try:
            self.temporaryRegistration = TemporaryRegistration.objects.get(
                id=self.request.session[REG_VALIDATION_STR].get('temporaryRegistrationId')
            )
        except ObjectDoesNotExist:
            messages.error(request,_('Invalid registration identifier passed to sign-up form.'))
            return HttpResponseRedirect(reverse('registration'))

        expiry = parse_datetime(
            self.request.session[REG_VALIDATION_STR].get('temporaryRegistrationExpiry',''),
        )
        if not expiry or expiry < timezone.now():
            messages.info(request,_('Your registration session has expired. Please try again.'))
            return HttpResponseRedirect(reverse('registration'))

        return super(StudentInfoView,self).dispatch(request,*args,**kwargs)
项目:django-danceschool    作者:django-danceschool    | 项目源码 | 文件源码
def dispatch(self,request,*args,**kwargs):
        '''
        Handle the session data passed by the prior view.
        '''

        lessonSession = request.session.get(PRIVATELESSON_VALIDATION_STR,{})

        try:
            self.lesson = PrivateLessonEvent.objects.get(id=lessonSession.get('lesson'))
        except (ValueError, ObjectDoesNotExist):
            messages.error(request,_('Invalid lesson identifier passed to sign-up form.'))
            return HttpResponseRedirect(reverse('bookPrivateLesson'))

        expiry = parse_datetime(lessonSession.get('expiry',''),)
        if not expiry or expiry < timezone.now():
            messages.info(request,_('Your registration session has expired. Please try again.'))
            return HttpResponseRedirect(reverse('bookPrivateLesson'))

        self.payAtDoor = lessonSession.get('payAtDoor',False)
        return super(PrivateLessonStudentInfoView,self).dispatch(request,*args,**kwargs)
项目:promgen    作者:line    | 项目源码 | 文件源码
def form_valid(self, form):
        data = form.clean()
        if data.get('file_field'):
            rules = data['file_field'].read().decode('utf8')
        elif data.get('rules'):
            rules = data.get('rules')
        else:
            messages.warning(self.request, 'Missing rules')
            return self.form_invalid(form)

        try:
            counters = prometheus.import_rules(rules)
            messages.info(self.request, 'Imported %s' % counters)
            return redirect('rule-import')
        except:
            messages.error(self.request, 'Error importing rules')
            return self.form_invalid(form)
项目:grical    作者:wikical    | 项目源码 | 文件源码
def event_does_not_exist( request, event_id, redirect_url ): # {{{1
    """ if event_id was deleted it shows event redirection or deleted page,
    otherwise raises 404 """
    try:
        deleted_version = reversion.get_deleted(Event).get(object_id=event_id)
    except Version.DoesNotExist:
        raise Http404
    revision_meta = deleted_version.revision.revisioninfo_set.all()
    assert( len( revision_meta ) == 1 )
    redirect = revision_meta[0].redirect
    if redirect:
        messages.info( request,
                _( u'redirected from deleted event %(event_nr)s' ) % \
                        {'event_nr': event_id} )
        return HttpResponseRedirect( reverse( redirect_url,
            kwargs = {'event_id': redirect,} ) )
    else:
        messages.info( request,
            _('You have tried to access an event which has been deleted.'))
        return HttpResponseRedirect( reverse(
            'event_deleted', kwargs = { 'event_id': event_id } ) )
项目:ansible-manager    作者:telminov    | 项目源码 | 文件源码
def get(self, *args, **kwargs):
        task = self.get_object()
        if task.status in consts.NOT_RUN_STATUSES:
            hosts = task.hosts.all()
            groups = task.host_groups.all()
            vars = task.vars.all()

            task.id = None
            task.pid = None
            task.status = consts.WAIT
            task.save()

            task.hosts.add(*hosts)
            task.host_groups.add(*groups)
            task.vars.add(*vars)

            models.TaskLog.objects.create(
                task=task,
                status=consts.IN_PROGRESS,
                message='Replay task'
            )
        else:
            messages.info(self.request, 'Not start duplicate task')
        return redirect(reverse('task_log', kwargs={'pk': task.id}))
项目:bluebutton-web-server    作者:CMSgov    | 项目源码 | 文件源码
def secret_question_challenge_1(request, username):
    up = get_object_or_404(UserProfile, user__username=username)

    if request.method == 'POST':
        form = SecretQuestionForm(request.POST)
        if form.is_valid():
            # Does the answer match?
            data = form.cleaned_data
            if up.password_reset_answer_1.lower() == data['answer'].lower():
                ValidPasswordResetKey.objects.create(user=up.user)
                messages.info(request,
                              'Please check your email for a special link'
                              ' to reset your password.')
                return HttpResponseRedirect(reverse('mfa_login'))
            else:
                messages.error(request,
                               'Wrong answer. Please try again.')
                return HttpResponseRedirect(reverse('secret_question_challenge',
                                                    args=(username,)))

    # HTTP GET
    return render(request,
                  'generic/bootstrapform.html',
                  {'name': up.get_password_reset_question_1_display(),
                   'form': SecretQuestionForm()})
项目:bluebutton-web-server    作者:CMSgov    | 项目源码 | 文件源码
def secret_question_challenge_2(request, username):
    up = get_object_or_404(UserProfile, user__username=username)

    if request.method == 'POST':
        form = SecretQuestionForm(request.POST)
        if form.is_valid():
            # Does the answer match?
            data = form.cleaned_data
            if up.password_reset_answer_2.lower() == data['answer'].lower():
                ValidPasswordResetKey.objects.create(user=up.user)
                messages.info(request,
                              'Please check your email for a special link'
                              ' to reset your password.')
                return HttpResponseRedirect(reverse('mfa_login'))
            else:
                messages.error(request,
                               'Wrong answer. Please try again.')
                return HttpResponseRedirect(reverse('secret_question_challenge',
                                                    args=(username,)))
    # HTTP GET
    return render(request,
                  'generic/bootstrapform.html',
                  {'name': up.get_password_reset_question_2_display(),
                   'form': SecretQuestionForm()})
项目:bluebutton-web-server    作者:CMSgov    | 项目源码 | 文件源码
def secret_question_challenge_3(request, username):
    up = get_object_or_404(UserProfile, user__username=username)
    if request.method == 'POST':
        form = SecretQuestionForm(request.POST)
        if form.is_valid():
            # Does the answer match?
            data = form.cleaned_data
            if up.password_reset_answer_3.lower() == data['answer'].lower():
                ValidPasswordResetKey.objects.create(user=up.user)
                messages.info(request,
                              'Please check your email for a special link'
                              ' to reset your password.')
                return HttpResponseRedirect(reverse('mfa_login'))
            else:
                messages.error(request,
                               'Wrong answer. Please try again.')
                return HttpResponseRedirect(reverse('secret_question_challenge',
                                                    args=(username,)))
    # HTTP GET
    return render(request,
                  'generic/bootstrapform.html',
                  {'name': up.get_password_reset_question_3_display(),
                   'form': SecretQuestionForm()})
项目:bluebutton-web-server    作者:CMSgov    | 项目源码 | 文件源码
def user_code_register(request):
    if request.method == 'POST':
        form = EndUserRegisterForm(request.POST)
        if form.is_valid():
            form.save()
            messages.info(
                request, _('Please check your email for a link to complete registration.'))
            return HttpResponseRedirect(reverse('home'))

        else:
            return render(request, 'user-code-login.html', {'form': form})
    # this is a GET
    initial = {"username": request.GET.get('username'),
               "code": request.GET.get('code')}
    return render(request, 'user-code-login.html',
                  {'form': EndUserRegisterForm(initial=initial)})
项目:TranskribusWebUI    作者:Transkribus    | 项目源码 | 文件源码
def ingest_mets_xml(request):
    if request.method == 'POST':
        try:
            #if ingest_mets_xml_file_form.is_valid(): #  TODO Check something for better error messages? And validate the file. Note: Django allows form submission, even if no file has been selected.
            t_ingest_mets_xml(request.POST.get('collection'), request.FILES['mets_file'])
            messages.info(request, 'File is being uploaded.')# TODO i18n,
            return HttpResponse(json.dumps({'RESET': 'true', 'MESSAGE': render_to_string('library/message_modal.html', request=request)}), content_type='text/plain')
        except:
            messages.error(request, 'Error!')# TODO i18n,
            return HttpResponse(json.dumps({'RESET': 'false', 'MESSAGE': render_to_string('library/message_modal.html', request=request)}), content_type='text/plain')
    else:
        ingest_mets_xml_file_form = MetsFileForm()
        collections = t_collections(request)
        if isinstance(collections,HttpResponse):
            return collections

        return render(request, 'library/ingest_mets_xml.html', {'ingest_mets_xml_form': ingest_mets_xml_file_form,  'collections': collections})
项目:TranskribusWebUI    作者:Transkribus    | 项目源码 | 文件源码
def ingest_mets_url(request):
    if request.method == 'POST':
        # What should be checked here and what can be left up to Transkribus?
        if (t_ingest_mets_url(request.POST.get('collection'), request.POST.get('url'))):
            messages.info(request, 'URL is being processed.')# TODO i18n,
            return HttpResponse(json.dumps({'RESET': 'true', 'MESSAGE': render_to_string('library/message_modal.html', request=request)}), content_type='text/plain')
        else:
            messages.error(request, 'URL processing failed.')# TODO i18n,
            return HttpResponse(json.dumps({'RESET': 'false', 'MESSAGE': render_to_string('library/message_modal.html', request=request)}), content_type='text/plain')
    else:
        data = {'url': request.GET.get('metsURL', '')}
        ingest_mets_url_form = IngestMetsUrlForm(initial=data)
        collections = t_collections(request)
        if isinstance(collections,HttpResponse):
            return collections

        return render(request, 'library/ingest_mets_url.html', {'ingest_mets_url_form': ingest_mets_url_form, 'collections': collections})
项目:poetrydb    作者:ra1ski    | 项目源码 | 文件源码
def post(self, request):
        form = self.form_class(request.POST)

        if form.is_valid():
            email = form.cleaned_data['email']
            password = form.cleaned_data['password']

            auth_user = authenticate(username=email, password=password)

            if auth_user is not None:
                if auth_user.is_active:
                    login(request, auth_user)

                    return redirect(reverse('user:user_home', args=[auth_user.id]))
                else:
                    messages.info(request, '?????? ??????????? ???????????? ??????.')
            else:
                messages.error(request, 'Email ?????? ???????? ???? ????????. ?????? ???????? ???????')

            return redirect(reverse('user:user_login'))

        return render(request, self.template_name, {
            'form': form
        })
项目:velespi    作者:lyk2016-python    | 项目源码 | 文件源码
def register(request):
    form = RegistrationForm()

    if request.method == 'POST':
        form = RegistrationForm(request.POST)

        if form.is_valid():
            form.save()

            messages.info(
                request,
                'Kay?t ba?ar?l?. ?imdi login olabilirsiniz.'
            )

            return redirect('login')

    return render(request, 'register.html', {
        'form': form,
    })
项目:velespi    作者:lyk2016-python    | 项目源码 | 文件源码
def login(request):
    form = LoginForm()

    if request.method == 'POST':
        form = LoginForm(request.POST)

        if form.is_valid():
            auth_login(request, form.user)
            messages.info(
                request,
                'Giri? yapt?n?z.'
            )

    return render(request, 'login.html', {
        'form': form
    })
项目:velespi    作者:lyk2016-python    | 项目源码 | 文件源码
def new_place(request):
    form = PlaceCreationForm()

    if request.method == "POST":
        form = PlaceCreationForm(request.POST)
        if form.is_valid():
            form.instance.user = request.user
            form.save()
            messages.info(
                request,
                'Tebrikler. Yer bildiriminiz ba?ar?yla al?nd?. '
                'Editör onay?ndan geçtikten sonra yay?nlanacakt?r.'
            )
            return redirect('/')

    return render(
        request,
        'new_place.html',
        {
            'form': form,
        }
    )
项目:DjangoCMS    作者:farhan711    | 项目源码 | 文件源码
def revert_page(self, request, page_id, language):
        page = get_object_or_404(self.model, id=page_id)
        # ensure user has permissions to publish this page
        if not page.has_change_permission(request):
            return HttpResponseForbidden(force_text(_("You do not have permission to change this page")))

        page.revert(language)

        messages.info(request, _('The page "%s" was successfully reverted.') % page)

        if 'node' in request.GET or 'node' in request.POST:
            # if request comes from tree..
            return HttpResponse(admin_utils.render_admin_menu_item(request, page))

        # TODO: This should never fail, but it may be a POF
        path = page.get_absolute_url(language=language)
        path = '%s?%s' % (path, get_cms_setting('CMS_TOOLBAR_URL__EDIT_OFF'))
        return HttpResponseRedirect(path)
项目:django-cms-articles    作者:misli    | 项目源码 | 文件源码
def get_urls(self):
        """Get the admin urls
        """
        info = '%s_%s' % (self.model._meta.app_label, self.model._meta.model_name)

        def pat(regex, fn):
            return url(regex, self.admin_site.admin_view(fn), name='%s_%s' % (info, fn.__name__))

        url_patterns = [
            pat(r'^([0-9]+)/delete-translation/$', self.delete_translation),
            pat(r'^([0-9]+)/([a-z\-]+)/publish/$', self.publish_article),
            pat(r'^([0-9]+)/([a-z\-]+)/unpublish/$', self.unpublish),
            pat(r'^([0-9]+)/([a-z\-]+)/preview/$', self.preview_article),
        ]

        url_patterns += super(ArticleAdmin, self).get_urls()
        return url_patterns
项目:website    作者:hackerspace-ntnu    | 项目源码 | 文件源码
def get_redirect_url(self, **kwargs):

        self.image.current_revision = self.revision
        self.image.save()
        messages.info(
            self.request,
            _('%(file)s has been changed to revision #%(revision)d') % {
                'file': self.image.current_revision.imagerevision.get_filename(),
                'revision': self.revision.revision_number})
        if self.urlpath:
            return reverse(
                'wiki:images_index',
                kwargs={
                    'path': self.urlpath.path})
        return reverse(
            'wiki:images_index',
            kwargs={
                'article_id': self.article.id})
项目:edx-enterprise    作者:edx    | 项目源码 | 文件源码
def add_unenrollable_item_message(request, item):
    """
    Add a message to the Django message store indicating that the item (i.e. course run, program) is unenrollable.

    :param request: The current request.
    :param item: The item that is unenrollable (i.e. a course run).
    """
    messages.info(
        request,
        _(
            '{strong_start}Something happened.{strong_end} '
            '{span_start}This {item} is not currently open to new learners. Please start over and select a different '
            '{item}.{span_end}'
        ).format(
            item=item,
            strong_start='<strong>',
            strong_end='</strong>',
            span_start='<span>',
            span_end='</span>',
        )
    )
项目:edx-enterprise    作者:edx    | 项目源码 | 文件源码
def add_generic_info_message_for_error(request):
    """
    Add message to request indicating that there was an issue processing request.

    Arguments:
        request: The current request.

    """
    messages.info(
        request,
        _(
            '{strong_start}Something happened.{strong_end} '
            '{span_start}This course is not available. '
            'Please start over and select a different course.{span_end}'
        ).format(
            span_start='<span>',
            span_end='</span>',
            strong_start='<strong>',
            strong_end='</strong>',
        )
    )
项目:nav    作者:UNINETT    | 项目源码 | 文件源码
def set_ifalias(account, fac, interface, request):
    """Set ifalias on netbox if it is requested"""
    if 'ifalias' in request.POST:
        ifalias = request.POST.get('ifalias')
        if check_format_on_ifalias(ifalias):
            try:
                fac.set_if_alias(interface.ifindex, ifalias)
                interface.ifalias = ifalias
                LogEntry.add_log_entry(
                    account,
                    u'set-ifalias',
                    u'{actor}: {object} - ifalias set to "%s"' % ifalias,
                    subsystem=u'portadmin',
                    object=interface,
                )
                _logger.info('%s: %s:%s - ifalias set to "%s"', account.login,
                             interface.netbox.get_short_sysname(),
                             interface.ifname, ifalias)
            except SnmpError as error:
                _logger.error('Error setting ifalias: %s', error)
                messages.error(request, "Error setting ifalias: %s" % error)
        else:
            messages.error(request, "Wrong format on port description")
项目:django-oscar-bookstore    作者:paiuolo    | 项目源码 | 文件源码
def post(self, request, *args, **kwargs):
        print('\n post', request.POST)
        product_id = int(request.POST.get('product_id'))
        owned_products_id = owned_products_pk(request.user)
        print('product_id owned?', product_id, owned_products_id,product_id in owned_products_id, type(product_id), type(owned_products_id[0]) )
        if product_id in owned_products_id:
            product = Product.objects.get(id=product_id)
            response = HttpResponse()
            url = "/books/virtual_store/{}",format(product.file.name)
            print('redirect to url', url)
            response['X-Accel-Redirect'] = url
            return response

        return HttpResponseRedirect(reverse('customer:personal-library'))

        messages.info(
                self.request,
                "Product not owned")
项目:website    作者:OKThess    | 项目源码 | 文件源码
def contact(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            content_vars = {
                'name': form.cleaned_data['name'],
                'email': form.cleaned_data['email'],
                'message': form.cleaned_data['message'],
            }
            send_mail(
                'Contact form submission from okthess.gr',
                render_to_string('main/contact-email.txt', content_vars),
                settings.DEFAULT_FROM_EMAIL,
                [settings.CONTACT_TO_EMAIL],
            )
            messages.info(request, "Thank you for contacting us! We'll answer ASAP.")
            return HttpResponseRedirect(reverse('main:contact'))
        else:
            return HttpResponse('Contact form is invalid.')
    else:
        return render(request, 'main/contact.html')
项目:website    作者:OKThess    | 项目源码 | 文件源码
def apply(request):
    if request.method == 'POST':
        form = ApplicationForm(request.POST)
        if form.is_valid():
            form.save()
            messages.info(request, 'Your application has been submitted. Thank you!')
            return HttpResponseRedirect(reverse('main:apply'))
        else:
            return HttpResponse('Application form submission is invalid.')
    else:
        form = ApplicationForm()
        apply_text = ApplyText.objects.first()
        application_content = ''
        if apply_text:
            if request.LANGUAGE_CODE == 'en':
                application_content = apply_text.content_en
            else:
                application_content = apply_text.content_el
        return render(request, 'main/apply.html', {
            'form': form,
            'application_content': application_content,
        })