Python django.http 模块,HttpResponseRedirect() 实例源码

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

项目:taiga-contrib-saml-auth    作者:jgiannuzzi    | 项目源码 | 文件源码
def complete_login(request):
    auth = get_saml_auth(request)
    auth.process_response()
    errors = auth.get_errors()

    if errors:
        logger.error(auth.get_last_error_reason(), exc_info=True)
        return HttpResponseBadRequest(
                content='Error when processing SAML Response: {}'.format(', '.join(errors))
                )

    if auth.is_authenticated():
        request.session['saml_attributes'] = auth.get_attributes()
        request.session['saml_nameid'] = auth.get_nameid()
        request.session['saml_session_index'] = auth.get_session_index()

        params = {'state': 'saml'}
        url = request.POST.get('RelayState', '/login')

        return HttpResponseRedirect(auth.redirect_to(url, parameters=params))

    else:
        raise PermissionDenied()
项目:TeleGiphy    作者:JessicaNgo    | 项目源码 | 文件源码
def new_game(request):
    """
    This view creates a new game token when a user clicks on "New Game" button on index.html
    This is done randomly and then checks in the database to see if that token is already present.
    If so, it'll keep on trying until it finds a unique token.
    """
    # Makes initial token
    new_token = str(random.randint(1000, 9999))
    # Checks to see if the token created is unique
    # What if ALL tokens already taken? Well, that would suck!
    while Game.objects.filter(token=new_token).exists():
        new_token = str(random.randint(1000, 9999))
    # Make new game in database with the token
    if 'game_mode' not in request.session:
        request.session['game_mode'] = request.POST['game_mode']
    game = Game(token=new_token, mode=request.session['game_mode'])
    game.save()
    if not request.user.is_authenticated():
        _give_random_name(request)

    try:
        _attach_user_to_game(game, request)
    except IntegrityError:
        return redirect(reverse('game:index'))
    return HttpResponseRedirect(reverse('game:pre_game_room', args=(new_token,)))
项目:mendelmd    作者:raonyguimaraes    | 项目源码 | 文件源码
def createconfig(request):
    print('Hello Config')
    query_string = request.META['QUERY_STRING']
    new_query_string = []
    for item in query_string.split('&'):
        if not item.startswith('individuals'):
             new_query_string.append(item)
    query_string = "&".join(new_query_string)
    filterstring = query_string

    if request.method == 'POST':
        form = Filter(request.POST)        
        if form.is_valid():
            #use id for unique names
            filterconfig = FilterConfig.objects.create(user=request.user)
            filterconfig.name = request.POST['name']
            filterconfig.filterstring = form.cleaned_data['filterstring']
            filterconfig.save()
            #return HttpResponseRedirect('/filter_analysis/?%s' % (filterconfig.filterstring))
            return redirect(reverse('filter_analysis')+'?'+filterconfig.filterstring)
    else:
        form = Filter(initial={'filterstring': filterstring})

    return render(request, 'filter_analysis/createfilter.html', {'form': form})
项目:RobotFrameworkReporter    作者:ivanitskiy    | 项目源码 | 文件源码
def upload_output_xml(request):
    if request.method == 'POST':
        form = UploadOutputXmlForm(request.POST, request.FILES)
        print "HELLP"
        if form.is_valid():
            print "YES"
            try:
                handle_uploaded_file(request)
            except:
                tt, value, tb = sys.exc_info()
                print {'exception_value': value,
                       'value': tt,
                       'tb': traceback.format_exception(tt, value, tb)}
                return handler500(request)
            return HttpResponseRedirect(reverse('home'))
        else:
            return handler500(request)
    else:
        print "No"
        form = UploadOutputXmlForm()
    return render(request, 'report/upload_xml_file.html', {'form': form})
项目:sentry-plugins    作者:getsentry    | 项目源码 | 文件源码
def sign_out(request, context):
    tenant = context.tenant
    cfg_url = '%s?signed_request=%s' % (reverse('sentry-hipchat-ac-config'), context.signed_request)

    if 'no' in request.POST:
        return HttpResponseRedirect(cfg_url)
    elif request.method == 'POST':
        if tenant.auth_user:
            tenant.clear()
            notify_tenant_removal(tenant)
        url = "%s?next=%s" % (reverse('sentry-logout'), cfg_url)
        return HttpResponseRedirect(url)

    return render(
        request, 'sentry_hipchat_ac/sign_out.html', {
            'context': context,
            'tenant': tenant,
        }
    )
项目:django-fieldbook    作者:bsab    | 项目源码 | 文件源码
def form_valid(self, form):
        user = form.save(commit=False);
        user.set_password(form.cleaned_data['password']);
        user.username = form.cleaned_data['username'].lower();
        user.email = form.cleaned_data['email'].lower();
        user.is_active = True;
        user.save();

        fbuserprofile = FieldBookUser();
        fbuserprofile.user = user;
        # saving the fieldbook key and password
        fbuserprofile.fieldbook_api_key = form.cleaned_data['username'].lower();
        fbuserprofile.fieldbook_api_secret = form.cleaned_data['password'];
        fbuserprofile.fieldbook_book= form.cleaned_data['fieldbook_book'];
        fbuserprofile.save();

        # execute login
        user_logged = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password']);
        login(self.request, user_logged);

        return HttpResponseRedirect(self.get_success_url())
项目:taiga-contrib-saml-auth    作者:jgiannuzzi    | 项目源码 | 文件源码
def complete_logout(request):
    auth = get_saml_auth(request)
    url = auth.process_slo(delete_session_cb=lambda: request.session.flush())
    errors = auth.get_errors()

    if errors:
        logger.error(auth.get_last_error_reason(), exc_info=True)
        return HttpResponseBadRequest(
                content='Error when processing SAML Logout Request: {}'.format(', '.join(errors))
                )

    params = {}
    if url:
        params['next'] = url

    return HttpResponseRedirect(auth.redirect_to('/logout', parameters=params))
项目:TeleGiphy    作者:JessicaNgo    | 项目源码 | 文件源码
def start_game(request, token):
    """
    The game is initiated through this view, not actually displayed though
    """
    # current_game can use refactoring to be queryset for easier updating and cleaner code
    current_game = Game.objects.get(token=token)
    current_game.game_active = True
    current_game.save()

    if request.session['game_mode'] == HOTSEAT_MODE:
        return HttpResponseRedirect(reverse('game:game_lobby', args=(token,)))
    elif request.session['game_mode'] == MULTIPLAYER_MODE:
        # initiallizes round 1 for all users in a multiplayer game
        users = User.objects.filter(usergame__game__token=token)
        for user in users:
            GameRound.objects.update_or_create(
                round_number=1,
                user=user,
                game=current_game,
                origin_user=user)
        current_game.total_rounds = len(users)
        current_game.mode = MULTIPLAYER_MODE
        current_game.save()
        return HttpResponseRedirect(reverse('game:multi_game_lobby', args=(token,)))
项目:TeleGiphy    作者:JessicaNgo    | 项目源码 | 文件源码
def pass_on(request, token):
    g = Game.objects.get(token=token)

    # Hotseat mode
    if g.mode == 'hotseat':
        g.current_round += 1
        g.save()
        return HttpResponseRedirect(reverse('game:game_lobby', args=(token,)))

    # Multiplayer mode
    if g.mode == 'multiplayer':
        game_round = g.gameround_set.get(
            user=request.user, round_number=g.current_round)
        game_round.committed = True
        game_round.save()
        return HttpResponseRedirect(reverse('game:waiting_room', args=(token,)))


# ================== MULTIPLAYER GAMEPLAY =========================
项目:django-tutorial    作者:fernandojunior    | 项目源码 | 文件源码
def vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice = question.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        # Redisplay the question voting form.
        return render(request, 'polls/detail.html', {
            'question': question,
            'error_message': "You didn't select a choice."
        })
    else:
        # See  Avoiding race conditions using F()
        # https://docs.djangoproject.com/en/1.9/ref/models/expressions/#avoiding-race-conditions-using-f
        selected_choice.votes += 1
        selected_choice.save()
        # Always return an HttpResponseRedirect after successfully dealing
        # with POST data. This prevents data from being posted twice if a
        # user hits the Back button.
        return HttpResponseRedirect(reverse('polls:results', args=(
            question.id,
        )))
项目:MetaCI    作者:SalesforceFoundation    | 项目源码 | 文件源码
def plan_run_repo(request, plan_id, repo_owner, repo_name):
    plan = get_object_or_404(Plan, id=plan_id)
    repo = get_object_or_404(Repository, owner=repo_owner, name=repo_name)
    if request.method == 'POST':
        form = RunPlanForm(plan, repo, request.user, request.POST)
        if form.is_valid():
            build = form.create_build()
            return HttpResponseRedirect(build.get_absolute_url())
    else:
        form = RunPlanForm(plan, repo, request.user)
    context = {
        'form': form,
        'plan': plan,
        'repo': repo,
    }
    return render(request, 'plan/run.html', context=context)
项目:MetaCI    作者:SalesforceFoundation    | 项目源码 | 文件源码
def _org_lock_unlock(request, org_id, action):
    org = get_object_or_404(Org, id=org_id)
    if org.scratch:
        raise HttpResponseForbidden('Scratch orgs may not be locked/unlocked')
    if action == 'lock':
        form_class = OrgLockForm
        template = 'cumulusci/org_lock.html'
    elif action == 'unlock':
        form_class = OrgUnlockForm
        template = 'cumulusci/org_unlock.html'
    if request.method == 'POST':
        form = form_class(request.POST)
        if form.is_valid():
            if request.POST['action'] == 'Lock':
                org.lock()
            elif request.POST['action'] == 'Unlock':
                org.unlock()
            return HttpResponseRedirect(org.get_absolute_url())
    else:
        form = form_class()
    return render(request, template, context={'form': form, 'org': org})
项目:MetaCI    作者:SalesforceFoundation    | 项目源码 | 文件源码
def _delete_notification(request, notification):
    if request.user != notification.user:
        return HttpResponseForbidden()
    if request.method == 'POST':
        form = DeleteNotificationForm(request.POST)
        if form.is_valid():
            if request.POST['action'] == 'Delete':
                notification.delete()
            return HttpResponseRedirect('/notifications')
    else:
        form = DeleteNotificationForm()
    return render(
        request,
        'notification/delete_notification.html',
        context={
            'form': form,
            'notification': notification,
            'notification_type': notification.__class__.__name__.replace(
                'Notification',
                '',
            ),
        },
    )
项目:MetaCI    作者:SalesforceFoundation    | 项目源码 | 文件源码
def build_rebuild(request, build_id):
    build = get_object_or_404(Build, id=build_id)

    if not request.user.is_staff:
        return HttpResponseForbidden(
            'You are not authorized to rebuild builds')

    rebuild = Rebuild(
        build=build,
        user=request.user,
        status='queued',
    )
    rebuild.save()

    if not build.log:
        build.log = ''

    build.log += '\n=== Build restarted at {} by {} ===\n'.format(
        timezone.now(), request.user.username)
    build.current_rebuild = rebuild
    build.save()

    return HttpResponseRedirect('/builds/{}'.format(build.id))
项目:mendelmd    作者:raonyguimaraes    | 项目源码 | 文件源码
def wizard(request):
    form = FilterWizard([FilterWiZardForm1, FilterWiZardForm2, FilterWiZardForm3])
    if request.method == 'GET':
        print('CHECK HERE')
        query_string = request.META['QUERY_STRING']
        if query_string != '':
            print("LIMPANDO")
            new_query_string = []
            query_string = query_string.split('&')
            for item in query_string:
                if not (item.startswith('csrfmiddlewaretoken') or item.startswith('hash') or item.startswith('wizard')):
                    #get here only the ones need to be cleaned Ex. 1-chr
                    item = "-".join(item.split('-', 2)[1:])
                    new_query_string.append(item)

            #create new query
            filterstring = "&".join(new_query_string)
            # return HttpResponseRedirect('/filter_analysis/?%s' % (filterstring))
            return redirect(reverse('filter_analysis')+'?'+filterstring)





    return form(context=RequestContext(request), request=request)
项目:mendelmd    作者:raonyguimaraes    | 项目源码 | 文件源码
def create(request):
    print('Hello')
    filterstring = request.META['QUERY_STRING']
    print(filterstring)
    if request.method == 'POST':
        form = Filter(request.POST)        
        if form.is_valid():
            #use id for unique names
            filter = FilterAnalysis.objects.create(user=request.user)
            filter.name = request.POST['name']
            filter.filterstring = form.cleaned_data['filterstring']
            filter.save()
            #return HttpResponseRedirect('/filter_analysis/?%s' % (filter.filterstring))
            return redirect(reverse('filter_analysis')+'?'+filter.filterstring)
    else:
        form = Filter(initial={'filterstring': filterstring})

    return render(request, 'filter_analysis/createfilter.html', {'form': form})
项目:mendelmd    作者:raonyguimaraes    | 项目源码 | 文件源码
def family_analysis_create_filter(request):
    print('Hello')
    filterstring = request.META['QUERY_STRING']
    print(filterstring)
    if request.method == 'POST':
        form = FamilyFilter(request.POST)        
        if form.is_valid():
            #use id for unique names
            filter = FamilyFilterAnalysis.objects.create(user=request.user)
            filter.name = request.POST['name']
            filter.filterstring = form.cleaned_data['filterstring']
            filter.save()
            #return HttpResponseRedirect('/filter_analysis/family_analysis/?%s' % (filter.filterstring))
            return redirect(reverse('family_analysis')+'?'+filter.filterstring)
            # return redirect('mendelmd/%s' % (reverse('family_analysis')+'?'+filter.filterstring))
    else:
        form = FamilyFilter(initial={'filterstring': filterstring})

    return render(request, 'filter_analysis/createfilter.html', {'form': form})
项目:mendelmd    作者:raonyguimaraes    | 项目源码 | 文件源码
def wizard(request):
    form = FilterWizard([FilterWiZardForm1, FilterWiZardForm2, FilterWiZardForm3])
    if request.method == 'GET':
        print('CHECK HERE')
        query_string = request.META['QUERY_STRING']
        if query_string != '':
            print("LIMPANDO")
            new_query_string = []
            query_string = query_string.split('&')
            for item in query_string:
                if not (item.startswith('csrfmiddlewaretoken') or item.startswith('hash') or item.startswith('wizard')):
                    #get here only the ones need to be cleaned Ex. 1-chr
                    item = "-".join(item.split('-', 2)[1:])
                    new_query_string.append(item)

            #create new query
            filterstring = "&".join(new_query_string)
            # return HttpResponseRedirect('/filter_analysis/?%s' % (filterstring))
            return redirect(reverse('filter_analysis')+'?'+filterstring)





    return form(context=RequestContext(request), request=request)
项目:mendelmd    作者:raonyguimaraes    | 项目源码 | 文件源码
def create(request):
    print('Hello')
    filterstring = request.META['QUERY_STRING']
    print(filterstring)
    if request.method == 'POST':
        form = Filter(request.POST)        
        if form.is_valid():
            #use id for unique names
            filter = FilterAnalysis.objects.create(user=request.user)
            filter.name = request.POST['name']
            filter.filterstring = form.cleaned_data['filterstring']
            filter.save()
            #return HttpResponseRedirect('/filter_analysis/?%s' % (filter.filterstring))
            return redirect(reverse('filter_analysis')+'?'+filter.filterstring)
    else:
        form = Filter(initial={'filterstring': filterstring})

    return render(request, 'filter_analysis/createfilter.html', {'form': form})
项目:mendelmd    作者:raonyguimaraes    | 项目源码 | 文件源码
def family_analysis_create_filter(request):
    print('Hello')
    filterstring = request.META['QUERY_STRING']
    print(filterstring)
    if request.method == 'POST':
        form = FamilyFilter(request.POST)        
        if form.is_valid():
            #use id for unique names
            filter = FamilyFilterAnalysis.objects.create(user=request.user)
            filter.name = request.POST['name']
            filter.filterstring = form.cleaned_data['filterstring']
            filter.save()
            #return HttpResponseRedirect('/filter_analysis/family_analysis/?%s' % (filter.filterstring))
            return redirect(reverse('family_analysis')+'?'+filter.filterstring)
            # return redirect('mendelmd/%s' % (reverse('family_analysis')+'?'+filter.filterstring))
    else:
        form = FamilyFilter(initial={'filterstring': filterstring})

    return render(request, 'filter_analysis/createfilter.html', {'form': form})
项目:mendelmd    作者:raonyguimaraes    | 项目源码 | 文件源码
def createconfig(request):
    print('Hello Config')
    query_string = request.META['QUERY_STRING']
    new_query_string = []
    for item in query_string.split('&'):
        if not item.startswith('individuals'):
             new_query_string.append(item)
    query_string = "&".join(new_query_string)
    filterstring = query_string

    if request.method == 'POST':
        form = Filter(request.POST)        
        if form.is_valid():
            #use id for unique names
            filterconfig = FilterConfig.objects.create(user=request.user)
            filterconfig.name = request.POST['name']
            filterconfig.filterstring = form.cleaned_data['filterstring']
            filterconfig.save()
            #return HttpResponseRedirect('/filter_analysis/?%s' % (filterconfig.filterstring))
            return redirect(reverse('filter_analysis')+'?'+filterconfig.filterstring)
    else:
        form = Filter(initial={'filterstring': filterstring})

    return render(request, 'filter_analysis/createfilter.html', {'form': form})
项目:table_tennis_league    作者:ulternate    | 项目源码 | 文件源码
def form_valid(self, form):
        # Make sure only two players are selected.
        players = form.cleaned_data['players']
        if players.count() != 2:
            form.add_error(
                'players',
                'A game requires two players, please try again.',
            )
            return self.form_invalid(form)

        # Otherwise, connect the game to the group.
        self.object = form.save()
        group = get_object_or_404(Group, id=self.kwargs.get('pk', None))

        group.games.add(self.object)
        group.save()

        return HttpResponseRedirect(self.get_success_url())
项目: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('/')
项目:geekcloud    作者:Mr-Linus    | 项目源码 | 文件源码
def require_role(role='user'):
    """
    decorator for require user role in ["super", "admin", "user"]
    ????????? ["super", "admin", "user"]????
    """

    def _deco(func):
        def __deco(request, *args, **kwargs):
            request.session['pre_url'] = request.path
            if not request.user.is_authenticated():
                return HttpResponseRedirect(reverse('login'))
            if role == 'admin':
                # if request.session.get('role_id', 0) < 1:
                if request.user.role == 'CU':
                    return HttpResponseRedirect(reverse('index'))
            elif role == 'super':
                # if request.session.get('role_id', 0) < 2:
                if request.user.role in ['CU', 'GA']:
                    return HttpResponseRedirect(reverse('index'))
            return func(request, *args, **kwargs)

        return __deco

    return _deco
项目:mos-horizon    作者:Mirantis    | 项目源码 | 文件源码
def handle(self, request, data):
        try:
            volume_id = self.initial['volume_id']
            transfer = cinder.transfer_create(request, volume_id, data['name'])

            if data['name']:
                msg = _('Created volume transfer: "%s".') % data['name']
            else:
                msg = _('Created volume transfer.')
            messages.success(request, msg)
            response = http.HttpResponseRedirect(
                reverse("horizon:project:volumes:volumes:show_transfer",
                        args=(transfer.id, transfer.auth_key)))
            return response
        except Exception:
            redirect = reverse("horizon:project:volumes:index")
            exceptions.handle(request, _('Unable to create volume transfer.'),
                              redirect=redirect)
项目:mos-horizon    作者:Mirantis    | 项目源码 | 文件源码
def handle(self, request, data):
        user_is_editable = api.keystone.keystone_can_edit_user()

        if user_is_editable:
            try:
                api.keystone.user_update_own_password(request,
                                                      data['current_password'],
                                                      data['new_password'])
                response = http.HttpResponseRedirect(settings.LOGOUT_URL)
                msg = _("Password changed. Please log in again to continue.")
                utils.add_logout_reason(request, response, msg)
                return response
            except Exception:
                exceptions.handle(request,
                                  _('Unable to change password.'))
                return False
        else:
            messages.error(request, _('Changing password is not supported.'))
            return False
项目:gitgud    作者:123z    | 项目源码 | 文件源码
def login(request):
        form = LoginModel(request.POST or None)
        if form.is_valid():
            instance = form.save(commit=False)
            user = User.objects.get(emailaddress__iexact=instance.emailaddress)
            request.session['logged'] = 1
            request.session['user'] = user.emailaddress
            request.session['type'] = user.usertype
            if form.cleaned_data["rememberMe"]:
                request.session['remember'] = True
            else:
                request.session['remember'] = False
            logging.debug(form.cleaned_data["rememberMe"])
            return HttpResponseRedirect('/')
        else:
            try:
                if request.session['remember']:
                    form.fields['emailaddress'].initial = request.session['user']
                    form.fields['rememberMe'].initial = True
            except:
                pass
        return render(request, 'auscities/login.html/', {'form':form})
项目:lightning-coindesk    作者:lightninglabs    | 项目源码 | 文件源码
def verify(request):

    assert 'login_signature' in request.POST, "No signature supplied"
    kwargs = {
        'username': request.POST.get('login_username'),
        'signature': request.POST.get('login_signature'),
        'csrf_token': str(request.POST.get('csrfmiddlewaretoken'))
    }

    user = authenticate(request=request, **kwargs)
    if user is None:
        raise Exception("Failed to log in")
        # return HttpResponseRedirect('/login')
    else:
        login(request, user)
        return HttpResponseRedirect("/")
项目:django-ajax-views    作者:Pyco7    | 项目源码 | 文件源码
def process_response(self, request, response):
        if not request.is_ajax() and not isinstance(response, HttpResponseRedirect) and hasattr(response, 'content'):
            content = force_text(response.content, encoding=response.charset)
            if '</body>' not in content:
                return response

            json_cfg = {}
            if hasattr(response, 'context_data'):
                json_cfg = response.context_data.get('json_cfg', {})

            template = get_template('ajaxviews/_middleware.html')
            html = template.render({
                'json_cfg': json_cfg,
                'main_name': settings.REQUIRE_MAIN_NAME,
            })

            l_content, r_content = content.rsplit('</body>', 1)
            content = ''.join([l_content, html, '</body>', r_content])

            response.content = response.make_bytes(content)
            if response.get('Content-Length', None):
                response['Content-Length'] = len(response.content)
        return response
项目:OpsManage    作者:welliamcao    | 项目源码 | 文件源码
def login(request):
    if request.session.get('username') is not None:
        return HttpResponseRedirect('/',{"user":request.user})
    else:
        username = request.POST.get('username')
        password = request.POST.get('password') 
        user = auth.authenticate(username=username,password=password)
        if user and user.is_active:
            auth.login(request,user)
            request.session['username'] = username
            return HttpResponseRedirect('/user/center/',{"user":request.user})
        else:
            if request.method == "POST":
                return render(request,'login.html',{"login_error_info":"???????????????"},)  
            else:
                return render(request,'login.html')
项目:ecs_sclm    作者:meaningful    | 项目源码 | 文件源码
def paste_clipboard_to_folder(request):
    if True:
        # TODO: cleanly remove Clipboard code if it is no longer needed
        return HttpResponseBadRequest('not implemented anymore')

    if request.method == 'POST':
        folder = Folder.objects.get(id=request.POST.get('folder_id'))
        clipboard = Clipboard.objects.get(id=request.POST.get('clipboard_id'))
        if folder.has_add_children_permission(request):
            tools.move_files_from_clipboard_to_folder(clipboard, folder)
            tools.discard_clipboard(clipboard)
        else:
            raise PermissionDenied
    redirect = request.GET.get('redirect_to', '')
    if not redirect:
        redirect = request.POST.get('redirect_to', '')
    return HttpResponseRedirect(
        '{0}?order_by=-modified_at{1}'.format(
            redirect,
            admin_url_params_encoded(request, first_separator='&'),
        )
    )
项目:ecs_sclm    作者:meaningful    | 项目源码 | 文件源码
def response_change(self, request, obj):
        """
        Overrides the default to be able to forward to the directory listing
        instead of the default change_list_view
        """
        if (
            request.POST and
            '_continue' not in request.POST and
            '_saveasnew' not in request.POST and
            '_addanother' not in request.POST
        ):
            if obj.parent:
                url = reverse('admin:filer-directory_listing',
                              kwargs={'folder_id': obj.parent.id})
            else:
                url = reverse('admin:filer-directory_listing-root')
            url = "{0}{1}".format(
                url,
                admin_url_params_encoded(request),
            )
            return HttpResponseRedirect(url)
        return super(FolderAdmin, self).response_change(request, obj)
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def redirect_to_login(next, login_url=None,
                      redirect_field_name=REDIRECT_FIELD_NAME):
    """
    Redirects the user to the login page, passing the given 'next' page
    """
    resolved_url = resolve_url(login_url or settings.LOGIN_URL)

    login_url_parts = list(urlparse(resolved_url))
    if redirect_field_name:
        querystring = QueryDict(login_url_parts[4], mutable=True)
        querystring[redirect_field_name] = next
        login_url_parts[4] = querystring.urlencode(safe='/')

    return HttpResponseRedirect(urlunparse(login_url_parts))


# 4 views for password reset:
# - password_reset sends the mail
# - password_reset_done shows a success message for the above
# - password_reset_confirm checks the link the user clicked and
#   prompts for a new password
# - password_reset_complete shows a success message for the above
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def response_post_save_change(self, request, obj):
        """
        Figure out where to redirect after the 'Save' button has been pressed
        when editing an existing object.
        """
        opts = self.model._meta

        if self.has_change_permission(request, None):
            post_url = reverse('admin:%s_%s_changelist' %
                               (opts.app_label, opts.model_name),
                               current_app=self.admin_site.name)
            preserved_filters = self.get_preserved_filters(request)
            post_url = add_preserved_filters({'preserved_filters': preserved_filters, 'opts': opts}, post_url)
        else:
            post_url = reverse('admin:index',
                               current_app=self.admin_site.name)
        return HttpResponseRedirect(post_url)
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
def redirect_to_login(next, login_url=None,
                      redirect_field_name=REDIRECT_FIELD_NAME):
    """
    Redirects the user to the login page, passing the given 'next' page
    """
    resolved_url = resolve_url(login_url or settings.LOGIN_URL)

    login_url_parts = list(urlparse(resolved_url))
    if redirect_field_name:
        querystring = QueryDict(login_url_parts[4], mutable=True)
        querystring[redirect_field_name] = next
        login_url_parts[4] = querystring.urlencode(safe='/')

    return HttpResponseRedirect(urlunparse(login_url_parts))


# 4 views for password reset:
# - password_reset sends the mail
# - password_reset_done shows a success message for the above
# - password_reset_confirm checks the link the user clicked and
#   prompts for a new password
# - password_reset_complete shows a success message for the above
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
def response_post_save_add(self, request, obj):
        """
        Figure out where to redirect after the 'Save' button has been pressed
        when adding a new object.
        """
        opts = self.model._meta
        if self.has_change_permission(request, None):
            post_url = reverse('admin:%s_%s_changelist' %
                               (opts.app_label, opts.model_name),
                               current_app=self.admin_site.name)
            preserved_filters = self.get_preserved_filters(request)
            post_url = add_preserved_filters({'preserved_filters': preserved_filters, 'opts': opts}, post_url)
        else:
            post_url = reverse('admin:index',
                               current_app=self.admin_site.name)
        return HttpResponseRedirect(post_url)
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
def response_post_save_change(self, request, obj):
        """
        Figure out where to redirect after the 'Save' button has been pressed
        when editing an existing object.
        """
        opts = self.model._meta

        if self.has_change_permission(request, None):
            post_url = reverse('admin:%s_%s_changelist' %
                               (opts.app_label, opts.model_name),
                               current_app=self.admin_site.name)
            preserved_filters = self.get_preserved_filters(request)
            post_url = add_preserved_filters({'preserved_filters': preserved_filters, 'opts': opts}, post_url)
        else:
            post_url = reverse('admin:index',
                               current_app=self.admin_site.name)
        return HttpResponseRedirect(post_url)
项目: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)
项目:pyconjp-website    作者:pyconjp    | 项目源码 | 文件源码
def change_locale(request):
    """
    Redirect to a given url while changing the locale in the path
    The url and the locale code need to be specified in the
    request parameters.
    """
    next = request.REQUEST.get('next', None)
    if not next:
        referrer = request.META.get('HTTP_REFERER', None)
        if referrer:
            next = urlsplit(referrer)[2]
    if not next:
        next = '/'
    _, path = utils.strip_path(next)
    if request.method == 'POST':
        locale = request.POST.get('locale', None)
        if locale and check_for_language(locale):
            if localeurl_settings.USE_SESSION:
                request.session['django_language'] = locale
            path = utils.locale_path(path, locale)

    response = http.HttpResponseRedirect(path)
    return response
项目:docker-grader    作者:elsys    | 项目源码 | 文件源码
def process_request(self, request):
        if request.method == 'POST' and \
           request.POST.get('lti_message_type') == 'basic-lti-launch-request':
            logger.debug('received a basic-lti-launch-request - '
                         'authenticating the user')

            # authenticate and log the user in
            user = auth.authenticate(request=request)

            if user is not None:
                # User is valid.
                # Set request.user and
                # persist user in the session by logging the user in.

                logger.debug('user was successfully authenticated; '
                             'now log them in')
                request.user = user
                auth.login(request, user)
                return HttpResponseRedirect(request.get_full_path())
项目:CoBL-public    作者:lingdb    | 项目源码 | 文件源码
def add_relation(request):
    if request.method == 'POST':
        form = EditRelationForm(request.POST)
        if "cancel" in form.data:  # has to be tested before data is cleaned
            return HttpResponseRedirect(request.POST['url']
                                        if 'url' in request.POST else '/')
        if form.is_valid():
            form.save()
            relation = SemanticRelation.objects.get(
                    relation_code=form.cleaned_data["relation_code"])
            return HttpResponseRedirect(relation.get_absolute_url())
    else:
        form = EditRelationForm()
    return render_template(request, "relation_edit.html",
                           {"form": form,
                            "relation": "Add semantic relation"})

# -- semantic extensions --------------------------------------------------
项目:CoBL-public    作者:lingdb    | 项目源码 | 文件源码
def alter_profile(request, username=None):
    if username:
        the_user = get_object_or_404(User, username__exact=username)
    else:
        the_user = request.user
    if request.method == 'POST':
        redirect_url = reverse("view-profile-user", args=[the_user.username])
        form = UserAlterDetailsForm(request.POST)
        if "cancel" in form.data:  # has to be tested before data is cleaned
            return HttpResponseRedirect(redirect_url)
        assert form.is_valid()
        if form.is_valid():
            for key in form.cleaned_data:
                setattr(the_user, key, form.cleaned_data[key])
            the_user.save()
            msg = "Profile details changed"
            messages.add_message(request, messages.INFO, msg)
            return HttpResponseRedirect(redirect_url)
    else:
        # form = UserAlterDetailsForm(initial=the_user.__dict__)
        form = UserAlterDetailsForm(instance=the_user)
    return render_template(request, "profiles/alter_profile.html",
                           {"the_user": the_user,
                            "form": form})
项目:CoBL-public    作者:lingdb    | 项目源码 | 文件源码
def post(self, request, pk, **kwargs):
        instance = CognateClassCitation.objects.get(id=pk)
        form = EditCognateClassCitationForm(request.POST, instance=instance)
        try:
            # validate {ref foo ...}
            s = Source.objects.all().filter(deprecated=False)
            pattern = re.compile(r'(\{ref +([^\{]+?)(:[^\{]+?)? *\})')
            for m in re.finditer(pattern, form.data['comment']):
                foundSet = s.filter(shorthand=m.group(2))
                if not foundSet.count() == 1:
                    raise ValidationError('In field “Comment” source shorthand “%(name)s” is unknown.', 
                                                params={'name': m.group(2)})
            form.save()
        except ValidationError as e:
            messages.error(
                request,
                'Sorry, the server had problems updating the cognate citation. %s' % e)
            return self.render_to_response({"form": form})
        return HttpResponseRedirect(reverse('cognate-class-citation-detail', args=[pk]))
项目: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})
项目:Django-Views-Unleashed    作者:codingforentrepreneurs    | 项目源码 | 文件源码
def post_model_create_view(request):
    form = PostModelForm(request.POST or None)
    context = {
        "form": form
    }
    if form.is_valid():
        obj = form.save(commit=False)
        #print(obj.title)
        obj.save()
        messages.success(request, "Created a new blog post!")
        context = {
            "form": PostModelForm()
        }
        #return HttpResponseRedirect("/blog/{num}".format(num=obj.id))

    template = "blog/create-view.html"
    return render(request, template, context)

#@login_required
项目:Server    作者:malaonline    | 项目源码 | 文件源码
def _get_confirm_page(self, request):
        kwargs = {}
        kwargs['teacher'] = teacher = self.get_teacher(request)
        parent = self.get_parent(request)
        if parent is None:
            redirect_url = _get_auth_redirect_url(request, teacher.id)
            logger.warning(redirect_url)
            return HttpResponseRedirect(redirect_url)
        kwargs['parent'] = parent
        grade_id = request.GET.get('grade_id')
        grade = models.Grade.objects.get(id=grade_id)
        kwargs['grade_subject_name'] = grade.name + teacher.subject().name
        school_id = request.GET.get('school_id')
        school = models.School.objects.get(id=school_id)
        kwargs['school_name'] = school.name

        # wxsdk config
        url = request.build_absolute_uri()
        sign_data = _jssdk_sign(url)
        kwargs.update(sign_data)
        kwargs['WX_APPID'] = settings.WEIXIN_APPID
        return render(request, self.confirm_page, kwargs)
项目:Server    作者:malaonline    | 项目源码 | 文件源码
def get(self, request):
        kwargs = {}
        kwargs['teacher'] = teacher = self.get_teacher(request)
        parent = self.get_parent(request)
        if parent is None:
            redirect_url = _get_auth_redirect_url(request, teacher.id)
            logger.warning(redirect_url)
            return HttpResponseRedirect(redirect_url)
        kwargs['parent'] = parent

        now = timezone.now()
        coupons = models.Coupon.objects.filter(parent=parent,
                                               expired_at__gt=now, used=False
                                               ).order_by('used', '-amount',
                                                          'expired_at')

        kwargs['coupons'] = sorted(coupons, key=lambda x: x.sort_key())
        pre_chosen_coupon = None
        # for coupon in coupons:
        #     if coupon.usable and coupon.mini_course_count==0:
        #         pre_chosen_coupon = coupon
        #         break
        # pre_chosen_coupon = pre_chosen_coupon or coupons.first()
        kwargs['pre_chosen_coupon'] = pre_chosen_coupon
        return render(request, self.template_name, kwargs)
项目:Server    作者:malaonline    | 项目源码 | 文件源码
def phone_page(request):
    template_name = 'wechat/parent/reg_phone.html'
    teacherId = request.GET.get('state')  # ??, ??, ??

    openid = request.GET.get("openid")
    if not openid:
        openid = request.POST.get("openid")

    nextpage = _get_reg_next_page(teacherId, openid)
    parent = _get_parent(request)
    if parent:
        return HttpResponseRedirect(nextpage)

    if not openid and settings.TESTING:
        # the below line is real wx_openid, but not related with ours server
        openid = 'oUpF8uMuAJO_M2pxb1Q9zNjWeS6o'

    context = {
        "openid": openid,
        "teacherId": teacherId,
        "nextpage": nextpage
    }
    return render(request, template_name, context)
项目:blog_django    作者:chnpmy    | 项目源码 | 文件源码
def post(self, request, *args, **kwargs):
        self.instance_forms()
        self.setup_forms()

        if self.valid_forms():
            self.save_forms()
            self.save_models()
            self.save_related()
            response = self.post_response()
            cls_str = str if 2 < sys.version_info.major else basestring
            if isinstance(response, cls_str):
                return HttpResponseRedirect(response)
            else:
                return response

        return self.get_response()
项目: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')