Example #1
1
def datasourceInventory(request, hostname, resource_name):
    server_info = read_server_info(hostname)
    if server_info:
        selected_datasource = None
        for datasource in server_info["datasources"]:
            if datasource["name"] == resource_name:
                selected_datasource = datasource
                break
        convert_keys_names(selected_datasource)
        return render_to_response(
            "platforms/weblogic/datasource.html",
            {
                "base_url": settings.BASE_URL,
                "static_url": settings.STATIC_URL,
                "hostname": hostname,
                "datasource": datasource,
            },
            context_instance=RequestContext(request),
        )
    else:
        return render_to_response(
            "platforms/weblogic/datasource.html",
            {"base_url": settings.BASE_URL, "static_url": settings.STATIC_URL, "hostname": hostname},
            context_instance=RequestContext(request),
        )
Example #2
1
def register(request):
    context = RequestContext(request)
    context.update(csrf(request))

    if request.method == "GET":
        form = forms.RegisterForm()
        return render_to_response("register.html", {"form": form}, context_instance=context)
    elif request.method == "POST":
        form = forms.RegisterForm(request.POST)
        if form.is_valid():
            name = form.cleaned_data["username"]
            pword = form.cleaned_data["password"]
            email = form.cleaned_data["email"]

            try:
                user = User.objects.get(username__exact=name)
            except User.DoesNotExist:
                user = User.objects.create_user(name, email, pword)
            else:
                return render_to_response(
                    "register.html",
                    {"form": form, "error_message": "User %s already exists." % name},
                    context_instance=context,
                )

            d = {
                "info_message": "Thanks for registering. You can now use your name [%s] and password to sign in."
                % user.username
            }
            return render_to_response("reg_success.html", d, context_instance=context)
        else:
            return render_to_response("register.html", {"form": form}, context_instance=context)
Example #3
1
def change_list(request, app_label, model_name):
    model = models.get_model(app_label, model_name)
    if model is None:
        raise Http404("App %r, model %r, not found" % (app_label, model_name))
    if not request.user.contains_permission(app_label + "." + model._meta.get_change_permission(), model):
        raise PermissionDenied
    try:
        cl = ChangeList(request, model)
    except IncorrectLookupParameters:
        # Wacky lookup parameters were given, so redirect to the main
        # changelist page, without parameters, and pass an 'invalid=1'
        # parameter via the query string. If wacky parameters were given and
        # the 'invalid=1' parameter was already in the query string, something
        # is screwed up with the database, so display an error page.
        if ERROR_FLAG in request.GET.keys():
            return render_to_response("admin/invalid_setup.html", {"title": _("Database error")})
        return HttpResponseRedirect(request.path + "?" + ERROR_FLAG + "=1")
    c = template.RequestContext(request, {"title": cl.title, "is_popup": cl.is_popup, "cl": cl})
    c.update({"has_add_permission": c["perms"][app_label][cl.opts.get_add_permission()]}),
    return render_to_response(
        [
            "admin/%s/%s/change_list.html" % (app_label, cl.opts.object_name.lower()),
            "admin/%s/change_list.html" % app_label,
            "admin/change_list.html",
        ],
        context_instance=c,
    )
Example #4
1
def edit_field(req, form_id, field_id):
    xform = XForm.on_site.get(pk=form_id)
    field = XFormField.objects.get(pk=field_id)
    if req.method == "POST":
        form = FieldForm(req.POST, instance=field)
        form.updateTypes()

        if form.is_valid():
            field = form.save(commit=False)
            field.xform = xform
            field.save()
            return render_to_response(
                "xforms/field_view.html",
                {"form": form, "xform": xform, "field": field},
                context_instance=RequestContext(req),
            )
        else:
            return render_to_response(
                "xforms/field_edit.html",
                {"form": form, "xform": xform, "field": field},
                context_instance=RequestContext(req),
            )
    else:
        form = FieldForm(instance=field)
        form.updateTypes()

    return render_to_response(
        "xforms/field_edit.html", {"form": form, "xform": xform, "field": field}, context_instance=RequestContext(req)
    )
Example #5
1
def index(request):
    if request.method == "GET":
        return render_to_response(
            "index.html",
            {"error": False, "token_field_name": TOKEN_FIELD_NAME},
            context_instance=RequestContext(request),
        )
    else:
        formkey = urlparser.get_formkey(request.POST["formurl"])

        if not formkey:
            return render_to_response(
                "index.html",
                {"error": True, "formurl": request.POST["formurl"], "token_field_name": TOKEN_FIELD_NAME},
                context_instance=RequestContext(request),
            )

        form = Form(formkey=formkey)
        form.fill_entry_id()
        if not form.entry_id:
            return render_to_response(
                "index.html",
                {"error": True, "formurl": request.POST["formurl"], "token_field_name": TOKEN_FIELD_NAME},
                context_instance=RequestContext(request),
            )

        form.save()

        return render_to_response("created.html", {"form": form})
Example #6
1
def new_clause(request):
    context = RequestContext(request)
    if request.method == "GET":
        sectionlist = getsections()
        return render_to_response("new_clause.html", {"sectionlist": sectionlist, "error": ""}, context)

    if request.method == "POST":
        form = forms.ClauseForm(request.POST)
        if form.is_valid():
            section = request.POST.get("section")
            section = request.POST.get("newsection") if section == "" else section
            enddate = request.POST.get("enddate")
            card = request.POST.get("card")
            clause = newclause(
                creater=request.user,
                description=request.POST.get("description"),
                startdate=date.today(),
                enddate=enddate,
                section=section,
                card=card,
            )
            newrecord(user=request.user, cid=clause.id, operation="更新")
            print "inserted!"
            return HttpResponseRedirect("/country/law/")
        else:
            print "not a valid form"
            clauselist = getclauses()
            return render_to_response(
                "law.html", {"error": "Clause addition failed", "clauselist": clauselist}, context
            )
Example #7
1
def simple_login(request):
    if request.method == "POST":
        form = LoginForm(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)
                    patient = user.get_profile()
                    messages.success(request, _("You have logged in successfully."))
                    return HttpResponseRedirect(reverse("home"))
                else:
                    messages.error(request, _("Your account is inactive so you may not log in."))
                    return render_to_response("accounts/login.html", {"form": form}, RequestContext(request))
            else:
                messages.error(request, _("Invalid username or password."))
                return render_to_response("accounts/login.html", {"form": form}, RequestContext(request))

        else:
            return render_to_response("accounts/login.html", RequestContext(request, {"form": form}))
    # this is a GET
    return render_to_response("accounts/login.html", {"form": LoginForm()}, context_instance=RequestContext(request))
Example #8
0
def logout(request, next_page="/", redirect_field_name=REDIRECT_FIELD_NAME, template="idp/logout.html"):
    global __logout_redirection_timeout
    "Logs out the user and displays 'You are logged out' message."
    do_local = "local" in request.REQUEST
    context = RequestContext(request)
    context["redir_timeout"] = __logout_redirection_timeout
    next_page = request.REQUEST.get(redirect_field_name, next_page)
    if not do_local:
        l = logout_list(request)
        if l:
            # Full logout
            ok_icon_url = "%s/authentic2/images/ok.png" % settings.STATIC_URL
            next_is_ok = "?local=ok&next=%s" % urllib.quote(ok_icon_url)
            code = "<div>"
            code += _("Local logout...")
            code += (
                '<iframe src="/logout/%s" marginwidth="0" marginheight="0" \
                scrolling="no" style="border: none" width="16" height="16"> \
                </iframe></div>'
                % next_is_ok
            )
            l += [code]
            context["logout_list"] = l
            logger.debug("logout: %r" % unicode(context["logout_list"]))
            context["next_page"] = next_page
            context["message"] = _("Logging out from all your services")
            return render_to_response(template, context_instance=context)
    # Local logout
    auth_logout(request)
    context["next_page"] = next_page
    context["message"] = _("Logged out")
    return render_to_response(template, context_instance=context)
Example #9
0
def status(request, stat_id, msg=""):
    stat = libstatuses.get_status(stat_id)
    if stat == None:
        return HttpResponse("404")
    comments = libstatuses.get_comments(stat)
    contact = libstatuses.get_contact(stat.contact.id)

    re_img = re.compile(r"\[img\](.*?)\[\/img\]", re.I | re.S)
    re_url = re.compile(r"\[url=(.*?)\](.*?)\[\/url\]", re.I | re.S)
    for comment in comments:
        comment.text = re.sub(r">", "&gt;", re.sub(r"<", "&lt;", comment.text))
        comment.text = re.sub(
            re_url, r'<a href="\1">\2</a>', re.sub(re_img, r'<img src="\1">', comment.text)
        )  # obtaining string with html-like links and images
        comment.text = re.sub("\n", "<br>", comment.text)
    if is_mobile_browser(request):
        return render_to_response(
            "robot/status_mobile.html",
            {"status": stat, "comments": comments, "stat_id": stat_id, "contact": contact, "msg": msg},
        )
    else:
        return render_to_response(
            "robot/status.html",
            {"status": stat, "comments": comments, "stat_id": stat_id, "contact": contact, "msg": msg},
        )
Example #10
0
def pay(tokenId, callerReference):
    logging.info("Sending PAY request...")
    response = fps_client.pay(sender_token=tokenId, amount=price, caller_reference=callerReference)

    logging.info("response: %s", dir(response))

    transactionId = response.payResult.transactionId
    transactionStatus = response.payResult.transactionStatus
    requestId = response.responseMetadata.requestId
    logging.info("Got transaction ID: %s", transactionId)
    logging.info("Got transaction status: %s", transactionStatus)
    logging.info("Got request ID: %s", requestId)

    query = models.AmazonFps.all()
    query.filter("callerReference =", callerReference)
    entry = query.get()
    if entry is not None:
        entry.transactionId = transactionId
        entry.requestId = requestId
        entry.put()
        logging.info("Updated Amazon FPS payment data")
    else:
        logging.error("No matching caller reference in the database for: %s", callerReference)

    context = {"tabId": "thirdTab", "tabJavaScriptClass": "AboutTab"}

    if transactionStatus == "Success":
        context.update({"amazonFpsSuccessSelected": True})
        return render_to_response("aboutTab.html", context)
    elif transactionStatus == "Pending":
        context.update({"amazonFpsPendingSelected": True})
        return render_to_response("aboutTab.html", context)
    else:
        context.update({"amazonFpsFailedSelected": True})
        return render_to_response("aboutTab.html", context)
Example #11
0
def school(request, internalName):
    user = request.user
    posts = Post.objects.filter(school=School.objects.get(internalName=internalName))

    if request.method == "POST":
        postForm = PostForm(request.POST)
        if postForm.is_valid():
            post = Post(
                title=postForm.cleaned_data["title"],
                user=user,
                school=user.get_profile().school,
                seekingFemale=postForm.cleaned_data["seekingFemale"],
                seekingMale=postForm.cleaned_data["seekingMale"],
                seekingTransgendered=postForm.cleaned_data["seekingTransgendered"],
                type=postForm.cleaned_data["hookupType"],
                allowOtherSchools=postForm.cleaned_data["allowOtherSchools"],
                text=postForm.cleaned_data["text"],
            )
            post.save()
            return HttpResponseRedirect("")
        else:
            return render_to_response(
                "schools/school.html",
                {"posts": posts, "postForm": postForm, "user": user, "loginform": AuthenticationForm, "logoSize": 50},
                context_instance=RequestContext(request),
            )
    else:
        return render_to_response(
            "schools/school.html",
            {"posts": posts, "postForm": PostForm(), "user": user, "loginform": AuthenticationForm, "logoSize": 50},
            context_instance=RequestContext(request),
        )
Example #12
0
def main(request):

    if request.user.is_authenticated():
        player = Player.objects.get(pk=request.user.username)
        return render_to_response("main.html", {"player": player, "leaderboard": getLeaderboard()})

    return render_to_response("main.html", {"leaderboard": getLeaderboard()})
Example #13
0
def _send_invitation(request, project, invite_form, override_auth):
    """ The logged in project leader OR administrator wants to invite somebody.
    """
    form = invite_form(request.POST or None)
    if request.method == "POST":
        if form.is_valid():

            email = form.cleaned_data["email"]
            applicant, existing_person = get_applicant_from_email(email)

            if existing_person and not "existing" in request.POST:
                return render_to_response(
                    "applications/project_common_invite_existing.html",
                    {"form": form, "person": applicant},
                    context_instance=RequestContext(request),
                )

            application = form.save(commit=False)
            application.applicant = applicant
            if project is not None:
                application.project = project
            application.save()
            state_machine = get_application_state_machine()
            response = state_machine.start(request, application, override_auth)
            return response

    return render_to_response(
        "applications/project_common_invite_unauthenticated.html",
        {"form": form, "project": project},
        context_instance=RequestContext(request),
    )
Example #14
0
def serve_docs(request, username, project_slug, filename):
    """
    The way that we're serving the documentation.

    This is coming out of Django so that we can do simple page counting, and
    because later we can use Django auth to protect views.

    This could probably be refactored to serve out of nginx if we have more
    time.
    """
    proj = get_object_or_404(Project, slug=project_slug, user__username=username)
    if not filename:
        filename = "index.html"
    filename = filename.rstrip("/")
    if "html" in filename:
        try:
            proj.full_html_path
            if not os.path.exists(os.path.join(proj.full_html_path, filename)):
                return render_to_response("404.html", {"project": proj}, context_instance=RequestContext(request))
        except AttributeError:
            return render_to_response("404.html", {"project": proj}, context_instance=RequestContext(request))

        pageview, created = PageView.objects.get_or_create(project=proj, url=filename)
        if not created:
            pageview.count = F("count") + 1
            pageview.save()
    return serve(request, filename, proj.full_html_path)
Example #15
0
def handle_value(request):
    name = request.GET["name"]
    value = float(request.GET["value"])
    unitOfMeasure = request.GET["unit"]
    year = int(request.GET["year"])
    month = int(request.GET["month"])
    day = int(request.GET["day"])
    hour = int(request.GET["hour"])
    min = int(request.GET["min"])
    sec = 0

    measureDate = datetime(year, month, day, hour, min, sec)
    lastMeasures = LastMeasure.objects.filter(UnitOfMeasure=unitOfMeasure, Name=name)
    fixedvalue = 0
    if len(lastMeasures) > 0:
        fixedvalue = lastMeasures[0].Value
        lastMeasures[0].delete()

    if value <= 0 and (name == "thermal" or name == "elec"):
        value = fixedvalue

    measure = Measure(Name=name, Value=value, MeasureDate=measureDate, UnitOfMeasure=unitOfMeasure)
    if value < -100:
        return render_to_response("polls/insert.html", {"measure": measure})

    measure.save()
    lastMeasure = LastMeasure(Name=name, Value=value, MeasureDate=measureDate, UnitOfMeasure=unitOfMeasure)
    lastMeasure.save()
    date = measure.MeasureDate.strftime("%Y/%m")
    measureMonths = MeasureMonth.objects.filter(Month=date)
    if len(measureMonths) == 0:
        measureMonth = MeasureMonth(Month=date)
        measureMonth.save()

    return render_to_response("polls/insert.html", {"measure": measure})
Example #16
0
def subscribers_import_status(request, group_slug, task_id, template_name="user_groups/import_status.html"):
    """
    Checks if a subscriber import is completed.
    """
    group = get_object_or_404(Group, slug=group_slug)

    if not request.user.profile.is_superuser:
        raise Http403

    try:
        task = TaskMeta.objects.get(task_id=task_id)
    except TaskMeta.DoesNotExist:
        # tasks database entries are not created at once.
        task = None

    if task and task.status == "SUCCESS":
        subs = task.result
        return render_to_response(
            "user_groups/import_subscribers_result.html",
            {"group": group, "subs": subs},
            context_instance=RequestContext(request),
        )
    else:
        return render_to_response(
            template_name, {"group": group, "task": task}, context_instance=RequestContext(request)
        )
Example #17
0
def clause_update(request, clauseid):
    context = RequestContext(request)
    if request.method == "GET":
        clause = getclause(cid=clauseid)
        sectionlist = getsections()
        return render_to_response(
            "new_clause.html", {"sectionlist": sectionlist, "error": "", "clause": clause, "update": True}, context
        )

    if request.method == "POST":
        form = forms.UpdateClauseForm(request.POST)
        if form.is_valid():
            section = request.POST.get("section")
            section = request.POST.get("newsection") if section == "" else section
            enddate = request.POST.get("enddate")
            card = request.POST.get("card")
            user = request.user
            description = request.POST.get("description")
            updateclause(user, cid=clauseid, description=description, section=section, enddate=enddate, card=card)
            newrecord(user=user, cid=clauseid, operation="更新")
            print "inserted!"
            return HttpResponseRedirect("/country/clause_detail/" + str(clauseid))
        else:
            print "not a valid form"
            print form.errors
            return render_to_response("law.html", {"error": "Clause addition failed"}, context)
Example #18
0
def server_type_add(request):
    content = {}
    if request.method == "POST":  # 验证post方法
        uf = Service_type_from(request.POST)  # 绑定POST动作
        print uf
        if uf.is_valid():  # 验证数据有效性
            uf.save()
            uf = Service_type_from()
            content["uf"] = uf
            content["server_type"] = MyForm.objects.all()
            content["user_list"] = User.objects.all()
            content.update(csrf(request))
            print "server_type save is ok"
            # return render_to_response('server_idc/server_type_add.html', content, context_instance=RequestContext(request))
            return HttpResponseRedirect("/assets/server/type/list/")
        else:
            print "save error"
            uf = Service_type_from()
            content["server_type"] = MyForm.objects.all()
            content["uf"] = uf
            content.update(csrf(request))
            return render_to_response(
                "server_idc/server_type_add.html", content, context_instance=RequestContext(request)
            )
    else:
        uf = Service_type_from()
        content["uf"] = uf
        content["user_list"] = User.objects.all()
        content["server_type"] = MyForm.objects.all()
        content.update(csrf(request))
        return render_to_response("server_idc/server_type_add.html", content, context_instance=RequestContext(request))
Example #19
0
def ReferencePosting(request):
    if request.user.is_authenticated():
        user = request.user
        profile = user.get_profile()
        if not profile.is_intern:
            return HttpResponseRedirect("/profile")
        form = ReferenceForm(request.POST)
        if request.method == "POST":
            if form.is_valid():
                reference_post = add_reference(form, profile)
                return HttpResponseRedirect("/profile/references")
            else:
                return render_to_response(
                    "resume/reference_post.html",
                    {"form": form, "userProfile": profile},
                    context_instance=RequestContext(request),
                )
        else:
            form = ReferenceForm()
            return render_to_response(
                "resume/reference_post.html",
                {"form": form, "userProfile": profile},
                context_instance=RequestContext(request),
            )
    else:
        return HttpResponseRedirect("/register/intern")
Example #20
0
def login(req):
    if req.method == "POST":
        admin_id = req.REQUEST.get("admin_id", "0")
        admin_pwd = req.REQUEST.get("admin_pwd", "0")
        print(admin_id)
        print(admin_pwd)
        sql = "select admin_id,admin_pwd,admin_name from admin_user where admin_id='" + admin_id + "' and status=0"
        print(sql)

        conn, cur = ShareMethod.views.connDB()
        ShareMethod.views.exeQuery(cur, sql)
        ShareMethod.views.connClose(conn, cur)
        user = {}
        for row in cur:
            user = {"admin_id": row[0], "admin_pwd": row[1], "admin_name": row[2]}
            if user:
                if admin_pwd == user["admin_pwd"]:
                    admin_name = user["admin_name"]
                    req.session["username"] = admin_name
                    username = req.session.get("username", "未登录")
                    return HttpResponseRedirect("index.do")
                else:
                    return render_to_response("login.html", {"passwordMsg": "密码输入错误!"})

            else:
                return render_to_response("login.html", {"usernameMsg": "账号输入错误!"})
    else:
        return render_to_response("login.html")
Example #21
0
def upload(request, requestslug=None, template_name="doccloud/list.html"):
    context = {}
    try:
        if request.method == "POST":
            dc_form = DocCloudDocForm(request.POST, request.FILES)
            dc_form.user = request.user
            if dc_form.is_valid():
                model = dc_form.save(commit=False)
                model.user = request.user
                model.connect_dc_doc()
                model.save()

                if requestslug != None:
                    req = get_object_or_404(Request, slug=requestslug)
                    req.documents.add(model)
                    return redirect("request_detail", slug=requestslug)
            else:
                context["form"] = dc_form
                return render_to_response("doccloud/upload.html", context, context_instance=RequestContext(request))
        else:
            return render_to_response("doccloud/upload.html", context, context_instance=RequestContext(request))
    except Exception as e:
        print e  # need logger
    context["objects"] = Document.objects.all()
    return render_to_response(template_name, context, context_instance=RequestContext(request))
Example #22
0
def post(request):
    classes = []
    result = {}
    result.update(csrf(request))
    for item in Article_class.objects.all():
        classes.append({"id": item.cid, "name": item.name})
    result["classes"] = classes
    if not ("title" in request.POST and "content" in request.POST):
        return render_to_response("post.html", result)
    errors = []
    if not request.POST["title"]:
        errors.append("Title is empty")
    if not request.POST["content"]:
        errors.append("Content is empty")
    if errors == []:
        article = Article(
            img=request.POST["img"],
            title=request.POST["title"],
            content=request.POST["content"],
            author=request.user.username,
            time_stamp=datetime.now(),
            comments=0,
            aclass=Article_class.objects.get(cid=request.POST["class"]),
        )
        article.save()
        errors.append("Published successfully")
    result["errors"] = errors
    return render_to_response("post.html", result)
Example #23
0
def add_constraint(req, form_id, field_id):
    xform = XForm.on_site.get(pk=form_id)
    field = XFormField.objects.get(pk=field_id)
    constraints = XFormFieldConstraint.objects.order_by("order").filter(field=field)
    form = ConstraintForm()

    if req.method == "POST":
        form = ConstraintForm(req.POST)
        if form.is_valid():
            constraint = form.save(commit=False)
            constraint.field = field
            constraint.order = len(constraints)
            constraint.save()
            return render_to_response(
                "xforms/table_row_view.html",
                {
                    "item": constraint,
                    "columns": constraint_columns,
                    "buttons": constraint_buttons,
                    "field": field,
                    "xform": xform,
                },
                context_instance=RequestContext(req),
            )
    else:
        form = ConstraintForm()

    return render_to_response(
        "xforms/table_row_edit.html",
        {"buttons": add_button, "form": form, "xform": xform, "field": field},
        context_instance=RequestContext(req),
    )
Example #24
0
def contact(request):
    if request.method == "POST":
        form = ContactForm(request.POST)
        if form.is_valid():
            form.save()
            return render_to_response("tips.html")
            admin_email = "daipeng123456@gmail.com"
            send_mail(
                "联系我们",
                form.cleaned_data["content"],
                "daipeng123456@gmail.com",
                ["daipeng123456@gmail.com"],
                fail_silently=False,
            )
            if True == form.cleaned_data["if_accept_email"]:
                send_mail(
                    "联系我们",
                    form.cleaned_data["content"],
                    "daipeng123456@gmail.com",
                    [form.cleaned_data["email"]],
                    fail_silently=False,
                )
        else:
            log = loggging.getLogger("contact")
            log.debug("contact form valid false")

    form = ContactForm()
    return render_to_response("webblog/contact.html", {"form": form}, context_instance=RequestContext(request))
Example #25
0
def get_template(request):
    """Gets a template for a given level"""

    context = RequestContext(request)

    # if request.method == 'POST':
    context_dict = {"message": "Noe har gått feil."}
    form = request.POST
    if int(form.get("level_id")) == None:
        return redirect("/")
    level_id = int(form.get("level_id"))
    chapter_id = int(form.get("chapter_id"))
    set_id = int(form.get("set_id"))
    set = Set.objects.get(pk=set_id)
    # if check_for_level_skip(request.user, Chapter.objects.get(pk=chapter_id), level_id):
    #    return render_to_response('game/template.html', context_dict, context)
    context["set_title"] = set.name
    context["set_id"] = set_id
    context["chapter_id"] = chapter_id
    context["chapter_title"] = Chapter.objects.get(pk=chapter_id).name
    context["level_title"] = Level.objects.get(pk=level_id).name
    context["level_id"] = level_id
    context_dict = generate_level(request.user, level_id)
    context_dict["rating"] = get_user_rating(request.user)
    level = Level.objects.get(pk=level_id)
    context_dict["stars"] = get_user_stars_for_level(request.user, level)
    context_dict["ulp"] = get_user_rating_for_level(request.user, level)
    if request.is_ajax():
        return render_to_response("game/template.html", context_dict, context)
    else:
        return render_to_response("game/template_noajax.html", context_dict, context)
Example #26
0
File: views.py Project: 18dubu/MMS
def search(request):
    c = settings.AJAX_SEARCH_HELPER
    parts = c.split(".")
    m = __import__(parts[0])
    for comp in parts[1:]:
        m = getattr(m, comp)

    template_name = settings.SEARCH_RESULT_TEMPLATE
    c = RequestContext(request)

    if "q" in request.GET:
        query = request.GET["q"]
        if query == "":
            return render_to_response(
                template_name, {"searchform": SearchForm(), "query": query, "timenow": datetime.datetime.now()}, c
            )

        words = query.split()
        count = len(words)
        model_list = m(count, query)
        return render_to_response(
            template_name,
            {"searchform": SearchForm(), "query": query, "items_list": model_list, "timenow": datetime.datetime.now()},
            c,
        )
    else:
        return render_to_response(template_name, {"searchform": SearchForm()})
Example #27
0
def stmt_validator(request):
    context = RequestContext(request)
    context.update(csrf(request))

    if request.method == "GET":
        form = forms.ValidatorForm()
        return render_to_response("validator.html", {"form": form}, context_instance=context)
    elif request.method == "POST":
        form = forms.ValidatorForm(request.POST)
        if form.is_valid():
            # Initialize validator (validates incoming data structure)
            try:
                validator = StatementValidator.StatementValidator(form.cleaned_data["jsondata"])
            except SyntaxError, se:
                return render_to_response(
                    "validator.html",
                    {"form": form, "error_message": "Statement is not a properly formatted dictionary"},
                    context_instance=context,
                )
            except ValueError, ve:
                return render_to_response(
                    "validator.html",
                    {"form": form, "error_message": "Statement is not a properly formatted dictionary"},
                    context_instance=context,
                )
            except Exception, e:
                return render_to_response(
                    "validator.html", {"form": form, "error_message": e.message}, context_instance=context
                )
Example #28
0
def home(request):
    # If logged in show main post feed
    if request.user.is_authenticated():
        username = request.user.username
        # Check for a post submission
        if request.POST:
            return check_for_post(request, redirect_url="home")

        context = SquibContext(request, {})
        context["write_post"] = WritePost(request)
        context["posts"] = ProfilePosts(request, username)
        return render_to_response("main.html", context)

    # Else show public home page
    else:
        form = UserForm(request.POST or None)
        login_form = LoginForm()
        if request.method == "POST" and form.is_valid():
            initial_user = form.save()
            username = form.cleaned_data["username"]
            password = form.cleaned_data["password"]
            user = authenticate(username=username, password=password)
            login(request, user)
            return redirect("edit_profile")

        context = RequestContext(request, {"form": form, "login_form": login_form})
        return render_to_response("home.html", context)
Example #29
0
def approve(request, year, hash):
    try:
        year = afap.models.Year.objects.get(date=RangedDate(int(year), 1, 1))
        approval = afap.models.Approval.objects.get(key=hash)
    except (ValueError, afap.models.Year.DoesNotExist, afap.models.Approval.DoesNotExist):
        messages.error(
            request,
            "Invalid approval link; please check your email account "
            + "for an updated link or contact the person in your organization responsible "
            + "for the AFAP application.",
        )
        return shortcuts.render_to_response("approval.html", {}, template.RequestContext(request))
    if request.method == "POST":
        form = afap.forms.ApprovalForm(request.POST, instance=approval)
        if form.is_valid():
            form.save()
            messages.info(request, "Your changes have been saved.")
            return shortcuts.redirect(urlresolvers.reverse(afap.views.approve, args=(year.year, hash)))
        else:
            messages.error(
                request, "An error occurred in saving your changes, " + "please refer to any error messages below."
            )
    app = afap.forms.ApplicationForm(instance=approval.application)
    budget_request_by_cat = {}
    line_items = afap.models.LineItem.objects.filter(application=approval.application)
    for line_item in line_items:
        try:
            budget_request_by_cat[line_item.category]["line_items"].append(line_item)
        except (KeyError):
            budget_request_by_cat[line_item.category] = {"line_items": [line_item]}
    budget_request = []
    for category in budget_request_by_cat:
        budget_request.append(
            {
                "category": category,
                "line_items": budget_request_by_cat[category]["line_items"],
                "sum": sum_line_items(budget_request_by_cat[category]["line_items"]),
            }
        )
    total_sum = sum([x["sum"] for x in budget_request]) - (
        approval.application.balance_forward + approval.application.afap_income
    )
    total_request = max(total_sum, 0)
    form = afap.forms.ApprovalForm(instance=approval)
    return shortcuts.render_to_response(
        "approval.html",
        {
            "form": form,
            "application": app,
            "budget_request": budget_request,
            "approval": approval,
            "total_sum": total_sum,
            "total_request": total_request,
            "year": year,
            "hash": hash,
            "balance_forward": approval.application.balance_forward,
            "afap_income": approval.application.afap_income,
        },
        template.RequestContext(request),
    )
Example #30
0
def instanceInventory(request, hostname, resource_name):
    server_info = read_server_info(hostname)
    if server_info:
        selected_instance = None
        for instance in server_info["instances"]:
            if instance["name"] == resource_name:
                selected_instance = instance
                break
        convert_keys_names(selected_instance)
        if "java_ver" in server_info:
            java_version = server_info["java_ver"]
        else:
            java_version = ""
        return render_to_response(
            "platforms/weblogic/instance.html",
            {
                "base_url": settings.BASE_URL,
                "static_url": settings.STATIC_URL,
                "hostname": hostname,
                "instance": selected_instance,
                "java_version": java_version,
            },
            context_instance=RequestContext(request),
        )
    else:
        return render_to_response(
            "platforms/weblogic/instance.html",
            {"base_url": settings.BASE_URL, "static_url": settings.STATIC_URL, "hostname": hostname},
            context_instance=RequestContext(request),
        )