Python django.shortcuts 模块,redirect() 实例源码

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

项目: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,
    })
项目:stregsystemet    作者:f-klubben    | 项目源码 | 文件源码
def razzia_wizard(request):
    if request.method == 'POST':
        return redirect(
            reverse("razzia_view") + "?start={0}-{1}-{2}&end={3}-{4}-{5}&products={6}&username=&razzia_title={7}"
            .format(int(request.POST['start_year']),
                    int(request.POST['start_month']),
                    int(request.POST['start_day']),
                    int(request.POST['end_year']), int(request.POST['end_month']),
                    int(request.POST['end_day']),
                    request.POST.get('products'),
                    request.POST.get('razzia_title')))

    suggested_start_date = timezone.now() - datetime.timedelta(days=-180)
    suggested_end_date = timezone.now()

    start_date_picker = fields.DateField(
        widget=extras.SelectDateWidget(years=[x for x in range(2000, timezone.now().year + 1)]))
    end_date_picker = fields.DateField(
        widget=extras.SelectDateWidget(years=[x for x in range(2000, timezone.now().year + 1)]))

    return render(request, 'admin/stregsystem/razzia/wizard.html',
                  {
                      'start_date_picker': start_date_picker.widget.render("start", suggested_start_date),
                      'end_date_picker': end_date_picker.widget.render("end", suggested_end_date)},
                  )
项目:Plamber    作者:OlegKlimenko    | 项目源码 | 文件源码
def user_login(request):
    """
    Logins user if he passed authentication.
    """
    log_in_form = LogInForm(request.POST)

    if log_in_form.is_valid():
        user = authenticate(username=log_in_form.cleaned_data['username'],
                            password=log_in_form.cleaned_data['passw'])
        if user:
            login(request, user)
            logger.info("User '{}' logged in.".format(user.username))

            return redirect('index')
        else:
            return render(request, 'index.html', {'invalid_authentication': True})


# ----------------------------------------------------------------------------------------------------------------------
项目: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,)))
项目:WPS-4th    作者:Fastcampus-WPS    | 项目源码 | 文件源码
def post_add(request):
    def create_post_comment(file, comment_content):
        post = Post(author=request.user, photo=file)
        post.save()
        if comment_content != '':
            post.add_comment(user=request.user, content=comment_content)

    if request.method == 'POST':
        form = PostForm(request.POST, request.FILES)
        if form.is_valid():
            files = request.FILES.getlist('photo')
            comment_content = form.cleaned_data.get('content', '').strip()

            for file in files:
                create_post_comment(file, comment_content)

            return redirect('post:list')
    else:
        form = PostForm()

    context = {
        'form': form,
    }
    return render(request, 'post/post_add.html', context)
项目: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})
项目:socialhome    作者:jaywink    | 项目源码 | 文件源码
def get(self, request, *args, **kwargs):
        """See if we have a direct match. If so redirect, if not, search.

        Try fetching a remote profile if the search term is a handle.
        """
        try:
            q = safe_text(request.GET.get("q"))
            if q:
                q = q.strip()
            validate_email(q)
        except ValidationError:
            pass
        else:
            profile = None
            try:
                profile = Profile.objects.visible_for_user(request.user).get(handle=q)
            except Profile.DoesNotExist:
                # Try a remote search
                remote_profile = retrieve_remote_profile(q)
                if remote_profile:
                    profile = Profile.from_remote_profile(remote_profile)
            if profile:
                return redirect(reverse("users:profile-detail", kwargs={"guid": profile.guid}))
        return super().get(request, *args, **kwargs)
项目:dsa-sign-in-sheets    作者:PhillyDSA    | 项目源码 | 文件源码
def event_signin(request, *args, **kwargs):
    if not request.user.is_anonymous():
        logout(request)

    event = Event.objects.get(pk=kwargs.get('pk', None))

    if request.method == "GET":
        return render(request,
                      'signin_sheets/participant_signin.html',
                      {'form': ParticipantSigninForm,
                       'event': event})
    elif request.method == "POST":
        form = ParticipantSigninForm(request.POST)
        if form.is_valid():
            user = form.save()
            user.event = Event.objects.get(pk=kwargs.get('pk'))
            user.save()
            messages.success(request, "Your information has been saved.<br>Thanks for signing in!")

            return redirect(reverse('event-signin',
                                    kwargs={'pk': kwargs.get('pk')}))
    return redirect(reverse('event-list'))
项目:cmsplugin-form-handler    作者:mkoistinen    | 项目源码 | 文件源码
def form_invalid(self, form):
        """
        Return to sender
        """
        plugin_id = self.plugin[0].pk
        url = self.source_url
        data = form.data.copy()
        if getattr(self.request, 'session'):
            session_key = get_session_key(plugin_id)
            self.request.session[session_key] = data.urlencode()
        else:
            # Fallback to GET params...
            # Don't need this on the URL
            del data['csrfmiddlewaretoken']
            # We will need this though.
            data['cmsplugin_form_plugin_id'] = plugin_id

            params = urlparse(url)
            params.update(data)
            url = '{0}?{1}'.format(self.source_url, params)
        return redirect(url)
项目:Instagram    作者:Fastcampus-WPS-5th    | 项目源码 | 文件源码
def post_create_with_video(request):
    # POST???? video_pk?? ??
    video_pk = request.POST['video_pk']
    # ?? video_pk? ???? Video????
    video = get_object_or_404(Video, pk=video_pk)

    # ?? video? ?? Post??
    post = Post.objects.create(
        author=request.user,
        video=video,
    )
    # ??? Post??? my_comment? ???? Comment??
    post.my_comment = Comment.objects.create(
        post=post,
        author=request.user,
        content=video.title
    )
    return redirect('post:post_detail', post_pk=post.pk)
项目:Bitpoll    作者:fsinfuhh    | 项目源码 | 文件源码
def invite(request, group_name):
    group = get_object_or_404(Group, name=group_name)
    if not group.properties.admins.filter(pk=request.user.pk):
        raise PermissionDenied()

    if request.method == 'POST':
        form = InvitationForm(request.POST, group=group,
                              user=request.user)
        if form.is_valid():
            subject = u'Neue Gruppeneinladung / new group invitation'
            invitations = form.get_invitations()
            for invitation in invitations:
                invitation.save()
                _send_invitation_mail(request, invitation, subject, 'new_invitation')
            messages.success(request, _('Invitation was sent.'))
            return redirect('groups_show', group_name)
    else:
        form = InvitationForm(group=group, user=request.user)

    return TemplateResponse(request, 'groups/invite.html', {
        'group': group,
        'form': form
    })
项目: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 change_email(request, token):
    try:
        data = signing.loads(token, max_age=TOKEN_MAX_AGE)
    except signing.SignatureExpired:
        return TemplateResponse(request, 'registration/token_expired.html')
    except signing.BadSignature:
        return TemplateResponse(request, 'registration/token_invalid.html')
    if request.user.username != data.get('username'):
        return TemplateResponse(request, 'registration/token_invalid.html')
    email = data.get('email')
    try:
        validate_email(email)
    except ValidationError:
        return TemplateResponse(request, 'registration/token_invalid.html')
    request.user.email = email
    request.user.save()

    messages.success(request, _('Your email address has been changed.'))
    return redirect('registration_account')
项目:Bitpoll    作者:fsinfuhh    | 项目源码 | 文件源码
def _send_mail_or_error_page(subject, content, address, request):
    try:
        send_mail(subject, content, None, [address])
        if settings.DEBUG:
            print(u"VALIDATION MAIL to {0}\nSubject: {1}\n{2}".format(
                address, subject, content))
    except SMTPRecipientsRefused as e:
        wrong_email, (error_code, error_msg) = e.recipients.items()[0]
        unknown = 'User unknown' in error_msg
        if not unknown:
            error_email_content = u'{0}: {1}'.format(e.__class__.__name__,
                                                     repr(e.recipients))
            send_mail(
                    _('Registration: Sending mail failed: {}'.format(address)),
                    error_email_content,
                    None,
                    [settings.TEAM_EMAIL])
        return TemplateResponse(request, 'registration/email_error.html', {
            'unknown': unknown,
            'error_code': error_code,
            'error_msg': error_msg,
            'recipient': wrong_email
        })

    return redirect('registration_request_successful', address)
项目: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)
项目: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
项目:oscars2016    作者:0x0ece    | 项目源码 | 文件源码
def oauth2_authorize(request):
    """ View to start the OAuth2 Authorization flow

     This view starts the OAuth2 authorization flow. If scopes is passed in
     as a  GET URL parameter, it will authorize those scopes, otherwise the
     default scopes specified in settings. The return_url can also be
     specified as a GET parameter, otherwise the referer header will be
     checked, and if that isn't found it will return to the root path.

    :param request: The Django request object
    :return: A redirect to Google OAuth2 Authorization
    """
    scopes = request.GET.getlist('scopes', django_util.oauth2_settings.scopes)
    return_url = request.GET.get('return_url', None)

    if not return_url:
        return_url = request.META.get('HTTP_REFERER', '/')
    flow = _make_flow(request=request, scopes=scopes, return_url=return_url)
    auth_url = flow.step1_get_authorize_url()
    return shortcuts.redirect(auth_url)
项目:webtzite    作者:materialsproject    | 项目源码 | 文件源码
def login(request):
    if request.method == 'POST':
        form = AuthenticationForm(data=request.POST)
        if form.is_valid():
            code = LoginCode.objects.filter(**{
                'user__email': request.POST.get('username')
            })[0]
            code.next = reverse('webtzite_register')
            code.save()
            code.send_login_code(
                secure=request.is_secure(),
                host=request.get_host(),
            )
            return render(request, 'registration/sent_mail.html')

    jpy_user = os.environ.get('JPY_USER')
    if jpy_user:
        from django.contrib.auth import authenticate
        code = authenticate(code=None, username=jpy_user+'@users.noreply.github.com')
        user = authenticate(code=code.code, username=code.user.username)
        auth_login(request, user)
        return redirect(reverse('webtzite_register'))

    return django_login(request, authentication_form=AuthenticationForm)
项目:WPS-4th    作者:Fastcampus-WPS    | 项目源码 | 文件源码
def signup_fbv(request):
    """
    ????? ?????
    1. member/signup.html?? ??
    2. SignupForm ??? ??
    3. ?? Form? ???? signup.html??? ??
    4. POST??? ?? MyUser??? ?? ? ???
    5. ??? ???? post_list ?? ??
    """
    if request.method == 'POST':
        form = SignupForm(request.POST)
        if form.is_valid():
            user = form.create_user()
            login(request, user)
            return redirect('post:list')
    else:
        form = SignupForm()
    context = {
        'form': form,
    }
    return render(request, 'member/signup.html', context)
项目:offline-201707-weekday-afternoon    作者:askdjango    | 项目源码 | 文件源码
def post_new(request):
    if request.method == 'POST':
        form = PostModelForm(request.POST, request.FILES)
        if form.is_valid():
            # form.cleaned_data  # dict??
            post = form.save()
            return redirect(post)  # post.get_absolute_url() ???? ??? ??
            # return redirect('blog:post_detail', post.id)
    else:
    # if request.method == 'GET':
        form = PostModelForm()

    return render(request, 'blog/post_form.html', {
        'form': form,
    })

# from django.views.generic import CreateView
# post_new = CreateView.as_view(model=Post, form_class=PostModelForm, success_url='/weblog/')
# post_new = CreateView.as_view(model=Post, form_class=PostModelForm)
项目:offline-201707-weekday-afternoon    作者:askdjango    | 项目源码 | 文件源码
def post_edit(request, pk):
    post = Post.objects.get(pk=pk)

    if request.method == 'POST':
        form = PostModelForm(request.POST, request.FILES, instance=post)
        if form.is_valid():
            # form.cleaned_data  # dict??
            post = form.save()
            return redirect(post)  # post.get_absolute_url() ???? ??? ??
        # return redirect('blog:post_detail', post.id)
    else:
        # if request.method == 'GET':
        form = PostModelForm(instance=post)

    return render(request, 'blog/post_form.html', {
        'form': form,
    })

# from django.views.generic import UpdateView
# post_edit = UpdateView.as_view(model=Post, form_class=PostModelForm)
项目:Peru    作者:ESEGroup    | 项目源码 | 文件源码
def post(self, request):
        form_busca = formBusca()
        form = self.form_class(request.POST)
        if form.is_valid():
            user      = form.save(commit=False)
            nome      = form.cleaned_data['nome']
            username  = form.cleaned_data['username']
            email     = form.cleaned_data['email']
            celular   = form.cleaned_data['celular']
            descricao = form.cleaned_data['descricao']
            password  = form.cleaned_data['password']
            user.set_password(password)
            user.save()

            user = authenticate(username=username, password=password)

            if user is not None:

                if user.is_active:
                    login(request, user)
                    return redirect('../')
        return render(request, self.template_name, {'form': form, 'formBusca':form_busca, 'localidade':"Localidade "})
项目:Peru    作者:ESEGroup    | 项目源码 | 文件源码
def post(self, request):
        form_busca = formBusca()
        form = self.form_class(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            user = authenticate(username=username, password=password)
            if user is not None:
                if user.is_active:
                    login(request, user)
                    return redirect('../')
                else:
                    print("Sua conta foi desabilitada!")
            else:
                print("Seu nome de usuario e/ou senha estao incorretos.")
        return render(request, self.template_name, {'form': form, 'formBusca':form_busca, 'localidade':"Localidade "})
项目:mendelmd    作者:raonyguimaraes    | 项目源码 | 文件源码
def edit(request, individual_id):
    individual = get_object_or_404(Individual, pk=individual_id)
    if request.method == 'POST':
        form = IndividualForm(request.POST, instance=individual)
        if form.is_valid():
            form.save()
            return redirect('dashboard')
    #     form = IndividualForm(request.POST, request.FILES)
    #     if form.is_valid():
    #         individual = form.save(commit=False)
    #         individual.user = request.user
    #         individual.save()
    #         return redirect('dashboard')
    else:
        form = IndividualForm(instance=individual)

    return render(request, 'individuals/individual_form.html', {'form':form})
项目:mendelmd    作者:raonyguimaraes    | 项目源码 | 文件源码
def post(self, request, *args, **kwargs):
        #get list of diseases
        diseases_ids = request.POST.getlist('diseases')
        diseases = Disease.objects.filter(id__in=diseases_ids)
        #create list of genes
        gene_list = []
        for disease in diseases:
            genes = disease.gene_names.split(',')
            for gene in genes:
                parsed_gene = gene.strip()
                if parsed_gene not in gene_list:
                    gene_list.append(parsed_gene)
        #redirect to filter analysis page
        gene_list_url = '?gene_list=%s' % ("%2C".join(gene_list))
        #return redirect('/filter_analysis/?gene_list=%s' % ("%2C".join(gene_list)))
        # return redirect(reverse('filter_analysis', args=['some_value']))
        return redirect(reverse('filter_analysis')+gene_list_url)
        # return redirect('filter_analysis', gene_list='%s' % ("%2C".join(gene_list)))
项目:mendelmd    作者:raonyguimaraes    | 项目源码 | 文件源码
def post(self, request, *args, **kwargs):
        #get list of diseases
        diseases_ids = request.POST.getlist('diseases')
        diseases = Disease.objects.filter(id__in=diseases_ids)
        #create list of genes
        gene_list = []
        for disease in diseases:
            genes = disease.gene_names.split(',')
            for gene in genes:
                gene_list.append(gene.strip())
        #redirect to filter analysis page
        gene_list_url = '?gene_list=%s' % ("%2C".join(gene_list))
        #return redirect('/filter_analysis/?gene_list=%s' % ("%2C".join(gene_list)))
        # return redirect(reverse('filter_analysis', args=['some_value']))
        return redirect(reverse('filter_analysis')+gene_list_url)
        # return redirect('filter_analysis', gene_list='%s' % ("%2C".join(gene_list)))
项目:mendelmd    作者:raonyguimaraes    | 项目源码 | 文件源码
def edit(request, case_id):

    case = get_object_or_404(Case, pk=case_id)

    if request.method == 'POST':
        form = CaseForm(request.POST, request.FILES, instance=case)        
        if form.is_valid():
            form.save()
#            variants = form.cleaned_data['variants']
#            strs = form.cleaned_data['strs']
#            cnvs = form.cleaned_data['cnvs']
#            #use id for unique names
#            individual = Individual.objects.create(user=request.user, status='new')
#            
#            individual.variants=variants
#            individual.strs=cnvs
#            individual.cnvs=cnvs
#            
#            individual.name=request.POST['name']
#            individual.save()
#            AnnotateVariants.delay(individual.id)
            return redirect('cases_list')
    else:
        form = CaseForm(instance=case)
    return render(request, 'cases/edit.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 oneclick(request):
    form = FilterAnalysisForm()
    if request.method == 'GET':
        print('Entrando no GET')
        # print request.META
        query_string = request.META['QUERY_STRING']
        print(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 render(request, 'filter_analysis/oneclick.html', {'form':form})
项目: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})
项目: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('/')
项目:linkedin_recommend    作者:duggalr2    | 项目源码 | 文件源码
def job_misclassify(request, id):
    instance = get_list_or_404(AllJobTitle, profile_id=id)
    id_instance = [job.id for job in instance]
    instance = [job.job for job in instance]
    form = JobMisClassify(request.POST or None, extra=instance)
    industry_map = {'software': 0, 'engineering': 1, 'research': 2, 'design': 3, 'data_science': 4,
                    'product_manager': 5, 'business_finance': 6, 'startup_founder': 7,
                    'admin_it': 8, 'crypto': 9}

    if form.is_valid():
        for i in form.extra_answers():
            i = list(i)
            if len(i[-1]) > 0:
                if i[-1] in industry_map.keys():
                    i[-1] = industry_map.get(i[-1])
                    index = instance.index(i[0])
                    job_id = id_instance[index]
                    j = AllJobTitle.objects.get(id=job_id)
                    j.job_classification = i[-1]
                    j.save()

        return redirect('home')
    return render(request, 'job_misclassify.html', {'form':form})
项目:mos-horizon    作者:Mirantis    | 项目源码 | 文件源码
def get_object(self, *args, **kwargs):
        instance_id = self.kwargs['instance_id']
        try:
            instance = api.nova.server_get(self.request, instance_id)
        except Exception:
            redirect = reverse("horizon:project:instances:index")
            msg = _('Unable to retrieve instance details.')
            exceptions.handle(self.request, msg, redirect=redirect)
        flavor_id = instance.flavor['id']
        flavors = self.get_flavors()
        if flavor_id in flavors:
            instance.flavor_name = flavors[flavor_id].name
        else:
            try:
                flavor = api.nova.flavor_get(self.request, flavor_id)
                instance.flavor_name = flavor.name
            except Exception:
                msg = _('Unable to retrieve flavor information for instance '
                        '"%s".') % instance_id
                exceptions.handle(self.request, msg, ignore=True)
                instance.flavor_name = _("Not available")
        return instance
项目:mos-horizon    作者:Mirantis    | 项目源码 | 文件源码
def single(self, table, request, instance_id):
        try:
            # target_id is port_id for Neutron and instance_id for Nova Network
            # (Neutron API wrapper returns a 'portid_fixedip' string)
            target_id = api.network.floating_ip_target_get_by_instance(
                request, instance_id).split('_')[0]

            fip = api.network.tenant_floating_ip_allocate(request)
            api.network.floating_ip_associate(request, fip.id, target_id)
            messages.success(request,
                             _("Successfully associated floating IP: %s")
                             % fip.ip)
        except Exception:
            exceptions.handle(request,
                              _("Unable to associate floating IP."))
        return shortcuts.redirect(request.get_full_path())
项目:mos-horizon    作者:Mirantis    | 项目源码 | 文件源码
def single(self, table, request, instance_id):
        try:
            # target_id is port_id for Neutron and instance_id for Nova Network
            # (Neutron API wrapper returns a 'portid_fixedip' string)
            targets = api.network.floating_ip_target_list_by_instance(
                request, instance_id)

            target_ids = [t.split('_')[0] for t in targets]

            fips = [fip for fip in api.network.tenant_floating_ip_list(request)
                    if fip.port_id in target_ids]
            # Removing multiple floating IPs at once doesn't work, so this pops
            # off the first one.
            if fips:
                fip = fips.pop()
                api.network.floating_ip_disassociate(request, fip.id)
                messages.success(request,
                                 _("Successfully disassociated "
                                   "floating IP: %s") % fip.ip)
            else:
                messages.info(request, _("No floating IPs to disassociate."))
        except Exception:
            exceptions.handle(request,
                              _("Unable to disassociate floating IP."))
        return shortcuts.redirect(request.get_full_path())
项目:mos-horizon    作者:Mirantis    | 项目源码 | 文件源码
def single(self, table, request, pool_id):
        try:
            pool = api.lbaas.pool_get(request, pool_id)
            fips = api.network.tenant_floating_ip_list(request)
            vip_fips = [fip for fip in fips
                        if fip.port_id == pool.vip.port_id]
            if not vip_fips:
                messages.info(request, _("No floating IPs to disassociate."))
            else:
                api.network.floating_ip_disassociate(request,
                                                     vip_fips[0].id)
                messages.success(request,
                                 _("Successfully disassociated "
                                   "floating IP: %s") % fip.ip)
        except Exception:
            exceptions.handle(request,
                              _("Unable to disassociate floating IP."))
        return shortcuts.redirect(request.get_full_path())
项目:mos-horizon    作者:Mirantis    | 项目源码 | 文件源码
def _download_rc_file_for_template(request, context, template):
    try:
        response = shortcuts.render(request,
                                    template,
                                    context,
                                    content_type="text/plain")
        response['Content-Disposition'] = ('attachment; '
                                           'filename="%s-openrc.sh"'
                                           % context['tenant_name'])
        response['Content-Length'] = str(len(response.content))
        return response

    except Exception as e:
        LOG.exception("Exception in DownloadOpenRCForm.")
        messages.error(request, _('Error Downloading RC File: %s') % e)
        return shortcuts.redirect(request.build_absolute_uri())
项目:OJ    作者:nishantcoder97    | 项目源码 | 文件源码
def post(self, request):
        form1=self.form_class1(request.POST)
        form2 = self.form_class2(request.POST)
        if form1.is_valid() and form2.is_valid():
            user = form1.save(commit=False)
            coder = form2.save(commit=False)
            username = form1.cleaned_data['username']
            password = form1.cleaned_data['password']
            email = form1.clean_email()
            user.set_password(password)
            user.save()
            coder.user = user
            coder.save()

            user = authenticate(username = username,password = password)
            if user is not None:

                if user.is_active:
                    login(request, user)
                    return redirect('/')
        return render(request, self.template_name, {'form1': form1, 'form2': form2})
项目:fleeg-platform    作者:Fleeg    | 项目源码 | 文件源码
def new(request):
        form = None
        if request.method == 'POST':
            form = URLForm(request.POST)
            if form.is_valid():
                post = form.save(commit=False)
                user_account = Account.get_by_user(request.user)
                post.owner = user_account
                post.publisher = user_account
                try:
                    post.set_metadata()
                    post.save()
                    return redirect('home')
                except LinkException as e:
                    form.add_error(None, e)
        return render(request, 'home.html', {'form': form})
项目:blog    作者:tomming233    | 项目源码 | 文件源码
def blog_search(request,):

    search_for = request.GET['search_for']

    if search_for:
        results = []
        article_list = get_list_or_404(Article)
        category_list = get_list_or_404(Category)
        for article in article_list:
            if re.findall(search_for, article.title):
                results.append(article)
        for article in results:
            article.body = markdown.markdown(article.body, )
        tag_list = Tag.objects.all().order_by('name')
        return render(request, 'blog/search.html', {'article_list': results,
                                                    'category_list': category_list,
                                                    'tag_list': tag_list})
    else:
        return redirect('app:index')
项目:socialhome    作者:jaywink    | 项目源码 | 文件源码
def post(self, request, *args, **kwargs):
        """Save sort order."""
        self.object = self.get_object()
        self._save_sort_order(request.POST.get("sort_order").split(","))
        return redirect(self.get_success_url())
项目:socialhome    作者:jaywink    | 项目源码 | 文件源码
def post(self, request, *args, **kwargs):
        if request.POST.get("regenerate") == "regenerate":
            self.object.auth_token.delete()
        return redirect(self.get_success_url())
项目:Leyes.io    作者:tosp    | 项目源码 | 文件源码
def logout(request):
    auth_logout(request)
    return redirect('/')
项目:django-codenerix-products    作者:centrologic    | 项目源码 | 文件源码
def post(self, *args, **kwargs):
        product_delete_pk = kwargs.get('pk', None)
        product_pk = kwargs.get('tpk', None)

        if product_pk and product_delete_pk:
            product_delete = ProductFinal.objects.filter(pk=product_delete_pk).first()
            product = ProductFinal.objects.filter(pk=product_pk).first()
            if product and product_delete:
                product.related.remove(product_delete)

        return redirect(reverse_lazy("status", kwargs={'status': 'accept', 'answer': urlsafe_base64_encode(json.dumps({'__pk__': None, '__str__': 'OK'}))}))


# ------- sublista de accesorios productos -------
项目:django-codenerix-products    作者:centrologic    | 项目源码 | 文件源码
def post(self, *args, **kwargs):
        product_delete_pk = kwargs.get('pk', None)
        product_pk = kwargs.get('tpk', None)

        if product_pk and product_delete_pk:
            product_delete = ProductFinal.objects.filter(pk=product_delete_pk).first()
            product = ProductFinal.objects.filter(pk=product_pk).first()
            if product and product_delete:
                product.related_accesory.remove(product_delete)

        return redirect(reverse_lazy("status", kwargs={'status': 'accept', 'answer': urlsafe_base64_encode(json.dumps({'__pk__': None, '__str__': 'OK'}))}))


# ###########################################
项目:dsa-sign-in-sheets    作者:PhillyDSA    | 项目源码 | 文件源码
def user_logout(request):
    logout(request)
    return redirect('/')