示例#1
0
def experimentpage(request, exp_id,comesFromNewExp=False):
    view_url = '/experiments/'+exp_id
    #uploadFormForLiquidClasses = UploadForm()
    is_valid = False
    try:
        exp = Experiment.objects.get(pk = exp_id)
    except Exception as e:
        raise Http404
    if not request.user.is_authenticated():
         return index(request,message = 'user is not logged in')
    if request.method=='POST':
        f = ExperimentForm (request.POST,request.FILES,instance=exp)
        if f.is_valid() :
            is_valid = True
            exp = f.save()
    else:
        f= ExperimentForm(instance=exp)
        f.fields["liquidClass"].queryset = LiquidClass.objects.all().order_by('name')
    _man = exp.manualFile.file.file
    _rob = exp.robotFile.file.file
    dilsList,pipetorsCV ,dilsListForLineChart= compareManualToRobotReaderForWebApp(manualExcelFile= _man,robotExcelFile=_rob, experiment=exp)
    upload_url, upload_data = prepare_upload(request, view_url)
    distance = abs(exp.getMeans()-exp.volume)
    c = RequestContext(request,{'exp':exp,'exp_id':exp_id,'form':f,'messege':'New experiment submitted successfully','pipetorsCV':pipetorsCV,'dilsList':dilsList,'dilsListForLineChart':dilsListForLineChart, 'upload_url':upload_url, 'upload_data':upload_data,
                                'comesFromNewExperiment':False,'distance':distance})
    c.update(csrf(request))
    return render_to_response('experiment_page.html',c)
示例#2
0
    def __init__(self, request, dictionary = None, current_project = None, current_story = None):
        self.request = request

        if request.user.is_authenticated():
            project_list = request.user.project_set.all()
            if project_list is None or project_list.count() == 0:
                raise UserHasNoProjectException
        else:
            raise UserHasNoProjectException

        if current_project is None:
            current_project = project_list[0]
        else:
            current_project = Project.objects.get(pk = current_project)

        if current_story is not None:
            try:
                current_story = UserStory.objects.get(id = current_story)
            except UserStory.DoesNotExist:
                current_story = None

        if dictionary is None:
            self.dictionary = { 'project_list' : project_list,
                                'current_project' : current_project,
                                'current_story': current_story,
                                'last_page': request.path,
                                }
        else:
            self.dictionary = dictionary
            self.dictionary['project_list'] = project_list
            self.dictionary['current_project'] = current_project
            self.dictionary['current_story'] = current_story
            self.dictionary['last_page'] = request.path
        
        RequestContext.__init__(self, self.request, self.dictionary)
示例#3
0
def lightbox_login(request):
    t = loader.get_template('lightbox/login.html')
    c = RequestContext(request, {
        'subscribe_form': ExpressRegistrationForm(),
    })
    c.update(csrf(request))
    return HttpResponse(t.render(c))
def add_occurrence(request):

    t = loader.get_template('add-occurrence.html')
    c = RequestContext(request)
    c.update(csrf(request))

    return HttpResponse(t.render(c))
示例#5
0
def get_from_context(request, what, default=None):
    context = RequestContext(request)
    if hasattr(context, 'bind_template'):
        # Django 1.8: force context processors
        with context.bind_template(Template('')):
            return context.get(what, default)
    return context.get(what, default)
示例#6
0
def signup(request):
    status = 0
    if request.user.is_authenticated():
        return HttpResponseRedirect('/')
    else:
        if request.method == 'POST':
            form = SignupForm(request.POST)
            if form.is_valid():
                if form.cleaned_data.get('username') and form.cleaned_data.get('password') and form.cleaned_data.get('email'):
                    username = form.cleaned_data.get('username')
                    password = form.cleaned_data.get('password')
                    email = form.cleaned_data.get('email')
                    User.objects.create_user(username=username, password=password, email=email,
                                             first_name='No', last_name='Name')
                    MyUser.objects.create(user=User.objects.get(username=username))
                    status = 1
        else:
            form = SignupForm()

        context = RequestContext(request, {
            'form': form,
            'status': status,
        })
        context.update(csrf(request))

        return render_to_response("signup.html", context)
示例#7
0
文件: views.py 项目: bl1nd/omnomnom
def confirm(request):
    context = RequestContext(request)
    context.update(csrf(request))

    if not request.user.is_authenticated():
        return HttpResponse("(\/)~(-_-)~(\/) Вы не туда попали (\/)~(-_-)~(\/)")

    if not request.method == "POST":
        return HttpResponse("(\/)~(-_-)~(\/) Вы не туда попали (\/)~(-_-)~(\/)")
    value = []
    for key in request.POST:
        if key[:4] == "dish" and request.POST[key] == u"on":
            try:
                value.append(int(key[4:]))
            except:
                return HttpResponse("Error {0}: {1}".format(str(exc_info()[0]), exc_info()[1]))

    tDishes = Dish.objects.filter(numbro__in=value)
    summ = 0
    for item in tDishes:
        summ += item.price
    context["tDishes"] = tDishes
    context["summ"] = summ
    context["device"] = device_check(request)
    return HttpResponse(get_template("omnomnom/confirm.html").render(context))
示例#8
0
def multipartite_view_free_sbol(request):
    context = RequestContext(request)
    context.update(csrf(request))
    if request.method == 'POST':
        request_data = request.POST
    else:
        msg = "To get the sequence you need first to assemble parts"
        return HttpResponseBadRequest(msg)

    feats = [request_data['vector']]
    for k in sorted(request_data.keys()):
        if 'part_' in k:
            feats.append(request_data[k])

    form_class = get_multipartite_free_form(feats)
    form = form_class(request_data)
    if form.is_valid():
        last_feat = Feature.objects.get(uniquename=feats[-1])
        last_suffix = last_feat.suffix
        if last_suffix == 'CGCT':
            protocol_data, part_order = _get_fragments_from_request(request)
            assembled_seq = assemble_parts(protocol_data, part_order)
            response = HttpResponse(convert_to_sbol(assembled_seq),
                                    content_type='xml/plain')
            filename = assembled_seq.name + '.xml'
            response['Content-Disposition'] = 'attachment; '
            response['Content-Disposition'] += 'filename="{0}"'.format(filename)
            return response

    return HttpResponseBadRequest('There was an error in the assembly')
 def __init__(self, request, course=None, course_instance=None, **dict):
     RequestContext.__init__(self, 
                             request, 
                             dict)
     
     # Initially the user is neither an assistant nor a teacher
     is_assistant    = False
     is_teacher      = False
     
     # If the course is not given, but an instance is, get the instance's course
     if course == None and course_instance != None:
         course = course_instance.course
     
     if request.user.is_authenticated():
         # If the user is authenticated, populate is_assistant and is_teacher fields
         profile     = request.user.get_profile()
         
         if course != None and course.is_teacher(profile):
             # Teachers are also allowed to act as assistants
             is_teacher      = True
             is_assistant    = True
         elif course_instance != None and course_instance.is_assistant(profile):
             is_assistant    = True
     
     course_info     = {"is_teacher":    is_teacher,
                        "is_assistant":  is_assistant,
                        "instance":      course_instance,
                        "course":        course,
                        }
     
     self.update(course_info)
示例#10
0
def multipartite_view_sbol(request, multi_type=None):
    'view of the multipartite tool'

    if multi_type is None:
        return render_to_response('multipartite_initial.html', {},
                                  context_instance=RequestContext(request))
    elif multi_type not in PARTS_TO_ASSEMBLE.keys():
        return Http404
    context = RequestContext(request)
    context.update(csrf(request))
    if request.method == 'POST':
        request_data = request.POST
    elif request.method == 'GET':
        request_data = request.GET
    else:
        request_data = None
    form_class = get_multipartite_form(multi_type, request.user)
    if request_data:
        form = form_class(request_data)

        if form.is_valid():
            multi_form_data = form.cleaned_data
            part_types = [p[0] for p in PARTS_TO_ASSEMBLE[multi_type]]
            assembled_seq = assemble_parts(multi_form_data, part_types)
            filename = assembled_seq.name + '.xml'
            response = HttpResponse(convert_to_sbol(assembled_seq),
                                    content_type='xml/plain')
            response['Content-Disposition'] = 'attachment; '
            response['Content-Disposition'] += 'filename="{0}"'.format(filename)
            return response
    return HttpResponseBadRequest()
示例#11
0
文件: views.py 项目: aazhbd/drpharma
def home(request):
    context = RequestContext(request)
    context.update({ 'msg_body' : "List of all machines", })
    
    products = Product.objects.all()
    context.update({ 'products' : products, })
    return render_to_response("home.html", context_instance=context)
示例#12
0
def multipartite_view(request, multi_type=None):
    if multi_type is None:
        return render_to_response('multipartite_initial.html', {},
                                  context_instance=RequestContext(request))
    elif multi_type not in PARTS_TO_ASSEMBLE.keys():
        return Http404
    context = RequestContext(request)
    context.update(csrf(request))
    if request.method == 'POST':
        request_data = request.POST
    elif request.method == 'GET':
        request_data = request.GET
    else:
        request_data = None
    form_class = get_multipartite_form(multi_type, request.user)
    if request_data:
        form = form_class(request_data)
        if form.is_valid():
            used_parts = OrderedDict()
            multi_form_data = form.cleaned_data
            for part_type in [p[0] for p in PARTS_TO_ASSEMBLE[multi_type]]:
                used_parts[part_type] = multi_form_data[part_type]
                used_parts[VECTOR_TYPE_NAME] = multi_form_data[VECTOR_TYPE_NAME]
            return render_to_response('multipartite_result.html',
                                      {'used_parts': used_parts,
                                       'multi_type': multi_type},
                                context_instance=RequestContext(request))
    else:
        form = form_class()

    context['form'] = form

    template = 'multipartite_template.html'
    content_type = None
    return render_to_response(template, context, content_type=content_type)
示例#13
0
文件: views.py 项目: bl1nd/omnomnom
def user_manage(request):
    context = RequestContext(request)
    context.update(csrf(request))
    if not request.user.is_authenticated():
        return HttpResponse("(\/)~(-_-)~(\/) Вы не туда попали (\/)~(-_-)~(\/)")
    context["device"] = device_check(request)
    return HttpResponse(get_template("manage.html").render(context))
示例#14
0
def get_placeholders(request):
    # Walk through all the templates which have a html extension
    placeholders = []
    for template_dir in settings.TEMPLATE_DIRS:
        for root, dirs, files in os.walk(template_dir):
            for file in files:
                ext = file.split(".")[-1]
                if ext == "html":
                    placeholders.append(os.path.join(root, file))

    # Update context and get current_placeholders
    context = RequestContext(request)
    context.update({'request': request,
                    'display_banner_names': True })
    current_placeholders = [(p.title) for p in Placeholder.objects.all()]

    # For every template retrieve the placeholders and add to the DB
    all_positions = set()
    for template in placeholders:
        file = open(template, 'r')
        temp_string = file.read()
        banner_re = r'{% banner (?P<title>[-\w]+).* %}'

        for match in re.finditer(banner_re, temp_string):
            title = match.group('title')
            all_positions.add(title)

            placeholder, created = Placeholder.objects.get_or_create(title=title)

    # Delete any non-existing placeholder
    removable = list(set(current_placeholders).difference(set(all_positions)))

    for placeholder in removable:
        Placeholder.objects.filter(title__iexact=placeholder).delete()
示例#15
0
def draw_chart(request):
    
    def validate_and_get_date(request):
        date_from = request.GET.get('date_from')
        date_to = request.GET.get('date_to')
        date_from = datetime.datetime.strptime(date_from, '%Y-%m-%d').date()
        date_to = datetime.datetime.strptime(date_to, '%Y-%m-%d').date()
        if date_to < date_from:
            messages.error(request, _('Invalid period entered'))
            return HttpResponseRedirect(request.META['HTTP_REFERER']), date_to, date_from
        return None, date_to, date_from
    
    group = None
    if request.GET.get('group'):
        group = request.GET.get('group')
    response, date_to, date_from = validate_and_get_date(request)
    if response:
        return response
    quality = Orderfailure.calculate_service_level(date_from, date_to, group)
    tooltip_date = "%d %b %Y %H:%M:%S %p"
    extra_series = {"tooltip": {"y_start": "", "y_end": " calls"},
                    "date_format": tooltip_date}
    chartdata = {
        'x': quality.keys(),
        'name1': _('Quality cofficient'), 'y1': quality.values(), 'extra1': extra_series
    }
    charttype = "cumulativeLineChart"
    data = {
        'charttype': charttype,
        'chartdata': chartdata,
    }
    rc = RequestContext(request, {})
    rc.autoescape = False
    res = render_to_response('graph.html', data, rc)
    return res
示例#16
0
文件: views.py 项目: menessy/eduudle
def connect(request):
    '''
    Exception and validation functionality around the _connect view
    Separated this out from _connect to preserve readability
    Don't bother reading this code, skip to _connect for the bit you're interested in :)
    '''
    facebook_login = to_bool(request.REQUEST.get('facebook_login'))
    context = RequestContext(request)

    #validation to ensure the context processor is enabled
    if not context.get('FACEBOOK_APP_ID'):
        message = 'Please specify a Facebook app id and ensure the context processor is enabled'
        raise ValueError(message)

    #hide the connect page, convenient for testing with new users in production though
    if not facebook_login and not settings.DEBUG and facebook_settings.FACEBOOK_HIDE_CONNECT_TEST:
        raise Http404('not showing the connect page')

    try:
        response = _connect(request, facebook_login)
    except open_facebook_exceptions.FacebookUnreachable, e:
        #often triggered when Facebook is slow
        warning_format = u'%s, often caused by Facebook slowdown, error %s'
        warn_message = warning_format % (type(e), e.message)
        send_warning(warn_message, e=e)
        response = error_next_redirect(request,
                                       additional_params=dict(
                                           fb_error_or_cancel=1)
                                       )
示例#17
0
def File_form(request):
    if request.method == 'GET':
        form = FileForm()
        data_for_templete = {'form' : form}
        rc = RequestContext(request, {})
        rc.autoescape = False
        return render_to_response('stock_info/fileimport.html', data_for_templete, rc)
    else:
        form = FileForm(request.POST, request.FILES)
        if form.is_valid():
            
            data = form.cleaned_data['file_name']
            try:
                results = Data_import(data)
                err_msg = []
                if results['not_found']:
                    err_msg.append(unicode(ugettext_lazy('Not found operations: %d' % results['not_found'])))
                if results['failed']:
                    err_msg.append(unicode(ugettext_lazy('Failed rows: %d' % results['failed'])))
                if len(err_msg) > 0:
                    messages.error(request, '; '.join(err_msg))
                else:
                    messages.info(request, unicode(ugettext_lazy('Success: %s rows' % results['success'])))
            except:
                messages.error(request, ugettext_lazy('Import failed'))
    return HttpResponseRedirect('/admin/stock_info/orderfailure')
示例#18
0
def render_single_to_response(request, comic, template='comics/single.html', contextDict=None):
    t = loader.get_template(template)
    c = RequestContext(request)
    thisId = comic.id
    # The out-commented alternatives should not be necessary because a webcomic should follow a strict id sequence
    firstId = 1
#    firstId = Comic.objects.order_by('dateTime')[0].id
    if firstId == thisId:
        firstId = 0
    latestId = get_published_comics().order_by('-dateTime')[0].id
    if latestId == thisId:
        latestId = 0
    prevId = 0
    if firstId:
        prevId = thisId - 1
#        prevId = Comic.objects.filter(dateTime__lt=comic.dateTime).order_by('-dateTime')[0].id
    nextId = 0
    if latestId:
        nextId = thisId + 1
#        nextId = Comic.objects.filter(datetime__gt=comic.dateTime).order_by('dateTime')[0].id
    c.update({
        'baseUrl': request.build_absolute_uri('/')[:-1],
        'comic': comic,
        'comicTemplate': 'comics/types/{0}.html'.format( comic.type.lower() ),
        'title': comic.title,
        'subtitle': comic.get_comic_obj().pageSubtitle,
        'firstId': firstId,
        'latestId': latestId,
        'prevId': prevId,
        'nextId': nextId
    })
    if contextDict:
        c.update(contextDict)
    return HttpResponse( t.render(c) )
示例#19
0
def get_placeholders(request, template=None):
    """
    Return a list of PlaceholderNode found in the given template
    """
    if not template:
        template = get_template_from_request(request)
    try:
        temp = loader.get_template(template)
    except TemplateDoesNotExist:
        return []
    user = request.user
    request.user = AnonymousUser()
    context = RequestContext(request)#details(request, no404=True, only_context=True)
    template = get_template_from_request(request)
    old_page = request.current_page
    request.current_page = "dummy"
    
    context.update({'template':template,
                    'request':request,
                    'display_placeholder_names_only': True,
                    'current_page': "dummy",
                    })
    output = temp.render(context)
    request.user = user
    placeholders = re.findall("<!-- PlaceholderNode: (.+?) -->", output)
    request.current_page = old_page
    return placeholders
示例#20
0
def get_outerobj_comment(request):
    outerobj_type = request.POST.get('outerobj_type')
    outerobj_id = request.POST.get('outerobj_id')
    comment_show_type = request.POST.get('comment_show_type', 0)
    page_num = int(request.REQUEST.get('page', 1))
    # 能否发表评论权限判断
    can_create_comment_permission = request.POST.get('can_create_comment_permission', 'True')
    can_create_comment_permission = True if can_create_comment_permission == 'True' else False
    cob = interface.CommentOperateBase()
    objs = cob.get_outerobj_comment(outerobj_type, outerobj_id)

    # 分页
    page_objs = page.Cpt(objs, count=10, page=page_num).info
    objs = page_objs[0]
    page_params = (page_objs[1], page_objs[4])
    lst_comment = format_outerobj_comment(objs, request.user)

    from www.custom_tags.templatetags.custom_filters import paging
    from www.comment.interface import get_comment_page_onclick
    paging_html = paging(page_params, request, get_page_onclick=get_comment_page_onclick,
                         page_onclick_params=dict(outerobj_type=outerobj_type, outerobj_id=outerobj_id,
                                                  comment_show_type=comment_show_type,
                                                  can_create_comment_permission=can_create_comment_permission))

    # 两种类型,一种给用于单条外部对象,一条用于可能有多条的
    tem = template.loader.get_template('comment/_comment_sub%s.html' % comment_show_type)
    context_instance = RequestContext(request)
    context_instance.update(dict(lst_comment=lst_comment, outerobj_type=outerobj_type, outerobj_id=outerobj_id,
                                 request=request, paging_html=paging_html,
                                 can_create_comment_permission=can_create_comment_permission,
                                 comment_user=request.session.get('comment_user')))

    return HttpResponse(tem.render(template.Context(context_instance, autoescape=False)))
示例#21
0
def add(request):
    """
    @attention: 发表评论
    """
    content = request.POST.get('content', '').strip()
    nick = request.POST.get('nick', '').strip()
    email = request.POST.get('email', '').strip()
    user_href = request.POST.get('user_href', '').strip()

    outerobj_type = request.POST.get('outerobj_type', 'default')
    outerobj_id = request.POST.get('outerobj_id')
    comment_show_type = request.POST.get('comment_show_type', 0)

    cob = interface.CommentOperateBase()
    flag, result = cob.add(nick, email, user_href, content, outerobj_type, outerobj_id, ip=utils.get_clientip(request))
    if flag:
        lst_comment = format_outerobj_comment([result, ], request.user)
        # 两种类型,一种给用于单条外部对象,一条用于可能有多条的
        tem = template.loader.get_template('comment/_comment_single_list%s.html' % comment_show_type)
        context_instance = RequestContext(request)
        context_instance.update(dict(c=lst_comment[0], outerobj_type=outerobj_type, outerobj_id=outerobj_id))

        # 设置留言用户session
        request.session['comment_user'] = dict(nick=nick, email=email, user_href=user_href)
        return HttpResponse(tem.render(template.Context(context_instance, autoescape=False)))
    else:
        return HttpResponse('$%s' % result)
示例#22
0
文件: views.py 项目: FOSSEE/SciPy2015
def cfp(request):
    if request.method == "POST":
        context = {}
        context.update(csrf(request))
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)
        if user is not None:
            login(request, user)
            if 'next' in request.GET:
                next = request.GET['next']
                return HttpResponseRedirect(next)
            context['user'] = user
            return render_to_response('cfp.html', context)
        else:
            context['invalid'] = True
            context['form'] = UserLoginForm
            return render_to_response('cfp.html', context)
    else:
        form = UserLoginForm()
        context = RequestContext(request, {'request': request,
                                           'user': request.user,
                                           'form': form})
        context.update(csrf(request))
        return render_to_response('cfp.html',
                             context_instance=context)
示例#23
0
文件: admin.py 项目: amaozhao/basecms
def render_admin_menu_item(request, page, template=None, language=None):
    """
    Renders requested page item for the tree. This is used in case when item
    must be reloaded over ajax.
    """
    if not template:
        template = "admin/cms/page/tree/menu_fragment.html"

    if not page.pk:
        return HttpResponse(NOT_FOUND_RESPONSE) # Not found - tree will remove item

    # languages
    from cms.utils import permissions
    languages = get_language_list(page.site_id)
    context = RequestContext(request, {
        'has_add_permission': permissions.has_page_add_permission(request),
        'site_languages': languages,
    })

    filtered = 'filtered' in request.REQUEST
    context.update(get_admin_menu_item_context(request, page, filtered, language))
    # add mimetype to help out IE
    if DJANGO_1_4:
        return render_to_response(template, context, mimetype="text/html; charset=utf-8")
    else:
        return render_to_response(template, context, content_type="text/html; charset=utf-8")
示例#24
0
文件: views.py 项目: bl1nd/omnomnom
def order_delete(request):
    context = RequestContext(request)
    context.update(csrf(request))
    if not request.user.is_authenticated:
        return HttpResponse("(\/)~(-_-)~(\/) Вы не туда попали (\/)~(-_-)~(\/)")
    if not request.method == "POST":
        return HttpResponse("(\/)~(-_-)~(\/) Вы не туда попали (\/)~(-_-)~(\/)")
    tDate = datetime.now()
    for key in request.POST:
        if key[:3] == "del" and request.POST[key] == u"on":
            try:
                value = int(key[3:])
                tOrder = Order.objects.get(id=value)
                tOrder_Log = Order_Log(
                    text="Заказ %s от %s был удалён %s в %s:%s:%s. Он содержал блюдо %s в кол-ве: %s"
                    % (
                        tOrder.customer,
                        tOrder.date.date(),
                        tDate.date(),
                        tDate.hour,
                        tDate.minute,
                        tDate.second,
                        tOrder.dish,
                        tOrder.count,
                    )
                )
                tOrder_Log.save()
                tOrder.delete()
            except:
                return HttpResponse("Error {0}: {1}".format(str(exc_info()[0]), exc_info()[1]))
    context["device"] = device_check(request)
    return HttpResponseRedirect("/order_today/")
示例#25
0
def connect(request, graph):
    '''
    Exception and validation functionality around the _connect view
    Separated this out from _connect to preserve readability
    Don't bother reading this code, skip to _connect for the bit you're interested in :)
    '''
    backend = get_registration_backend()
    context = RequestContext(request)

    # validation to ensure the context processor is enabled
    if not context.get('FACEBOOK_APP_ID'):
        message = 'Please specify a Facebook app id and ensure the context processor is enabled'
        logger.info('CO01 Please specify a Facebook app id and ensure the context processor is enabled')
        raise ValueError(message)

    try:
        response = _connect(request, graph)
    except open_facebook_exceptions.FacebookUnreachable, e:
        logger.info('CO02 Probably slow FB')
        # often triggered when Facebook is slow
        warning_format = u'%s, often caused by Facebook slowdown, error %s'
        warn_message = warning_format % (type(e), e.message)
        send_warning(warn_message, e=e)
        additional_params = dict(fb_error_or_cancel=1)
        response = backend.post_error(request, additional_params)
示例#26
0
def english_info(request):
    id = 0

    try:
        id = int(request.GET.get('id', 0))
    except Exception as e:
        log_info('english_info() errors: %s ' % str(e))

    data_dict = {}
    if not id:
        data_dict.update({'msg': ErrorCodeMsgList.INVALID_PARAMETER.message})
    else:
        item = English.get_dict_by_id(id)
        if item:
            item = format_english_dict(item, wechat=True)

        if not item:
            data_dict.update({'msg': ErrorCodeMsgList.INVALID_PARAMETER.message})
        else:
            data_dict.update(item)

    context = RequestContext(request)
    context.update(get_seo_context(request))
    context.update({'data': data_dict})
    return template_response('english/info.html', context_instance=context)
示例#27
0
def render_admin_menu_item(request, page, template=None):
    """
    Renders requested page item for the tree. This is used in case when item
    must be reloaded over ajax.
    """
    if not template:
        template = "admin/cms/page/menu_item.html"

    if not page.pk:
        return HttpResponse(NOT_FOUND_RESPONSE) # Not found - tree will remove item
        
    # languages
    languages = []
    if page.site_id in settings.CMS_SITE_LANGUAGES:
        languages = settings.CMS_SITE_LANGUAGES[page.site_id]
    else:
        languages = [x[0] for x in settings.CMS_LANGUAGES]
    
    context = RequestContext(request, {
        'has_add_permission': permissions.has_page_add_permission(request),
        'site_languages': languages,
    })
    
    filtered = 'filtered' in request.REQUEST
    context.update(get_admin_menu_item_context(request, page, filtered))
    # add mimetype to help out IE
    return render_to_response(template, context, mimetype="text/html; charset=utf-8")
    def _render_form_error(self, err_message):
        context = RequestContext(HttpRequest())
        data = {
            'message': err_message
        }

        context.update(data)
        return self.templates['form_error'].render(context)
示例#29
0
 def config(self, request, context=None):
     """配置 include 必须的参数 request_context """
     request_context = RequestContext(request, {})
     for c in self.context.dicts:
         request_context.update(c)
     if context:
         request_context.update(context)
     self.request_context = request_context
示例#30
0
文件: views.py 项目: bl1nd/omnomnom
def main(request):
    context = RequestContext(request)
    context.update(csrf(request))
    if device_check(request) == "notPC":
        context["device"] = True
    else:
        context["device"] = False
    return HttpResponse(get_template("brand.html").render(context))