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

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

项目: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})


# ----------------------------------------------------------------------------------------------------------------------
项目: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})
项目: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})
项目:RobotFrameworkReporter    作者:ivanitskiy    | 项目源码 | 文件源码
def handler500(request, template_name='500.html'):
    t = get_template(template_name)
    tt, value, tb = sys.exc_info()
    ctx = Context({'exception_value': value,
                   'value': tt,
                   'tb': traceback.format_exception(tt, value, tb)})
    return HttpResponseServerError(t.render(ctx))
项目: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'))
项目: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,
        }
    )
项目:UrlShortener    作者:p53ud0k0d3    | 项目源码 | 文件源码
def home(request):
    template = 'shortener/home.html'

    if request.method == 'GET':
        form_class = Urlform()
    else:
        form_class = Urlform(request.POST)

        if form_class.is_valid():
            url = form_class.cleaned_data['url']
            host = form_class.cleaned_data['host']
            short_url = worker(url, host)
            form_class = Urlform()
            return render(request, template, {'form': form_class, 'short_url': short_url,})

    return render(request, template, {'form': form_class,})
项目:Instagram    作者:Fastcampus-WPS-5th    | 项目源码 | 文件源码
def post_list_original(request):
    # ?? Post??? 'posts'?? key? context? ?? return render??
    # post/post_list.html? template?? ????? ??

    # ? ???? ?? ?? 4???? ??? ????? ???? ??
    # ? post??? CommentForm? ??? ???? ??? ????? ??

    # ??
    # 1. post_list? hashtag_post_list?? pagination? ????
    #    ? ?? 10??? ????? ??
    #   https://docs.djangoproject.com/en/1.11/topics/pagination/
    # 2. ??? ?? ?? ? ??? ? ?? ?? ??
    posts = Post.objects.all()
    context = {
        'posts': posts,
        'comment_form': CommentForm(),
    }
    return render(request, 'post/post_list.html', context)
项目:Instagram    作者:Fastcampus-WPS-5th    | 项目源码 | 文件源码
def comment_modify(request, comment_pk):
    # get_object_or_404? ???? Comment?? ????
    comment = get_object_or_404(Comment, pk=comment_pk)
    next = request.GET.get('next')
    if request.method == 'POST':
        # Form? ??? ??? update?? (data? ??? ??? update?)
        form = CommentForm(data=request.POST, instance=comment)
        if form.is_valid():
            form.save()
            if next:
                return redirect(next)
            return redirect('post:post_detail', post_pk=comment.post.pk)
    else:
        # CommentForm? ?? comment????? ??? ?? bound form
        form = CommentForm(instance=comment)
    context = {
        'form': form,
    }
    return render(request, 'post/comment_modify.html', context)
项目:Instagram    作者:Fastcampus-WPS-5th    | 项目源码 | 文件源码
def youtube_search(request):
    """
    ??? ??? ????? ??? ??
    """
    context = dict()
    q = request.GET.get('q')
    if q:
        # YouTube????? ????
        data = youtube.search(q)
        for item in data['items']:
            Video.objects.create_from_search_result(item)
        re_pattern = ''.join(['(?=.*{})'.format(item) for item in q.split()])
        videos = Video.objects.filter(
            Q(title__iregex=re_pattern) |
            Q(description__iregex=re_pattern)
        )
        context['videos'] = videos
    return render(request, 'post/youtube_search.html', context)
项目:sensu_drive    作者:ilavender    | 项目源码 | 文件源码
def clients(request):        

    data = {}

    for word in cache.keys("client_*"):
        client = re.sub(r'^client_', '', word)
        try:

            client_data = cache.get(word)
            data[client] = client_data 

        except:
            raise

    profile_form = ContactForm(instance=Contact.objects.get(user=request.user.id))

    return render(request, 'isubscribe/clients.html', {'DATA':data, 'profile_form': profile_form})
项目:sensu_drive    作者:ilavender    | 项目源码 | 文件源码
def subscriptions(request):        

    data = {}

    for word in r.keys("subscription_*"):
        subscription = re.sub(r'^subscription_', '', str(word.decode('utf-8')))
        try:

            subscription_data = r.lrange(word, 0, -1)
            data[subscription] = subscription_data 

        except:
            raise

    profile_form = ContactForm(instance=Contact.objects.get(user=request.user.id))   

    return render(request, 'isubscribe/subscriptions.html', {'DATA':data, 'profile_form': profile_form})




#@login_required(login_url=reverse_lazy('login'))
项目:sensu_drive    作者:ilavender    | 项目源码 | 文件源码
def user_settings(request):        

    logger.debug('settings view triggered by %s' % (request.user.username))

    form = ContactForm(request.POST, instance=Contact.objects.get(user=request.user.id))

    if form.is_valid:
        try:
            form.save()
            return HttpResponse('Done', status=200)
        except:        
            return HttpResponse(json.dumps(form.errors), status=409)
    else:
        return HttpResponse(json.dumps(form.errors), status=409)



    return render(request, 'isubscribe/user_settings.html', {'DATA':data, 'form': form})
项目:Plamber    作者:OlegKlimenko    | 项目源码 | 文件源码
def open_book(request, book_id):
    """
    Returns a page for reading book.
    """
    if request.user.is_authenticated():
        book = Book.objects.get(id=book_id)
        user = TheUser.objects.get(id_user=request.user)

        added_book = AddedBook.objects.get(id_book=book, id_user=user)
        added_book.last_read = added_book.last_read.now()
        added_book.save()

        logger.info("User '{}' opened book with id: '{}'.".format(user, book.id))

        context = {'book': book, 'book_page': added_book.last_page}
        return render(request, 'read_book.html', context)
    else:
        return redirect('index')


# ----------------------------------------------------------------------------------------------------------------------
项目:msdnhash    作者:mauricew    | 项目源码 | 文件源码
def index(request):
    latest_files = File.objects.order_by("-posted_date")[:10]
    latest_updated_families = ProductFamily.objects \
        .annotate(last_posted_date=Max('file__posted_date')) \
        .order_by('-last_posted_date')[:10]

    groups = ProductGroup.objects.order_by("name")
    total_count = File.objects.count()

    fcu_banner_expiration_date = datetime.date(2017, 11, 10)
    show_fcu_banner = datetime.date.today() < fcu_banner_expiration_date

    context = {
        'show_fcu_banner': show_fcu_banner,
        'latest_files': latest_files,
        'latest_updated_families': latest_updated_families,
        'groups': groups, 'total_count': total_count,
    }
    return render(request, 'msdn/index.html', context)
项目:msdnhash    作者:mauricew    | 项目源码 | 文件源码
def family_list(request):
    start_letter = request.GET.get('start_letter')
    if start_letter:
        first_letter = start_letter[0]
    else:
        first_letter = 'a'

    families = ProductFamily.objects \
        .prefetch_related('group') \
        .annotate(Count('file')) \
        .order_by('name')

    if first_letter == '#':
        families = families.exclude(name__regex=r'^[A-Za-z]')
    else:
        families = families.filter(name__istartswith=first_letter)

    all_letters = '#' + string.ascii_lowercase

    context = {'families': families, 'first_letter': first_letter, 'all_letters': all_letters}
    return render(request, 'msdn/family_list.html', context)
项目:MyFirstWebApp    作者:loyal888    | 项目源码 | 文件源码
def Login(request):
 if(request.method == "POST"):
     UserAccount = request.POST.get('name');#?????
     UserPassword = request.POST.get('password');#??????
     userInfo = getUserToSQL(UserAccount,UserPassword);#????? ??????
     if(userInfo):
         if userInfo[0].User_Role == 0:#?????
          request.session['CurrentUserId'] = userInfo[0].User_Id;#????????
          CurrentId = request.session.get('CurrentUserId');
          CurrentUser = getUserToSQLForId(CurrentId)[0];
          objs = UserInfo.objects.filter(User_Role = 1);#????????
          return render(request,'admin.html',{'CurrentUser':CurrentUser,'objs':objs});
         else:#??????
             request.session['CurrentUserId'] = userInfo[0].User_Id;
             CurrentId = request.session.get('CurrentUserId');
             CurrentUser = getUserToSQLForId(CurrentId)[0];
             signStatus = SignStatus.objects.filter(Sign_Status_User=CurrentUser)[0];#??????
             if(signStatus.Sign_Status == True):#????????
                 return render(request, 'normalOne.html', {'CurrentUser': CurrentUser, 'signStatus': signStatus});
             else:#????????

                 return  render(request,'normalTwo.html',{'CurrentUser':CurrentUser,'signStatus':signStatus});
 return HttpResponse("????????????");#?????????

#????
项目: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)
项目:WPS-4th    作者:Fastcampus-WPS    | 项目源码 | 文件源码
def bookmark_list(request):
    all_bookmarks = request.user.bookmarkvideo_set.select_related('video')

    # ?? ??? ???? ?????? ??
    paginator = Paginator(all_bookmarks, 5)
    page = request.GET.get('page')
    try:
        bookmarks = paginator.page(page)
    except PageNotAnInteger:
        bookmarks = paginator.page(1)
    except EmptyPage:
        bookmarks = paginator.page(paginator.num_pages)

    context = {
        'bookmarks': bookmarks,
    }
    return render(request, 'video/bookmark_list.html', context)
项目: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 repo_detail(request, owner, name):
    query = {
        'owner': owner,
        'name': name,
    }
    if not request.user.is_staff:
        query['public'] = True
    repo = get_object_or_404(Repository, **query)

    query = {'repo': repo}
    builds = view_queryset(request, query)
    context = {
        'repo': repo,
        'builds': builds,
    }
    return render(request, 'repository/repo_detail.html', context=context)
项目:MetaCI    作者:SalesforceFoundation    | 项目源码 | 文件源码
def branch_detail(request, owner, name, branch):
    query = {
        'owner': owner,
        'name': name,
    }
    if not request.user.is_staff:
        query['public'] = True
    repo = get_object_or_404(Repository, **query)

    branch = get_object_or_404(Branch, repo=repo, name=branch)
    query = {'branch': branch}
    builds = view_queryset(request, query)
    context = {
        'branch': branch,
        'builds': builds,
    }
    return render(request, 'repository/branch_detail.html', context=context)
项目:MetaCI    作者:SalesforceFoundation    | 项目源码 | 文件源码
def commit_detail(request, owner, name, sha):
    query = {
        'owner': owner,
        'name': name,
    }
    if not request.user.is_staff:
        query['public'] = True
    repo = get_object_or_404(Repository, **query)

    query = {'commit': sha, 'repo': repo}
    builds = view_queryset(request, query)

    context = {
        'repo': repo,
        'builds': builds,
        'commit': sha,
    }
    return render(request, 'repository/commit_detail.html', context=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 anuncio(request):
    anuncios = getTodosAnunciosValidos()
    form = formBusca()
    edit_forms = getFormsEdicaoDeAnuncios(anuncios)
    return render(request, 'anuncios/anuncios.html', {'anuncios': anuncios, 'formBusca':form, 'localidade':"Localidade ", 'editforms':edit_forms })


###################################################################################################
#View que renderiza anuncios do banco de dados filtrados por localidade.
#
#Nome: anuncioPorLocal
#Autor: Renan Basilio
#Versao: 1.0
#
#Algoritmo:
#   1. Chama o metodo getAnunciosPorLocalidade com o parametro localidade fornecido pela url
#   2. Inicializa uma form de busca
#   3. Chama o metodo render
#
####################################################################################################
项目:Peru    作者:ESEGroup    | 项目源码 | 文件源码
def anuncioPorLocal(request, localidade):
    anuncios = getAnunciosPorLocalidade(localidade)
    edit_forms = getFormsEdicaoDeAnuncios(anuncios)
    nome_local = Localidade.objects.get(nome_filtro=localidade).nome + ' '
    form = formBusca()
    return render(request, 'anuncios/anuncios.html', {'anuncios': anuncios, 'formBusca':form, 'localidade':nome_local, 'editforms':edit_forms})


###################################################################################################
#View que renderiza anuncios do banco de dados filtrados por um termo de busca
#
#Nome: anuncioPorBusca
#Autor: Renan Basilio
#Versao: 1.0
#
#Algoritmo:
#   1. Inicializa uma form de busca
#   2. Chama o metodo getAnunciosPorSubstring com o parametro 't' fornecido pela url
#   3. Chama o metodo render
#
####################################################################################################
项目:Peru    作者:ESEGroup    | 项目源码 | 文件源码
def anuncioPorBusca(request):
    form = formBusca(request.GET)
    anuncios = getAnunciosPorSubstring(request.GET.get('t'))
    edit_forms = getFormsEdicaoDeAnuncios(anuncios)
    return render(request, 'anuncios/anuncios.html', {'anuncios': anuncios, 'formBusca':form, 'localidade':"Localidade ", 'editforms':edit_forms})


###################################################################################################
#View que renderiza anuncios do banco de dados filtrados pelo usuario que os criou
#
#Nome: anuncioPorUsuario
#Autor: Renan Basilio
#Versao: 1.0
#
#Algoritmo:
#   1. Verifica se o usuario esta autenticado
#   2. Se nao retorna uma HttpResponseForbidden
#   3. Se sim, inicializa form de busca e constroi lista de anuncios a partir do metodo getAnunciosPorUsuario
#   4. Chama o metodo render
#
####################################################################################################
项目: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 view(request, disease_id):
    disease = get_object_or_404(Disease, pk=disease_id)
    gene = disease.gene_set.all()[0]
    # print 'gene', gene.official_name
    # individuals = Individual.objects.all()
    individuals_variants = Variant.objects.filter(gene=gene.official_name)
    # individuals_variants = []
    # for individual in individuals:
    #     individual_variants = Variant.objects.filter(individual=individual, gene=gene.official_name)
    #     individuals_variants.append(individual_variants)
#    individual_variants.query.group_by = ['individual_id']
#    results = query.execute_sql()
#    individuals = Individual.objects.all()
#    for individual in individuals:
#        individual_variants = Variant.objects.find(filter(date__range=["2011-01-01", "2011-01-31"]))


    return render(request, 'diseases/view.html', {'disease': disease, 'variants': individuals_variants})
项目: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 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 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})
项目:mendelmd    作者:raonyguimaraes    | 项目源码 | 文件源码
def import_files(request, project_id):
    project = get_object_or_404(Project, pk=project_id)
    form = ImportFilesForm(request.POST or None)
    if request.method == 'POST':
        if form.is_valid():
            for file in form.cleaned_data['file_list'].splitlines():
                # print(file)
                file_objs = File.objects.filter(name__contains=file)
                # print(file_obj)
                for file_obj in file_objs:
                    project.files.add(file_obj)
            # form.save()
            return redirect('projects-view', project.id)

    context = {'form': form, 'project': project}
    return render(request, 'projects/import_files.html', context)
项目:oglasi    作者:stralz    | 项目源码 | 文件源码
def napravi_oglas(request):
    if not request.user.is_authenticated():
        return render(request, 'music/login.html')
    else:
        form = OglasForm(request.POST or None, request.FILES or None)
        if form.is_valid():
            oglas = form.save(commit=False)
            oglas.vlasnik = request.user
            oglas.slike = request.FILES['slike']
            file_type = oglas.slike.url.split('.')[-1]
            file_type = file_type.lower()
            if file_type not in IMAGE_FILE_TYPES:
                context = {
                    'oglas': oglas,
                    'form': form,
                    'error_message': 'Image file must be PNG, JPG, or JPEG',
                }
                return render(request, 'music/napravi_oglas.html', context)
            oglas.save()
            return render(request, 'music/detail.html', {'oglas': oglas})
        context = {
            "form": form,
            'kategorije': Kategorija.objects.all(),
        }
        return render(request, 'music/napravi_oglas.html', context)
项目:wagtail-news-time    作者:JuanjoA    | 项目源码 | 文件源码
def search(request):
    search_query = request.GET.get('query', None)
    page = request.GET.get('page', 1)

    # Search
    if search_query:
        search_results = Page.objects.live().search(search_query)
        query = Query.get(search_query)

        # Record hit
        query.add_hit()
    else:
        search_results = Page.objects.none()

    # Pagination
    paginator = Paginator(search_results, 10)
    try:
        search_results = paginator.page(page)
    except PageNotAnInteger:
        search_results = paginator.page(1)
    except EmptyPage:
        search_results = paginator.page(paginator.num_pages)

    return render(request, 'search/search.html', {
        'search_query': search_query,
        'search_results': search_results,
    })
项目:Leyes.io    作者:tosp    | 项目源码 | 文件源码
def home(request):
    return render(request, "base/home.html")
项目:Leyes.io    作者:tosp    | 项目源码 | 文件源码
def base_files(request, filename):
    location = "base/" + filename
    return render(request, location, {}, content_type="text/plain")
项目:RobotFrameworkReporter    作者:ivanitskiy    | 项目源码 | 文件源码
def home(request):
    return render(request, "report/home.html")