Beispiel #1
0
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")
Beispiel #2
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)
Beispiel #3
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)
Beispiel #4
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)
Beispiel #5
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)
Beispiel #6
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)))
Beispiel #7
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')
Beispiel #8
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) )
Beispiel #9
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)
Beispiel #10
0
def viewChapter(request, **Args):
	context = RequestContext(request)

	chapterNum = str(Args.get('chap')).strip('/')
	cNum = int(chapterNum)
	context.update({ 'cnum' : cNum, })

	try:
		chName = Chapter.objects.get(pk=cNum)
		context.update({ 'msg_body' : "Verses of the chapter " + chapterNum + ": " + chName.transliteration + " " + chName.arabic_name + " (" + chName.english_name + ")", })
	except:
		context.update({ 'msg_body' : "Invalid chapter number", })

	v = Q(chapter=cNum) & Q(author__name='Original Text')
	full_chap = Verse.objects.filter(v).order_by('number')

	for content in full_chap:
		content.vtext = unicodedata.normalize('NFC', content.vtext)

	context.update({ 'full_chap' : full_chap, })

	auths = Verse.objects.filter(chapter=cNum).values('author').distinct()
	authors = []
	for a in auths:
		authors.append(Author.objects.get(pk=a['author']))

	context.update({ 'authors' : authors, })

	return render_to_response("chapter.html", context_instance=context)
Beispiel #11
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))
Beispiel #13
0
def viewDiscuss(request):
	context = RequestContext(request)

	comments = Comment.objects.filter(enabled=True).order_by('-date_published')
	context.update({ 'comments' : comments, })

	if request.method == "POST":
		uemail = request.POST.get('email', None).strip()
		password = request.POST.get('password', None).strip()

		try:
			user = User.objects.get(email=uemail)
		except:
			user = None

		if user is not None and user.check_password(password):
			if user.is_active:
				user.backend = 'django.contrib.auth.backends.ModelBackend'
				login(request, user)
				context.update({ 'msg_body' : "Login is successful.", })
			else:
				context.update({ 'msg_body' : "The account is currently inactive, contact administrator.", })
		else:
			context.update({ 'msg_body' : "The username and password were incorrect.", })
			return render_to_response("login.html", context_instance=context)

	context.update({ 'msg_body' : "Recent Discussions", })
	return render_to_response("discuss.html", context_instance=context)
Beispiel #14
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
Beispiel #15
0
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))
Beispiel #16
0
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)
Beispiel #17
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()
Beispiel #18
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()
Beispiel #19
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")
Beispiel #20
0
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)
Beispiel #21
0
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))
Beispiel #22
0
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/")
    def _render_form_error(self, err_message):
        context = RequestContext(HttpRequest())
        data = {
            'message': err_message
        }

        context.update(data)
        return self.templates['form_error'].render(context)
Beispiel #24
0
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))
Beispiel #25
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
Beispiel #26
0
def home(request):
    context = RequestContext(request)
    context.update({ 'msg_body' : "All Chapters", })
    
    chapters = Chapter.objects.all()
    
    context.update({ 'chapters' : chapters, })
    
    return render_to_response("home.html", context_instance=context)
Beispiel #27
0
def index(request):
   template_values = {}
   current_user = ''  ##### find current user
   context = RequestContext(request, template_values)
   context.update({'page_name': 'Landing Page',
                   'user': current_user
                   })

   return render_to_response('index.html', context)
 def as_csv(self, request):
     template = get_template(self.template_csv)
     context = RequestContext(request, {"table": self})
     context.update(request.extra_context)
     self.context = context
     param_report = generate_prefixto_report(self)
     return template.render(RequestContext(request,
                            {'table': self,
                             'param_report': param_report}))
Beispiel #29
0
def landing_page(request):
    t = loader.get_template('landing-page.html')
    c = RequestContext(request, {
        'form': RecordForm(),
        'success': False,
    })
    c.update(csrf(request))
    
    return HttpResponse(t.render(c))
Beispiel #30
0
def viewSearch(request, **Args):
	context = RequestContext(request)
	try:
		search = request.POST.get('search', Args.get('search'))
	except:
		search = ""

	if search == None:
		search = ""
	search = search.strip()

	try:
		page = str(Args.get('page', 1)).strip('/')
	except:
		page = 1

	pageNum = int(page)
	pageSize = 40
	titleresult = []
	verseresult = []
	commentresult = []

	if search and search != "":
		titlesearch = Q(english_name__icontains=search) | Q(arabic_name__icontains=search) | Q(transliteration__icontains=search)
		versesearch = Q(vtext__icontains=search)
		commentsearch = Q(ctext_icontains=search)
		try:
			titleresult = Paginator(Chapter.objects.filter(titlesearch), pageSize).page(pageNum)
		except:
			titleresult = []

		try:
			verseresult = Paginator(Verse.objects.filter(versesearch), pageSize).page(pageNum)
		except:
			verseresult = []

		try:
			commentresult = Paginator(Comment.objects.filter(commentsearch), pageSize).page(pageNum)
		except:
			commentresult = []

	totalentries = sum(getattr(x, 'paginator', Paginator([], 0)).count for x in [titleresult, verseresult, commentresult])
	totalpages = int(totalentries / pageSize)

	context.update({
		'titleresult' : titleresult,
		'verseresult' : verseresult,
		'commentresult' : commentresult,
		'searchkey' : search,
		'pageNum' : pageNum,
		'pageSize': pageSize,
		'totalresult' : totalentries,
		'totalpages' : totalpages
	})

	return render_to_response("search.html", context_instance=context)
Beispiel #31
0
def login_view(request):
    """
    Standard Django login, with additions:
        Lowercase the login email (username)
        Check user has accepted ToS, if any.
    """
    if request.method == "POST":
        redirect_to = request.REQUEST.get('next', False)
        if not redirect_to:
            redirect_to = reverse('seed:home')

        form = LoginForm(request.POST)
        if form.is_valid():
            new_user = authenticate(
                username=form.cleaned_data['email'].lower(),
                password=form.cleaned_data['password']
            )
            if new_user and new_user.is_active:
                # determine if user has accepted ToS, if one exists
                try:
                    user_accepted_tos = has_user_agreed_latest_tos(new_user)
                except NoActiveTermsOfService:
                    # there's no active ToS, skip interstitial
                    user_accepted_tos = True

                if user_accepted_tos:
                    login(request, new_user)
                    return HttpResponseRedirect(redirect_to)
                else:
                    # store login info for django-tos to handle
                    request.session['tos_user'] = new_user.pk
                    request.session['tos_backend'] = new_user.backend
                    context = RequestContext(request)
                    context.update({
                        'next': redirect_to,
                        'tos': TermsOfService.objects.get_current_tos()
                    })
                    return render_to_response(
                        'tos/tos_check.html',
                        context_instance=context
                    )
            else:
                errors = ErrorList()
                errors = form._errors.setdefault(NON_FIELD_ERRORS, errors)
                errors.append('Username and/or password were invalid.')
    else:
        form = LoginForm()
    return render_to_response(
        'landing/login.html',
        locals(),
        context_instance=RequestContext(request),
    )
Beispiel #32
0
    def get(self, request, uuid):
        # Mark the email associated with uuid as confirmed.
        ac = AddressConfirmation.objects.get(uuid=uuid)
        ac.confirmation_timestamp = datetime.now()
        ac.save()
        # Send any emails to this address which are waiting.
        send_queued_emails(ac)

        # Provide a page to thank the user for confirming.
        rc = RequestContext(request)
        rc.update({'email_address': ac.address})
        resp = render(request, self.template_name, rc)
        return resp
Beispiel #33
0
 def widget(self):
     context = {
         'widget_id': self.id,
         'widget_title': self.title,
         'widget_icon': self.widget_icon,
         'widget_type': self.widget_type,
         'form': self,
         'widget': self
     }
     self.context(context)
     _context = RequestContext(self.request)
     _context.update(context)
     return loader.render_to_string(self.template,
                                    context_instance=_context)
Beispiel #34
0
def edit_codificator(request, code):
    context = RequestContext(request)
    codificator = get_object_or_404(Codificator, code=code)
    context.update({'codificator': codificator})

    if request.method == 'POST':
        codificator.code = request.POST.get('code')
        codificator.description = request.POST.get('description')
        codificator.save()
        messages.info(request, u'El codificador ha sido actualizado.')
        return HttpResponseRedirect(
            reverse('cad.views.list_codificators', urlconf='cad.urls'))

    return TemplateResponse(request, 'cod/cod_edit.html', context)
Beispiel #35
0
def category_object_list(request, category, extra_context=None):

    context = RequestContext(request)

    if extra_context != None:
        context.update(extra_context)

    latest = Entry.objects.filter(category__slug=category)

    context.update({
        'latest': latest,
    })

    return render_to_response('news/entry_archive.html', context)
Beispiel #36
0
def htmlify(request):
    context = RequestContext(request)
    if request.method == 'GET':
        form = HtmlifyForm()
    elif request.method == 'POST':
        form = HtmlifyForm(request.POST)  # A form bound to the POST data
        if form.is_valid():  # All validation rules pass
            original_code = form.cleaned_data['code']
            encoding = form.cleaned_data['encoding']
            html_code = htmlify_code(original_code, encoding)
            context.update({'htmlified': html_code,
                            'to_htmlify': original_code})
    context.update({'form': form})
    return render_to_response('htmlify.html', context)
Beispiel #37
0
def pools(request):
    context = RequestContext(request)

    try:
        res = client.command('pools')
        context.update({ 'pool_list': res['POOLS'] })
        now = res['STATUS'][0]['When']
        for pool in context['pool_list']:
            last = pool['Last Share Time']
            if now-last < ACTIVE_STATUS_SECONDS:
                pool['status'] = 'active'
            elif now-last < STALE_STATUS_SECONDS:
                pool['status'] = 'stale'
    except Exception, e:
        context.update({ 'offline': True })
Beispiel #38
0
 def deletion_not_allowed(self, request, obj, language_code):
     opts = self.model._meta
     app_label = opts.app_label
     object_name = force_text(opts.verbose_name)
     
     context = RequestContext(request)
     context.update({
         'object': obj.master,
         'language_code': language_code,
         'opts': opts,
         'app_label': app_label,
         'language_name': get_language_name(language_code),
         'object_name': object_name,
     })
     return render_to_response(self.deletion_not_allowed_template, context)
Beispiel #39
0
    def _load_template(self, tpl_key, tpl_data=None):
        context = RequestContext(HttpRequest())

        if tpl_key not in self.templates.keys():
            raise IndexError('Template "' + tpl_key +
                             '" not found in registered templates ' +
                             str(self.templates.keys()))

        if tpl_data is not None and type(tpl_data) != dict:
            raise TypeError('Data parameter should be a dict (' +
                            str(type(tpl_data)) + ' given)')

        if tpl_data is not None:
            context.update(tpl_data)

        return self.templates[tpl_key].render(context)
Beispiel #40
0
def new_experiment(request):
    '''experiments = Experiment.objects.all().order_by('-startdate')[:5]
    tasks = Task.objects.all().order_by('-startdate')[:5]
    reagents = Reagent.objects.all().order_by('-createdate')[:5]
    plates = Plate.objects.all().order_by('-timestamp')[:5]'''
    is_valid = False
    is_post = False
    exp_id = 0
    view_url = '/new_experiment/'
    upload_url, upload_data = prepare_upload(request, view_url)
    if request.method=='POST':
        is_post = True
        form = ExperimentForm (request.POST, request.FILES) #bound form to project
        form.fields["liquidClass"].queryset = LiquidClass.objects.all().order_by('name')
        if form.is_valid():
            is_valid = True
            f=form.save(commit= False)
            f.user = request.user
            f=form.save(commit= True)
            exp = Experiment.objects.get(pk= f.id)
            exp_id = exp.id
           # uploadFileFromWebClient(request,exp,AMAZONE_URL,'manualFile')
            _man = f.manualFile.file.file
            _rob = f.robotFile.file.file
            dilsList,pipetorsCV ,dilsListForLineChart= compareManualToRobotReaderForWebApp(manualExcelFile= _man,robotExcelFile=_rob, experiment=exp)
            exp.grade = getAverageCV(pipetorsCV)
            exp.means = exp.getMeans()
            exp.distance = exp.getDistance()
            exp.save()
            distance = abs(exp.getMeans()-exp.volume)
            c = RequestContext(request,{'exp':exp,'exp_id':exp_id,'form':form,'messege':'New experiment submitted successfully','pipetorsCV':pipetorsCV,'dilsList':dilsList,'dilsListForLineChart':dilsListForLineChart,   'upload_url':upload_url,
                                        'upload_data':upload_data,'comesFromNewExperiment':True,'distance':distance})
            c.update(csrf(request))
            return render_to_response('experiment_page.html',c)
            #return HttpResponseRedirect('experiment_page.html',c)
    else:
        form = ExperimentForm()
        form.fields["liquidClass"].queryset = LiquidClass.objects.all().order_by('name')
        return direct_to_template(request, 'new_experiment.html',
            { 'form':form,
              'is_valid':is_valid,
              'is_post':is_post,
              'exp_id':exp_id,
              'upload_url':upload_url,
              'upload_data':upload_data,
              })
Beispiel #41
0
    def _load_template(self, tpl_key, tpl_data=None):
        """ Instantiate a preloaded template

        Parameters:
            tpl_key:
            tpl_data:

        Returns:
        """
        add_context = {}
        context = RequestContext(HttpRequest())

        if tpl_data is not None:
            add_context.update(tpl_data)
            context.update(add_context)

        return self.templates[tpl_key].render(context)
Beispiel #42
0
def error_page(request,error_id):
    '''edit the error within the script'''
    error = RobotScriptError.objects.get(pk = error_id)
    form = RobotScriptErrorForm (instance=error)#a bound form to the error to edit.
    form.fields['robotscript'].widget = django.forms.widgets.HiddenInput()
    script = error.robotscript
    errorstable = getErrorsTable(script= script)
    if errorstable.willHandle(request):
        return errorstable.handleRequest(request)
    if request.method=='POST':
        form = RobotScriptErrorForm (request.POST,instance=error) #bound form to script
        f=form.save()
        c = RequestContext(request,{'form':form,'script':script})
        c.update(csrf(request))
        view_url= '/robot_scripts_page/'+str(script.id)
        return HttpResponseRedirect(view_url)
    return render_to_response("script_page.html", context_instance=RequestContext(request,{'errorstable':errorstable,'script':script,'form':form}))
Beispiel #43
0
def render_admin_menu_item(request, page):
    """Renders requested page item for the tree. This is used in case when item
    must be reloaded over ajax.
    """

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

    context = RequestContext(
        request, {
            'has_add_permission': has_page_add_permission(request),
        })

    filtered = 'filtered' in request.REQUEST
    context.update(get_admin_menu_item_context(request, page, filtered))
    return render_to_response('admin/cms/page/menu_item.html', context)
Beispiel #44
0
    def buildEditContext(self, data, extra=None):
        x = RequestContext(self.request)
        x.update(data)
        x.update({'postaction': '#'})
        if extra is not None:
            x.update(extra)
        if 'debug' in self.request.REQUEST:
            x.update({'debug': 1})

        return x
Beispiel #45
0
def retrieve_download(request, download_id, template="soil/file_download.html", extra_context=None):
    """
    Retrieve a download that's waiting to be generated. If it is the get_file, 
    then download it, else, let the ajax on the page poll.
    """
    context = RequestContext(request)
    if extra_context:
        context.update(extra_context)
    context['download_id'] = download_id

    if 'get_file' in request.GET:
        download = DownloadBase.get(download_id)
        if download is None:
            logging.error("Download file request for expired/nonexistent file requested")
            raise Http404
        return download.toHttpResponse()

    return render_to_response(template, context=context.flatten())
Beispiel #46
0
def show_equip_info(request, codequipo):
    context = RequestContext(request)
    equip = Equip.objects.get(codequipo=codequipo)
    context.update({'equip': equip})

    schema_list = SchemaImageDraw.objects.filter(model=equip.codmodelo)
    paginator = Paginator(schema_list, 6)
    page = request.GET.get('page')

    try:
        schemas = paginator.page(page)
    except PageNotAnInteger:
        schemas = paginator.page(1)
    except EmptyPage:
        schemas = paginator.page(paginator.num_pages)

    context.update({'schemas': schemas})
    return TemplateResponse(request, 'equips/equips_details_info.html',
                            context)
Beispiel #47
0
 def widget(self):
     '''
     关键方法:输出内容,类似render
     '''
     context = {
         'widget_id': self.id,
         'widget_title': self.title,
         'widget_icon': self.widget_icon,
         'widget_type': self.widget_type,
         'form': self,
         'widget': self
     }
     self.context(context)
     _context = RequestContext(self.request)
     _context.update(context)
     _context[
         'box_tpl'] = self.admin_site.ext_ui and 'xadmin/includes/box_ext.html' or 'xadmin/includes/box.html'
     return dutils.render_to_string(self.template,
                                    context_instance=_context)
Beispiel #48
0
def add(request):
    context = RequestContext(request)

    if request.POST:
        form = AddPool(request.POST)

        if form.is_valid():
            cd = form.cleaned_data
            res = client.command('addpool', cd.get('url'), cd.get('user'), cd.get('password'))
            if mm(request, res):
                client.command('save')
                return redirect('pools_list')

    else:
        form = AddPool()

    context.update({'form': form})

    return render_to_response('pools/pool_form.html', context,)
Beispiel #49
0
def show_draw_versions(request, name):
    context = RequestContext(request)
    context.update({'draw':
                    Draw.objects.get(name=name)})  # TODO: Get object or 404

    # Get all dwgs from selected draw ordered by date.
    dwg_list = Draw.objects.get(name=name).dwg_set.all().order_by('-date')
    paginator = Paginator(dwg_list, 6)
    page = request.GET.get('page')

    try:
        dwgs = paginator.page(page)
    except PageNotAnInteger:
        dwgs = paginator.page(1)
    except EmptyPage:
        dwgs = paginator.page(paginator.num_pages)

    context.update({'dwgs': dwgs})
    return TemplateResponse(request, 'cad/cad_details_versions.html', context)
Beispiel #50
0
def list_draws_public(request):
    context = RequestContext(request)

    draw_list = Draw.objects.all()  # Get all draws.
    inbox_count = Dwg.objects.filter(public=False).count()
    context.update({'inbox_count': inbox_count})

    if 'q' in request.GET:
        # Apply the filter if a query has been made.
        query_string = request.GET.get('q')
        draw_list = Draw.objects.filter(name__icontains=query_string)
        context.update({'query': query_string})

    # Set pagination.
    paginator = Paginator(draw_list, settings.ITEMS_PER_PAGE)
    page = request.GET.get('page')

    try:
        draws = paginator.page(page)
    except PageNotAnInteger:
        draws = paginator.page(1)
    except EmptyPage:
        draws = paginator.page(paginator.num_pages)

    context.update({'draws': draws})

    return TemplateResponse(request, 'cad/cad_list_public.html', context)
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/tree/menu_fragment.html"

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

    # languages
    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))
    # add mimetype to help out IE
    return render_to_response(template, context, mimetype="text/html; charset=utf-8")
Beispiel #52
0
def get_placeholders(request, template_name):
    """
    Return a list of PlaceholderNode found in the given template
    """
    try:
        temp = loader.get_template(template_name)
    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)
    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
    return re.findall("<!-- PlaceholderNode: (.+?) -->", output)
Beispiel #53
0
def new_plateplastica(request):
    is_valid = False
    is_post = False
    plate_id = 0
    descriptions = None
    if request.method=='POST':
        is_post = True
        form = PlatePlasticaForm (request.POST, request.FILES) #bound form to project
        if form.is_valid():
            descriptions = PlatePlastica.objects.filter(description = form.cleaned_data['description'])
            if not len(descriptions):
                form.save(commit = True)
            return HttpResponseRedirect('/')
    else:
        form = PlatePlasticaForm()
        c = RequestContext(request,{
            'form':form,
            'is_valid':is_valid,
            'is_post':is_post,
            })
        c.update(csrf(request))
        return render_to_response('new_plate_plastica.html',context_instance=c)
Beispiel #54
0
def user_login(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)
            else:
                pass
            context['user'] = user
            ws = Workshop.objects.all().order_by("date_modified").reverse()
            for w in ws:
                tags = str(w.tag)
            try:
                tag_list = w.tag.split(",")
                w.tag = tag_list
            except:
                pass
            context['ws'] = ws
            return render_to_response('table.html', context)
        else:
            context['invalid'] = True
            context['form'] = UserLoginForm
            context['user'] = user
            return render_to_response('login.html', context)
    else:
        form = UserLoginForm()
        context = RequestContext(request, {
            'request': request,
            'user': request.user,
            'form': form
        })
        context.update(csrf(request))
        return render_to_response('login.html', context_instance=context)
Beispiel #55
0
def profile(request, extra_context=None):
    '''renders user profile page'''
    try:
        token = Token.objects.get_or_create(user=request.user)
    except Token.DoesNotExist:
        logging.debug('Exception while creating tokens')
        pass

    request_context = RequestContext(request)
    request_context.push({"api_key": token})

    if extra_context is not None:
        request_context.update(extra_context)

    group_list = request.user.groups.values_list('name', flat=True)
    print(group_list)

    request_context.push({"groups": group_list})

    return render(request,
                  'registration/profile.html',
                  context_instance=request_context)
Beispiel #56
0
def render_admin_menu_item(request, page):
    """
    Renders requested page item for the tree. This is used in case when item
    must be reloaded over ajax.
    """
    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))
    return render_to_response('admin/cms/page/menu_item.html', context)
Beispiel #57
0
def script_page(request,script_id):
    script = RobotScript.objects.get(pk=script_id)
    error = RobotScriptError(robotscript = script)
    form = RobotScriptErrorForm (instance=error)
    form.fields['robotscript'].widget = django.forms.widgets.HiddenInput()
    errorstable = getErrorsTable(script= script)
    if errorstable.willHandle(request):
        return errorstable.handleRequest(request)
    if request.method=='POST':
        is_post = True
        form = RobotScriptErrorForm (request.POST,instance=error) #bound form to script
        if form.is_valid():
            is_valid = True
            f=form.save(commit= False)
            f.robotScript = script
            f=form.save(commit= True)
            form.fields['robotscript'].widget = django.forms.widgets.HiddenInput()
            c = RequestContext(request,{'form':form,'errorstable':errorstable,'script':script})
            c.update(csrf(request))
        view_url= '/robot_scripts_page/'+str(script_id)
        return HttpResponseRedirect(view_url)
        #return render_to_response('script_page.html',c)
    return render_to_response("script_page.html", context_instance=RequestContext(request,{'errorstable':errorstable,'script':script,'form':form}))
Beispiel #58
0
def list_draws_inbox(request):
    context = RequestContext(request)

    dwg_list = Dwg.objects.filter(public=False).order_by('filename')

    if 'q' in request.GET:
        # Apply the filter if a query has been made.
        query_string = request.GET.get('q')
        dwg_list = dwg_list.filter(filename__icontains=query_string)
        context.update({'query': query_string})

    # Set pagination.
    paginator = Paginator(dwg_list, settings.ITEMS_PER_PAGE)
    page = request.GET.get('page')

    try:
        dwgs = paginator.page(page)
    except PageNotAnInteger:
        dwgs = paginator.page(1)
    except EmptyPage:
        dwgs = paginator.page(paginator.num_pages)

    context.update({'dwgs': dwgs})
    return TemplateResponse(request, 'cad/cad_list_inbox.html', context)
Beispiel #59
0
def list_equips(request):
    context = RequestContext(request)

    if 'q' in request.GET:
        # Apply the filter if a query has been made.
        query_string = request.GET.get('q')
        equips_list = Equip.objects.filter(
            Q(codequipo__icontains=query_string)
            | Q(codmodelo__icontains=query_string))
        # FIXME: Due to a problem with codequipo all entries that contains
        # a forward slash should be removed from the QuerySet.
        equips_list = equips_list.exclude(codequipo__icontains='/')
        context.update({'query': query_string})
    else:
        equips_list = Equip.objects.all()

    # Pagination
    paginator = Paginator(equips_list, settings.ITEMS_PER_PAGE)
    page = request.GET.get('page')

    try:
        equips = paginator.page(page)
    except PageNotAnInteger:
        equips = paginator.page(1)
    except EmptyPage:
        equips = paginator.page(paginator.num_pages)

    # Check if equips contain schemas.
    for equip in equips:
        if SchemaImageDraw.objects.filter(model=equip.codmodelo).count() == 0:
            equip.has_schemas = False
        else:
            equip.has_schemas = True

    context.update({'equips': equips})
    return TemplateResponse(request, 'equips/equips_list.html', context)
Beispiel #60
0
    def done(self, form_list, **kwargs):
        cleaned_data = [form.cleaned_data for form in form_list]
        ontologies = cleaned_data[0].get('ontologies')
        graphs = cleaned_data[1].get('classification_graphs')
        selected_feature_ids = cleaned_data[2].get('features')
        metric = str(cleaned_data[3].get('metric'))
        linkage = str(cleaned_data[3].get('linkage'))

        # Get selected features
        features = []
        for f_id in selected_feature_ids:
            features.append(self.features[int(f_id)])

        # Create binary matrix
        bin_matrix = nparray(create_binary_matrix(graphs, features))
        # Calculate the distance matrix
        dst_matrix = dist.pdist(bin_matrix, metric)
        # The distance matrix now has no redundancies, but we need the square form
        dst_matrix = dist.squareform(dst_matrix)
        # Calculate linkage matrix
        linkage_matrix = hier.linkage(bin_matrix, linkage, metric)
        # Obtain the clustering dendrogram data
        graph_names = [g.name for g in graphs]
        dendrogram = hier.dendrogram(linkage_matrix,
                                     no_plot=True,
                                     count_sort=True,
                                     labels=graph_names)

        # Create a binary_matrix with graphs attached for display
        num_graphs = len(graphs)
        display_bin_matrix = []
        for i in range(num_graphs):
            display_bin_matrix.append({
                'graph': graphs[i],
                'feature': bin_matrix[i]
            })

        # Create dst_matrix with graphs attached
        display_dst_matrix = []
        for i in range(num_graphs):
            display_dst_matrix.append({
                'graph': graphs[i],
                'distances': dst_matrix[i]
            })

        # Create a JSON version of the dendrogram to make it
        # available to the client.
        dendrogram_json = json.dumps(dendrogram)

        # Get the default request context and add custom data
        context = RequestContext(self.request)
        context.update({
            'ontologies': ontologies,
            'graphs': graphs,
            'features': features,
            'bin_matrix': display_bin_matrix,
            'metric': metric,
            'dst_matrix': display_dst_matrix,
            'dendrogram_json': dendrogram_json
        })

        return render_to_response('catmaid/clustering/display.html', context)