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

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

项目:Bitpoll    作者:fsinfuhh    | 项目源码 | 文件源码
def send(self, request):
        if (not self.last_email) or self.last_email + timedelta(hours=12) < now():  # TODO: TIMEDELTA mit config
            old_lang = translation.get_language()
            translation.activate(self.user.language)
            link = reverse('poll_vote', args=(self.poll.url,))  # TODO: hier direkt das poll oder das Vote?
            email_content = render_to_string('invitations/mail_invite.txt', {
                'receiver': self.user.username,
                'creator': self.creator.username,
                'link': link
            })
            try:
                send_mail("Invitation to vote on {}".format(self.poll.title), email_content, None, [self.user.email])
                self.last_email = now()
                self.save()
            except SMTPRecipientsRefused:
                translation.activate(old_lang)
                messages.error(
                    request, _("The mail server had an error sending the notification to {}".format(self.user.username))
                )
            translation.activate(old_lang)
        else:
            messages.error(
                request, _("You have send an Email for {} in the last 12 Hours".format(self.user.username))
            )
项目:Bitpoll    作者:fsinfuhh    | 项目源码 | 文件源码
def create(request):
    error = None
    group_name = ''
    if request.method == 'POST':
        group_name = request.POST.get('group_name', '')
        try:
            create_usergroup(request.user, group_name)
            msg = _('Group "{0}" was created.').format(group_name)
            messages.success(request, msg)
            return redirect('groups_show', group_name)
        except GroupError as e:
            error = e.message
    return TemplateResponse(request, 'groups/create.html', {
        'error': error,
        'group_name': group_name,
    })
项目:valhalla    作者:LCOGT    | 项目源码 | 文件源码
def render_to_response(self, context, **kwargs):
        context['pdf'] = True
        pdf_response = HttpResponse(content_type='application/pdf')
        response = super().render_to_response(context, **kwargs)
        response.render()
        try:
            html = HTML(string=response.content)
            fileobj = io.BytesIO()
            html.write_pdf(fileobj)
            merger = PdfFileMerger()
            merger.append(fileobj)
            if self.object.science_case_file:
                merger.append(self.object.science_case_file.file)
            if self.object.experimental_design_file:
                merger.append(self.object.experimental_design_file.file)
            merger.write(pdf_response)
        except Exception as exc:
            error = 'There was an error generating your pdf. {}'
            messages.error(self.request, error.format(str(exc)))
            return HttpResponseRedirect(reverse('sciapplications:index'))
        return pdf_response
项目:LDERP    作者:Ignoramuss    | 项目源码 | 文件源码
def get_context_data(self, **kwargs):
        context = super(LoginSignupView, self).get_context_data(**kwargs)
        context.update({
            'signup_form': RegistrationForm(),
            'message':''
        })
        return context

# def change_password(request):
#     if request.method == 'POST':
#         form = PasswordChangeForm(request.user, request.POST)
#         if form.is_valid():
#             user = form.save()
#             update_session_auth_hash(request, user)  # Important!
#             messages.success(request, 'Your password was successfully updated!')
#             return redirect('login:change_password')
#         else:
#             messages.error(request, 'Please correct the error below.')
#     else:
#         form = PasswordChangeForm(request.user)
#     response = render(request, 'password_change.html', {
#         'form': form
#     })
#     response.set_cookie('password_changed', 'true')
#     return response
项目:Bitpoll    作者:fsinfuhh    | 项目源码 | 文件源码
def watch(request, poll_url):
    current_poll = get_object_or_404(Poll, url=poll_url)

    if not current_poll.can_watch(request.user, request):
        messages.error(
            request, _("You are not allowed to watch this poll.")
        )
        return redirect('poll', poll_url)

    if current_poll.user_watches(request.user):
        poll_watch = PollWatch.objects.get(poll=current_poll, user=request.user)
        poll_watch.delete()
    else:
        poll_watch = PollWatch(poll=current_poll, user=request.user)
        poll_watch.save()
    return redirect('poll', poll_url)
项目:Bitpoll    作者:fsinfuhh    | 项目源码 | 文件源码
def can_vote(self, user: BitpollUser, request: HttpRequest, is_edit: bool=False) -> bool:
        """
        Determine if the user is allowed to vote

        :param is_edit: if the vote is an edit
        :param user:
        :param request:
        :return:
        """
        has_voted = self.has_voted(user)
        if self.one_vote_per_user and has_voted and not is_edit:
            messages.error(request, _("It is only one vote allowed. You have already voted."))
            return False
        elif self.require_login and not user.is_authenticated:
            messages.error(request, _("Login required to vote."))
            return False
        elif self.require_invitation and (not user.is_authenticated or user not in self.invitation_set.all().values('user')):
            messages.error(request, _("You are not allowed to vote in this poll. You have to be invited"))
            return False
        return True
项目:openbare    作者:openbare    | 项目源码 | 文件源码
def get(self, request, *args, **kwargs):
        """Process checkout when view triggered by GET request."""
        logger = logging.getLogger('django')

        try:
            self.item = Lendable(type=self.kwargs.get('item_subtype', None),
                                 user=self.request.user)

            self.item.checkout()
            self.item.save()
        except Exception as e:
            messages.error(request, e)
            logger.exception('%s: %s' % (type(e).__name__, e))
            return redirect(reverse('library:index'))
        else:
            messages.success(
                request,
                "'%s' is checked out to you until %s." %
                (self.item.name,
                 formatting_filters.format_date(self.item.due_on))
            )

        return super(CheckoutView, self).get(request, *args, **kwargs)
项目:openbare    作者:openbare    | 项目源码 | 文件源码
def checkin(request, primary_key):
    """Checkin the :model:`library.Lendable`.

    Cleanup and delete Lendable.

    Redirect:
    :view:`library.index`
    """
    item = get_object_or_404(Lendable.all_types,
                             pk=primary_key,
                             user=request.user)
    try:
        item.checkin()
    except Exception as e:
        messages.error(request, e)
    else:
        messages.success(request, "'%s' returned." % (item.name))
    return redirect(reverse('library:index'))
项目:TeleGiphy    作者:JessicaNgo    | 项目源码 | 文件源码
def choose_name(request):
    username = request.POST['username']
    try:
        user = User.objects.create(username=username)
        if request.user.is_authenticated():
            old_user = request.user
            django_logout(request)
            old_user.delete()
        _login_user(request, user)
        messages.success(request, 'You have chosen "{}"!'.format(username))
    except IntegrityError:
        messages.error(request, 'Sorry, "{}" is already taken :('.format(username))

    return redirect(request.GET.get('next', '/'))


# Gets context of previous and current player actions for Hotseat Gameplay
项目:byro    作者:byro    | 项目源码 | 文件源码
def post(self, request: HttpRequest, *args, **kwargs) -> HttpResponseRedirect:
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = authenticate(username=username, password=password)

        if user is None:
            messages.error(request, _('No user account matches the entered credentials.'))
            return redirect('common:login')

        if not user.is_active:
            messages.error(request, _('User account is deactivated.'))
            return redirect('common:login')

        login(request, user)
        url = urllib.parse.unquote(request.GET.get('next', ''))
        if url and is_safe_url(url, request.get_host()):
            return redirect(url)

        return redirect('/')
项目:pyconjp-website    作者:pyconjp    | 项目源码 | 文件源码
def disconnect(request, backend, association_id=None):
    associated = request.user.social_auth.count()
    url = request.REQUEST.get(REDIRECT_FIELD_NAME, '') or backend_setting(backend, 'SOCIAL_AUTH_DISCONNECT_REDIRECT_URL') or DEFAULT_REDIRECT

    if not request.user.has_usable_password() and associated <= 1:
        messages.error(request, _("Cannot remove the only Social Account without first setting a Password or adding another Social Account."))
        return HttpResponseRedirect(url)

    usa = request.user.social_auth.get(pk=association_id)

    backend.disconnect(request.user, association_id)
    messages.success(request, _("Removed the %(provider)s account '%(uid)s'.") % {
        "provider": usa.provider,
        "uid": usa.extra_data.get("display", usa.uid) if usa.extra_data is not None else usa.uid,
    })

    return HttpResponseRedirect(url)
项目:CoBL-public    作者:lingdb    | 项目源码 | 文件源码
def viewAuthor(request, initials):
    try:
        author = Author.objects.get(initials=initials)
    except Author.DoesNotExist:
        messages.error(request, "Unknown Author initials: %s." % initials)
        return HttpResponseRedirect(reverse("viewAuthors"))
    languageList = LanguageList.objects.get(
        name=getDefaultLanguagelist(request))
    languageData = languageList.languages.values_list(
        'ascii_name', 'utf8_name', 'author', 'reviewer')
    authored = []
    reviewed = []
    for aName, uName, aString, rString in languageData:
        if author.fullName in set(aString.split(' and ')):
            authored.append((aName, uName))
        if author.fullName in set(rString.split(' and ')):
            reviewed.append((aName, uName))
    return render_template(
        request, "author.html", {
            'author': author,
            'authored': authored,
            'reviewed': reviewed,
            'wordlist': getDefaultWordlist(request),
            'content': fetchMarkdown(
                "Author-description:-%s.md" % author.initials)})
项目:CoBL-public    作者:lingdb    | 项目源码 | 文件源码
def handle(self, request):
        # Iterating form to update languages:
        for entry in self.langlist:
            try:
                with transaction.atomic():
                    lang = Language.objects.get(id=entry.data['idField'])
                    if lang.isChanged(**entry.data):
                        problem = lang.setDelta(request, **entry.data)
                        if problem is None:
                            lang.save()
                        else:
                            messages.error(request,
                                           lang.deltaReport(**problem))
            except Exception:
                logging.exception(
                    'Exception in LanguageDistributionTableForm.handle().',
                    extra=entry.data)
                messages.error(request, 'Sorry, the server had problems '
                               'saving at least one language entry.')
项目:CoBL-public    作者:lingdb    | 项目源码 | 文件源码
def handle(self, request):
        cladeChanged = False
        idCladeMap = {c.id: c for c in Clade.objects.all()}
        for entry in self.elements:
            data = entry.data
            try:
                clade = idCladeMap[data['idField']]
                if clade.isChanged(**data):
                    problem = clade.setDelta(request, **data)
                    if problem is None:
                        with transaction.atomic():
                            clade.save()
                            cladeChanged = True
                    else:
                        messages.error(
                            request, clade.deltaReport(**problem))
            except Exception:
                logging.exception('Problem saving clade '
                                  'in view_clades.')
                messages.error(request,
                               'Problem saving clade data: %s' % data)
        return cladeChanged
项目:CoBL-public    作者:lingdb    | 项目源码 | 文件源码
def handle(self, request):
        # Iterate entries that may be changed:
        for entry in self.cogclass:
            data = entry.data
            cogclass = CognateClass.objects.get(
                id=int(data['idField']))
            # Check if entry changed and try to update:
            if cogclass.isChanged(**data):
                try:
                    with transaction.atomic():
                        problem = cogclass.setDelta(request, **data)
                        if problem is None:
                            cogclass.save()
                        else:
                            messages.error(
                                request, cogclass.deltaReport(**problem))
                except Exception:
                    logging.exception('Problem saving CognateClass '
                                      'in view_cognateclasses.')
                    messages.error(
                        request,
                        'Problem while saving entry: %s' % data)
项目:CoBL-public    作者:lingdb    | 项目源码 | 文件源码
def handle(self, request):
        try:
            c = CognateClass.objects.get(id=self.data['id'])
            if c.isChanged(**self.data):
                with transaction.atomic():
                    try:
                        problem = c.setDelta(**self.data)
                        if problem is None:
                            c.save()
                        else:
                            messages.error(request, c.deltaReport(**problem))
                    except Exception:
                        logging.exception(
                            'Exception handling CognateClassEditForm.')
                        messages.error(
                            request,
                            'Sorry, the server had problems '
                            'updating the cognate set.')
        except CognateClass.DoesNotExist:
            logging.exception('Cognate class does not exist in database.')
            messages.error(
                request,
                "Sorry, cognate class %s does not exist on the server." %
                self.data['id'])
项目:CoBL-public    作者:lingdb    | 项目源码 | 文件源码
def handle(self, request):
        ms = [m.data for m in self.meanings]
        for m in ms:
            try:
                meaning = Meaning.objects.get(id=m['meaningId'])
                if meaning.isChanged(**m):
                    try:
                        problem = meaning.setDelta(request, **m)
                        if problem is None:
                            meaning.save()
                        else:
                            messages.error(
                                request, meaning.deltaReport(**problem))
                    except Exception:
                        logging.exception('Exception while saving POST '
                                          'in view_wordlist.')
                        messages.error(request, 'Sorry, the server had '
                                       'problems saving changes for '
                                       '"%s".' % meaning.gloss)
            except Exception:
                logging.exception('Problem accessing Meaning object '
                                  'in view_wordlist.',
                                  extra=m)
                messages.error(request, 'The server had problems saving '
                               'at least one entry.')
项目:CoBL-public    作者:lingdb    | 项目源码 | 文件源码
def handle(self, request):
        data = self.data
        try:
            with transaction.atomic():
                author = Author.objects.get(
                    id=data['idField'])
                userChanged = data['user_id'] != author.user_id
                if author.isChanged(**data) or userChanged:
                    problem = author.setDelta(request, **data)
                    if problem is None:
                        if userChanged and request.user.is_staff:
                            author.user_id = data['user_id']
                        author.save()
                    else:
                        messages.error(
                            request, author.deltaReport(**problem))
        except Exception:
            logging.exception('Problem while updating author.')
            messages.error(
                request, 'Problem saving author data: %s' % data)
项目:CoBL-public    作者:lingdb    | 项目源码 | 文件源码
def post(self, request):
        form = ChooseNexusOutputForm(request.POST)
        if form.is_valid():
            export = NexusExport(
                exportName=self.fileNameForForm(form),
                description=form.cleaned_data["description"])
            export.setSettings(form)
            export.bump(request)
            export.save()
            theId = export.id
            e = NexusExport.objects.get(id=theId)
            e.exportName = "Exp%04d_%s" % (theId, e.exportName)
            e.save()
            return HttpResponseRedirect('/nexus/export/')
        messages.error(request,"Please provide a short description.")
        return self.render_to_response({"form": form})
项目: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')
项目:postix    作者:c3cashdesk    | 项目源码 | 文件源码
def post(self, request: HttpRequest, *args, **kwargs) -> HttpResponseRedirect:
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = authenticate(username=username, password=password)

        if user is None:
            messages.error(request, _('No user account matches the entered credentials.'))
            return redirect('backoffice:login')

        if not user.is_active:
            messages.error(request, _('User account is deactivated.'))
            return redirect('backoffice:login')

        if not is_backoffice_user(user):
            messages.error(request, _('User does not have permission to access backoffice data.'))
            return redirect('backoffice:login')

        login(request, user)
        url = request.GET.get('next')
        if url and is_safe_url(url, request.get_host()):
            return redirect(url)

        return redirect('backoffice:main')
项目:postix    作者:c3cashdesk    | 项目源码 | 文件源码
def reverse_session_view(request: HttpRequest, pk: int) -> Union[HttpRequest, HttpResponseRedirect]:
    session = get_object_or_404(CashdeskSession, pk=pk)

    if request.method == 'POST':
        try:
            reverse_session(session)
        except FlowError as e:
            messages.error(request, str(e))
        else:
            messages.success(request, _('All transactions in the session have been cancelled.'))
        return redirect('backoffice:session-detail', pk=pk)

    elif request.method == 'GET':
        return render(request, 'backoffice/reverse_session.html', {
            'session': session,
        })
项目:postix    作者:c3cashdesk    | 项目源码 | 文件源码
def post(self, request: HttpRequest, *args, **kwargs) -> HttpResponseRedirect:
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = authenticate(username=username, password=password)

        if user is None:
            messages.error(request, _('No user account matches the entered credentials.'))
            return redirect('troubleshooter:login')

        if not user.is_active:
            messages.error(request, _('User account is deactivated.'))
            return redirect('troubleshooter:login')

        if not troubleshooter_user(user):
            messages.error(request, _('User does not have permission to access troubleshooter data.'))
            return redirect('troubleshooter:login')

        login(request, user)
        return redirect('troubleshooter:main')
项目:postix    作者:c3cashdesk    | 项目源码 | 文件源码
def post(self, request: HttpRequest, *args, **kwargs) -> HttpResponseRedirect:
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = authenticate(username=username, password=password)
        if user is not None:
            if not user.is_active:
                messages.error(request, _('User account is deactivated.'))
                return redirect('desk:login')

            session = user.get_current_session()
            if session is None:
                messages.error(request, _('You do not have an active session.'))
                return redirect('desk:login')

            if session.cashdesk != self.cashdesk:
                messages.error(request, _('Your session is scheduled for a different cashdesk. Please go to '
                                          '{desk}').format(desk=str(session.cashdesk)))
                return redirect('desk:login')

            login(request, user)
            session.cashdesk.signal_next()
            return redirect('desk:main')
        else:
            messages.error(request, _('No user account matches the entered credentials.'))
        return redirect('desk:login')
项目:valhalla    作者:LCOGT    | 项目源码 | 文件源码
def post(self, request, **kwargs):
        try:
            proposal = request.user.membership_set.get(proposal=kwargs.get('pk'), role=Membership.PI).proposal
        except Membership.DoesNotExist:
            raise Http404
        emails = request.POST['email'].replace(' ', '').strip(',').split(',')
        valid = True
        for email in emails:
            try:
                validate_email(email)
            except ValidationError:
                valid = False
                messages.error(request, _('Please enter a valid email address: {}'.format(email)))
        if valid:
            proposal.add_users(emails, Membership.CI)
            messages.success(request, _('Co Investigator(s) invited'))
        return HttpResponseRedirect(reverse('proposals:detail', kwargs={'pk': proposal.id}))
项目: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)
项目: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-bom    作者:mpkasp    | 项目源码 | 文件源码
def add_subpart(request, part_id):
    user = request.user
    profile = user.bom_profile()
    organization = profile.organization

    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 = AddSubpartForm(request.POST, organization=organization, part_id=part_id)
        if form.is_valid():
            new_part = Subpart.objects.create(
                assembly_part=part,
                assembly_subpart=form.cleaned_data['assembly_subpart'],
                count=form.cleaned_data['count']
            )

    return HttpResponseRedirect(reverse('part-info', kwargs={'part_id': part_id}) + '#bom')
项目: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'))
项目:registration    作者:HackAssistant    | 项目源码 | 文件源码
def post(self, request, *args, **kwargs):
        ids = request.POST.getlist('selected')
        apps = models.Application.objects.filter(pk__in=ids).all()
        mails = []
        errors = 0
        for app in apps:
            try:
                app.invite(request.user)
                m = emails.create_invite_email(app, request)
                mails.append(m)
            except ValidationError:
                errors += 1
        if mails:
            send_batch_emails(mails)
            messages.success(request, "%s applications invited" % len(mails))
        else:
            messages.error(request, "%s applications not invited" % errors)

        return HttpResponseRedirect(reverse('invite_list'))
项目:registration    作者:HackAssistant    | 项目源码 | 文件源码
def post(self, request, *args, **kwargs):
        ids = request.POST.getlist('selected')
        reimbs = models.Reimbursement.objects.filter(pk__in=ids).all()
        mails = []
        errors = 0
        for reimb in reimbs:
            try:
                assigned_money = request.POST.get('am_' + str(reimb.pk))
                reimb.assigned_money = assigned_money
                reimb.send(request.user)
                m = emails.create_reimbursement_email(reimb, request)
                mails.append(m)
            except ValidationError:
                errors += 1

        if mails:
            send_batch_emails(mails)
            messages.success(request, "%s reimbursements sent" % len(mails))
        else:
            messages.error(request, "%s reimbursements not sent" % errors)

        return HttpResponseRedirect(reverse('send_reimbursement'))
项目:registration    作者:HackAssistant    | 项目源码 | 文件源码
def signup(request):
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        form = forms.RegisterForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data['email']
            password = form.cleaned_data['password']
            name = form.cleaned_data['name']

            if models.User.objects.filter(email=email).first() is not None:
                messages.error(request, 'An account with this email already exists')
            else:
                user = models.User.objects.create_user(email=email, password=password, name=name)
                user = auth.authenticate(email=email, password=password)
                auth.login(request, user)
                return HttpResponseRedirect(reverse('root'))
    else:
        form = forms.RegisterForm()

    return render(request, 'signup.html', {'form': form})
项目:registration    作者:HackAssistant    | 项目源码 | 文件源码
def activate(request, uid, token):
    try:
        uid = force_text(urlsafe_base64_decode(uid))
        user = User.objects.get(pk=uid)
        if request.user != user:
            messages.warning(request, "User email can be verified")
            return redirect('root')
    except (TypeError, ValueError, OverflowError, User.DoesNotExist):
        messages.warning(request, "User email can be verified")
        return redirect('root')

    if account_activation_token.check_token(user, token):
        messages.success(request, "Email verified!")

        user.email_verified = True
        user.save()
        auth.login(request, user)
    else:
        messages.error(request, "This email verification url has expired")
    return redirect('root')
项目:djangoblog    作者:liuhuipy    | 项目源码 | 文件源码
def password(request):
    user = request.user

    if request.method == "POST":
        form = PasswordChangeForm(request.POST)
        if form.is_valid():
            data = form.clean()
            if user.check_password(data["old_password"]):
                user.set_password(data["password"])
                user.save()
                messages.success(request, "?????????????")
                auth_logout(request)
                return HttpResponseRedirect(reverse("login"))
            else:
                messages.error(request,'????????')
                return render(request, "users/password.html", {'errors': form.errors})
    else:
        form = PasswordChangeForm()

    return render(request, "users/password.html")
项目:site    作者:alphageek-xyz    | 项目源码 | 文件源码
def form_valid(self, form):
        form.instance.remote_address = self.request.META.get(
            'HTTP_X_REAL_IP', '0.0.0.0'
        )
        try:
            self.object = form.save()
            form.send_email(request=self.request)
        except: # pragma: no cover
            messages.error(self.request,
                'An internal server error occured.',
                extra_tags='form_invalid',
            )
        else:
            messages.success(self.request,
                'Thanks! Someone will contact you soon.',
                extra_tags='form_valid',
            )
        return super(ContactView, self).form_valid(form)
项目:admintools    作者:openstates    | 项目源码 | 文件源码
def create_person_patch(request, jur_id):
    if request.method == 'POST':
        p = Person.objects.get(id=request.POST['person'])
        # if any error occur then `create` will throw error.
        IssueResolverPatch.objects.create(
            content_object=p,
            jurisdiction_id=jur_id,
            status='unreviewed',
            old_value=request.POST['old_value'],
            new_value=request.POST['new_value'],
            source=request.POST.get('source'),
            category=request.POST['category'],
            alert='error',
            note=request.POST.get('note'),
            applied_by='admin',
        )
        messages.success(request, "Successfully created Patch")
    people = Person.objects.filter(
        memberships__organization__jurisdiction_id=jur_id).distinct()
    context = {'jur_id': jur_id,
               'people': people}
    return render(request, 'admintools/create_person_patch.html', context)


# Data Quality Exceptions
项目:API-Manager    作者:OpenBankProject    | 项目源码 | 文件源码
def get_context_data(self, **kwargs):
        context = super(IndexView, self).get_context_data(**kwargs)
        consumers = []
        api = API(self.request.session.get('obp'))
        try:
            urlpath = '/management/consumers'
            consumers = api.get(urlpath)
            consumers = FilterEnabled(context, self.request.GET)\
                .apply(consumers['list'])
            consumers = FilterAppType(context, self.request.GET)\
                .apply(consumers)
            consumers = FilterTime(context, self.request.GET, 'created')\
                .apply(consumers)
            consumers = self.scrub(consumers)
        except APIError as err:
            messages.error(self.request, err)

        sorted_consumers = sorted(
            consumers, key=lambda consumer: consumer['created'], reverse=True)
        context.update({
            'consumers': sorted_consumers,
            'statistics': self.compile_statistics(consumers),
        })
        return context
项目:API-Manager    作者:OpenBankProject    | 项目源码 | 文件源码
def get_context_data(self, **kwargs):
        context = super(DetailView, self).get_context_data(**kwargs)
        api = API(self.request.session.get('obp'))

        try:
            urlpath = '/management/consumers/{}'.format(kwargs['consumer_id'])
            consumer = api.get(urlpath)
            consumer['created'] = datetime.strptime(
                consumer['created'], settings.API_DATETIMEFORMAT)
        except APIError as err:
            messages.error(self.request, err)

        context.update({
            'consumer': consumer,
        })
        return context
项目:API-Manager    作者:OpenBankProject    | 项目源码 | 文件源码
def form_valid(self, form):
        """Posts entitlement data to API"""
        try:
            data = form.cleaned_data
            urlpath = '/users/{}/entitlements'.format(data['user_id'])
            payload = {
                'bank_id': data['bank_id'],
                'role_name': data['role_name'],
            }
            entitlement = self.api.post(urlpath, payload=payload)
        except APIError as err:
            messages.error(self.request, err)
            return super(DetailView, self).form_invalid(form)

        msg = 'Entitlement with role {} has been added.'.format(
            entitlement['role_name'])
        messages.success(self.request, msg)
        self.success_url = self.request.path
        return super(DetailView, self).form_valid(form)
项目:API-Manager    作者:OpenBankProject    | 项目源码 | 文件源码
def get_context_data(self, **kwargs):
        context = super(DetailView, self).get_context_data(**kwargs)
        # NOTE: assuming there is just one user with that email address
        # The API needs a call 'get user by id'!
        user = {}
        try:
            urlpath = '/users/user_id/{}'.format(self.kwargs['user_id'])
            user = self.api.get(urlpath)
            context['form'].fields['user_id'].initial = user['user_id']
        except APIError as err:
            messages.error(self.request, err)

        context.update({
            'apiuser': user,  # 'user' is logged-in user in template context
        })
        return context
项目:API-Manager    作者:OpenBankProject    | 项目源码 | 文件源码
def get_redirect_url(self, *args, **kwargs):
        callback_uri = self.get_callback_uri(self.request)
        try:
            authenticator = OAuthAuthenticator()
            authorization_url = authenticator.get_authorization_url(
                callback_uri)
        except AuthenticatorError as err:
            messages.error(self.request, err)
            return reverse('home')
        else:
            self.request.session['obp'] = {
                'authenticator': 'obp.oauth.OAuthAuthenticator',
                'authenticator_kwargs': {
                    'token': authenticator.token,
                    'secret': authenticator.secret,
                }
            }
            return authorization_url
项目:API-Manager    作者:OpenBankProject    | 项目源码 | 文件源码
def get_redirect_url(self, *args, **kwargs):
        session_data = self.request.session.get('obp')
        authenticator_kwargs = session_data.get('authenticator_kwargs')
        authenticator = OAuthAuthenticator(**authenticator_kwargs)
        authorization_url = self.request.build_absolute_uri()
        try:
            authenticator.set_access_token(authorization_url)
        except AuthenticatorError as err:
            messages.error(self.request, err)
        else:
            session_data['authenticator_kwargs'] = {
                'token': authenticator.token,
                'secret': authenticator.secret,
            }
            self.login_to_django()
            messages.success(self.request, 'OAuth login successful!')
        redirect_url = self.request.GET.get('next', reverse('home'))
        return redirect_url
项目:polyglot-server    作者:MontrealCorpusTools    | 项目源码 | 文件源码
def import_corpus_view(request):
    if request.method == 'POST':
        corpus_id = request.POST.get('corpus_id', None)
        success = False
        corpus = Corpus.objects.get(pk=corpus_id)

        if corpus.status == 'NI':
            t = import_corpus_task.delay(corpus.pk)
            corpus.status = 'IR'
            corpus.current_task_id = t.task_id
            corpus.save()
            success = True
        if success:
            messages.success(request, "The {} corpus import was started successfully!".format(corpus.name))
        else:
            messages.error(request, "Something went wrong!")
    return redirect('pgdb:corpus_status')
项目:polyglot-server    作者:MontrealCorpusTools    | 项目源码 | 文件源码
def change_database_status(request):
    if request.method == 'POST':
        database = request.POST.get('database', None)
        action = request.POST.get('action', None)
        if database is not None:
            db = Database.objects.get(name=database)
            if action == 'stop':
                mod_action = 'stopped'
                success = db.stop()
            elif action == 'start':
                mod_action = 'started'
                success = db.start()
            else:  # FIXME for downloading logs
                success = False
                pass
            if action != 'log':
                if success:
                    messages.success(request, "The database {} was successfully {}!".format(db.name, mod_action))
                else:
                    messages.error(request,
                                   "The database {} could not be {}. Please check the relevant logs.".format(db.name,
                                                                                                             mod_action))
    return redirect('pgdb:database_status')
项目:polyglot-server    作者:MontrealCorpusTools    | 项目源码 | 文件源码
def get_corpus_status(request, name=None):
    if request.method == 'GET':
        try:
            corpus = Corpus.objects.get(name=name)
        except ObjectDoesNotExist:
            return HttpResponse('Could not find the specified corpus.', status=status.HTTP_404_NOT_FOUND)

        if corpus.current_task_id is None:
            return JsonResponse(data={'data': 'ready'}, status=status.HTTP_200_OK)
        else:
            res = AsyncResult(corpus.current_task_id)
            if res.state == cstates.SUCCESS:
                corpus.current_task_id = None
                if corpus.status == Corpus.IMPORT_RUNNING:
                    corpus.status = Corpus.IMPORTED
                corpus.save()
                return JsonResponse(data={'data': 'ready'}, status=status.HTTP_200_OK)
            elif res.state == cstates.FAILURE:
                corpus.current_task_id = None
                if corpus.status == Corpus.IMPORT_RUNNING:
                    corpus.status = Corpus.NOT_IMPORTED
                corpus.save()
                return JsonResponse(data={'data': 'error'}, status=status.HTTP_200_OK)
            return JsonResponse(data={'data': 'busy'}, status=status.HTTP_200_OK)
项目:django-mooch    作者:matthiask    | 项目源码 | 文件源码
def success_view(self, request):
        try:
            self._process_query(request.GET.copy(), request)
        except ValidationError as exc:
            mail_managers(
                'Validation error in PostFinance success view',
                '\n'.join([
                    request.build_absolute_uri(),
                    '',
                ] + [m for m in exc.messages]),
            )
            for m in exc.messages:
                messages.error(request, m)
            return redirect(self.failure_url)
        else:
            return redirect(self.success_url)
项目:WunderHabit    作者:passuf    | 项目源码 | 文件源码
def check_webhooks(request):
    user = request.user

    if not hasattr(user, 'wunderlist'):
        return render(request, 'wunderlist/check_webhooks.html')

    api = WunderlistApi(user.wunderlist.api_token)
    lists = api.get_lists()

    if lists is None:
        messages.error(request, _('Could not get lists from Wunderlist. Please try to reconnect.'))
        return redirect('index')

    webhooks = []
    for l in lists:
        webhooks.extend(api.get_webhooks(l[default.JSON_ID]))

    return render(request, 'wunderlist/check_webhooks.html', {'lists': lists, 'webhooks': webhooks})
项目:django-unifi-portal    作者:bsab    | 项目源码 | 文件源码
def manage_auth_already_associated(backend, uid, user=None, *args, **kwargs):
    """ OVERRIDED: It will logout the current user
    instead of raise an exception

    Fix to resolve AuthAlreadyAssociated Exception in Python Social Auth:
     http://stackoverflow.com/questions/13018147/authalreadyassociated-exception-in-django-social-auth
   """

    provider = backend.name
    social = backend.strategy.storage.user.get_social_auth(provider, uid)
    if social:
        if user and social.user != user:
            messages.error(backend.strategy.request, _('This account is already in use.'))
            return HttpResponseRedirect(reverse('home'))
            # msg = 'This {0} account is already in use.'.format(provider)
            # raise AuthAlreadyAssociated(backend, msg)
        elif not user:
            user = social.user

    return {'social': social,
            'user': user,
            'is_new': user is None,
            'new_association': False}
项目:habilitacion    作者:GabrielBD    | 项目源码 | 文件源码
def login_mio(request):
  if request.method == "POST":
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(request, username=username, password=password)

    if user is not None:
      login(request, user)

      return redirect ('select_perfil')

    else:
      messages.error(request, "Usuario y/o contraseña incorrectos.")
      return render(request, 'accounts/login.html')
  else:
    return render(request, 'accounts/login.html')


#seleccionar perfil una vez logueado
项目:Quantrade    作者:quant-trade    | 项目源码 | 文件源码
def password(request):
    previous_page = settings.BASE_URL

    if request.user.has_usable_password():
        PasswordForm = PasswordChangeForm
    else:
        PasswordForm = AdminPasswordChangeForm

    if request.method == 'POST':
        form = PasswordForm(request.user, request.POST)
        if form.is_valid():
            form.save()
            update_session_auth_hash(request, form.user)
            messages.success(request, 'Your password was successfully updated!')
            #return redirect('password')
            return render(request, 'registration/password_thanks.html', {'form': form, 'previous_page': previous_page } )
        else:
            messages.error(request, 'Please correct the error below.')
    else:
        form = PasswordForm(request.user)

    return render(request, 'registration/password.html', {'form': form } )