Example #1
1
def getGroups(request):
    if request.user.is_authenticated():
        groups_list = models.Group.objects.all()
        context = {"groups": groups_list}
        return render(request, "groups.html", context)
    # render error page if user is not logged in
    return render(request, "autherror.html")
Example #2
1
def imagesearch(request, page_num):
    if page_num == "":
        page_num = "1"
    page_num = int(page_num)
    num_per_page = 15

    q = request.GET.get("q", None)
    if q:
        image_server = settings.FDFS_HTTP_SERVER
        index_stories = SearchStory.query(q)[:500]
        response_images = []
        for index_story in index_stories:
            story = MStory.objects(id=index_story["db_id"]).first()
            if story and story.image_ids:
                for image_id in story.image_ids:
                    if len(image_id) > 20:
                        # print image_id
                        image = MImage.objects(id=image_id).first()
                        imagedict = dict(
                            image_url=image_server + image.image_remote_id,
                            story_url=story.story_guid,
                            story_title=story.story_title,
                        )
                        response_images.append(imagedict)
                        if len(response_images) >= 50:
                            return render(request, "imagesearch.html", locals())
    return render(request, "imagesearch.html", locals())
Example #3
1
def ingresar_cuenta(request):
    global user
    if user.has_perm("contable.add_cuenta") == False:
        return render(request, "error.html", {"mensaje": "No tiene permisos", "link": "/index"})

    if request.method == "GET":
        return render(request, "registrar_cuenta.html", {"tipo": TipoCuenta.objects.all()})
    if request.POST:
        c = request.POST["Cuenta"]
        if c == "0":
            return HttpResponseRedirect("/cuenta")
        else:
            a = Cuenta()
            s = TipoCuenta()
            a.nom_cuenta = request.POST["nom_cuenta"]
            a.saldo = 0
            s = TipoCuenta.objects.get(id=c)
            a.tipoCuenta = s
            cod = ""
            if c == "1":
                cod = "A0"
            elif c == "2":
                cod = "P0"
            elif c == "3":
                cod = "C0"
            elif c == "4":
                cod = "R0"

            cod = cod + str(len(Cuenta.objects.all()) + 1)
            a.codigo = cod
            a.montoCargo = 0
            a.montoAbono = 0
            a.save()
            return HttpResponseRedirect("/index")
    return render(request, "registrar_cuenta.html")
Example #4
1
def config_upload(request):

    if request.method == "POST":
        form = forms.ConfigUploadForm(request.POST, request.FILES)

        variables = {"form": form}

        if form.is_valid():
            success, errmsg = notifier().config_upload(request.FILES["config"])
            if not success:
                form._errors["__all__"] = form.error_class([errmsg])
                return JsonResp(request, form=form)
            else:
                request.session["allow_reboot"] = True
                return render(request, "system/config_ok.html", variables)

        return render(request, "system/config_upload.html", variables)
    else:
        FIRMWARE_DIR = "/var/tmp/firmware"
        if os.path.exists(FIRMWARE_DIR):
            if os.path.islink(FIRMWARE_DIR):
                os.unlink(FIRMWARE_DIR)
            if os.path.isdir(FIRMWARE_DIR):
                shutil.rmtree(FIRMWARE_DIR + "/")
        os.mkdir(FIRMWARE_DIR)
        os.chmod(FIRMWARE_DIR, 01777)
        form = forms.ConfigUploadForm()

        return render(request, "system/config_upload.html", {"form": form})
Example #5
1
def addMajor(request):
    if request.method == "POST":
        form = AddMajorForm(request.POST)
        if form.is_valid():
            user = request.user
            canAddMajor = user.has_perm("stufacultyinfosys.add_major")
            facultyusername = request.POST["facultyusername"]
            majorcode = request.POST["majorcode"]
            majorfullname = request.POST["majorfullname"]
            if facultyusername == user.username:
                try:
                    major = Major.createMajor(majorcode, majorfullname)
                    params = {"form": form, "canAddMajor": canAddMajor, "major": major}
                    return render(request, "stufacultyinfosys/addmajor.html", params)
                except IntegrityError as e:
                    params = {"form": form, "message": e}
                    return render(request, "stufacultyinfosys/addmajor.html", params)
            else:
                message = "Incorrect username !"
                params = {"form": form, "message": message, "canAddMajor": canAddMajor}
                return render(request, "stufacultyinfosys/addmajor.html", params)
    else:
        user = request.user
        canAddMajor = user.has_perm("stufacultyinfosys.add_major")
        form = AddMajorForm()
        params = {"form": form, "canAddMajor": canAddMajor}
        return render(request, "stufacultyinfosys/addmajor.html", params)
Example #6
1
def contact_admin(request):
    # check if form was posted
    if request.method == "POST":
        # create a Form instance and populate it with data from the request
        form = ContactForm(request.POST)

        # check whether user data is valid
        if form.is_valid():
            # send mail
            subject = form.cleaned_data["subject"]
            message = form.cleaned_data["message"]
            from_email = form.cleaned_data["from_email"]

            try:
                send_mail(subject, message, from_email, [ADMIN_EMAIL])
            except Exception:
                message = (
                    "під час відправки листа виникла "
                    "непередбачувана помилка."
                    "Спробуйте скористатися даною формою пізніше."
                )
            else:
                message = "Повідомлення успішно відіслане"

            # redirect to same contact page with success message
            return HttpResponseRedirect("%s?status_message=%s" % (reverse("contact_admin"), message))
        # if there was not POST render blank form
        else:
            form = ContactForm()

        return render(request, "contact_admin/form.html", {"form": form})
    else:
        form = ContactForm()
    return render(request, "contact_admin/form.html", {"form": form})
def gestionarSolicitud(request):
    if request.method == "GET":
        solicitud = []

        sol = Solicitud.objects.all().order_by("fechaDeCreacion")

        for x in sol:
            if x.estado == "pendiente":
                solicitud.append(x)

        return render(request, "aplicacion/gestionarSolicitud.html", {"solicitud": solicitud})
    elif request.method == "POST":

        global gestion

        gestion = request.POST.get("actual", 0)

        if gestion == 0:
            solicitud = []

            sol = Solicitud.objects.all().order_by("fechaDeCreacion")

            for x in sol:
                if x.estado == "pendiente":
                    solicitud.append(x)

            return render(request, "aplicacion/gestionarSolicitud.html", {"solicitud": solicitud})
        else:
            return HttpResponseRedirect("/choqueSolicitud")
Example #8
0
def store(request, store_id):
    liquorstore = LiquorStore.objects.get(storeHash=store_id)

    try:
        comments = Comment.objects.filter(liquorStore=liquorstore)
    except comments.DoesNotExist:
        comments = None

    if request.method == "POST":
        form = CommentForm(request.POST)
        content = request.POST.get("comment")

        if form.is_valid():
            comment = form.save(commit=False)
            comment.user = request.user
            comment.comment = content
            comment.liquorStore = liquorstore
            comment.save()
            form = CommentForm()

            # probably better to use a redirect here.
            context_dict = {"comments": comments, "form": form, "liquorstore": liquorstore}
            return render(request, "liquor_locator/store.html", context_dict)

        else:
            print form.errors
    else:
        form = CommentForm()

    context_dict = {"comments": comments, "form": form, "liquorstore": liquorstore}

    return render(request, "liquor_locator/store.html", context_dict)
Example #9
0
def editComment(request, comment_id, store_id):
    liquorstore = LiquorStore.objects.get(storeHash=store_id)
    comment = Comment.objects.get(pk=comment_id)
    comments = Comment.objects.filter(liquorStore=liquorstore)

    if request.method == "POST":
        form = EditForm(request.POST, instance=comment)
        content = request.POST.get("comment")
        if form.is_valid():
            form.comment = content
            form.save()
            form = EditForm()

            # probably better to use a redirect here.
            context_dict = {"comments": comments, "form": form, "liquorstore": liquorstore}
            return render(request, "liquor_locator/store.html", context_dict)

        else:
            print form.errors
    else:
        form = EditForm()

    context_dict = {"comments": comments, "form": form, "liquorstore": liquorstore}

    return render(request, "liquor_locator/store.html", context_dict)
Example #10
0
def company(request, name):
    try:
        company = Company.objects.get(shortName=name)
    except Company.DoesNotExist:
        # TODO: give pretty error
        return HttpResponseNotFound("<h1>Company does not exist</h1>")
    stocks = request.user.get_profile().get_stock(name)

    percentageChange = company.percentageChange()
    # ownStock is None when the user has not yet bought stock of that company
    if not stocks is None:
        return render(
            request,
            "company.html",
            {
                "company": company,
                "percentage_change": percentageChange,
                "amount_stocks": stocks.amount,
                "value_stocks": stocks.get_value(),
            },
        )
    else:
        return render(
            request,
            "company.html",
            {"company": company, "percentage_change": percentageChange, "amount_stocks": 0, "value_stocks": 0},
        )
Example #11
0
def collect2(request, start_date, end_date, gcid, fcid):
    client = GoogleClient.objects.get(pk=gcid)
    client_id = client.client_id
    client_name = client.client_name

    FacebookCampaign.objects.all().delete()
    account = FacebookAccount.objects.get(pk=fcid)
    report_model = Report.objects.get(user=request.user.username)

    if start_date == "1" and end_date == "1":
        all_fb_data(request, account)
        return render(request, "report/twothree.html")
    elif start_date == "2" and end_date == "2":
        month_fb_data(request, account)
        return render(request, "report/twothree.html")

    i_y = start_date[0] + start_date[1] + start_date[2] + start_date[3]
    i_m = start_date[5] + start_date[6]
    i_d = start_date[8] + start_date[9]

    f_y = end_date[0] + end_date[1] + end_date[2] + end_date[3]
    f_m = end_date[5] + end_date[6]
    f_d = end_date[8] + end_date[9]

    fbstartDate = i_y + "-" + i_m + "-" + i_d
    fbendDate = f_y + "-" + f_m + "-" + f_d

    fb_data(request, account, fbstartDate, fbendDate)

    return render(request, "report/twothree.html")
Example #12
0
 def get(self, request, token):
     user_profile = get_object_or_none(UserProfile, activation_key=token)
     if not user_profile:
         return render(request, self.template, {"status": "token_error", "msg": u"无效的激活链接"})
     if user_profile and user_profile.user.is_active:
         return render(request, self.template, {"status": "already_active", "msg": u"您已激活邮箱,请继续登陆"})
     return render(request, self.template, {"username": user_profile.user.username})
Example #13
0
def change_password_ajax(
    request, template_name="users/user.html", post_change_redirect="login.html", current_app=None, extra_context=None
):
    if request.method == "POST":
        form = PasswordChangeForm(request.JSON)
        if form.is_valid():
            old_password = form.cleaned_data.get("old_password", "")
            new_password1 = form.cleaned_data.get("new_password1", "")
            new_password2 = form.cleaned_data.get("new_password2", "")
            if old_password == "" or new_password1 == "" or new_password2 == "":
                return HttpResponse(json.dumps({"status": "error", "msg": "input empty"}))
            else:
                if new_password1 != new_password2:
                    return HttpResponse(json.dumps({"status": "error", "msg": "password confirm error"}))
                else:
                    if not request.user.check_password(old_password):
                        return render(request, template_name, {"error_message": "old password error", "form": form})
                        return HttpResponse(json.dumps({"status": "error", "msg": "old password error"}))
                    else:
                        request.user.set_password(new_password1)
                        request.user.save()
                        return render(request, "login.html")
                        return HttpResponse(json.dumps({"status": "success", "msg": ""}))
            return HttpResponse(json.dumps({"status": "error", "msg": "invalid input"}))
    else:
        return HttpResponse(json.dumps({"status": "error", "msg": "get method"}))
Example #14
0
def change_password(
    request, template_name="users/user.html", post_change_redirect="login.html", current_app=None, extra_context=None
):
    if request.method == "POST":
        form = PasswordChangeForm(request.JSON)
        if form.is_valid():
            old_password = form.cleaned_data.get("old_password", "")
            new_password1 = form.cleaned_data.get("new_password1", "")
            new_password2 = form.cleaned_data.get("new_password2", "")
            if old_password == "" or new_password1 == "" or new_password2 == "":
                return render(request, template_name, {"error_message": "input empty", "form": form})
            else:
                if new_password1 != new_password2:
                    return render(request, template_name, {"error_message": "password confirm error", "form": form})
                else:
                    if not request.user.check_password(old_password):
                        return render(request, template_name, {"error_message": "old password error", "form": form})
                    else:
                        request.user.set_password(new_password1)
                        request.user.save()
                        return redirect("/signout/")
        else:
            return render(request, template_name, {"error_message": "input empty", "form": form})
    else:
        return render(request, template_name)
Example #15
0
def routeToFinancesPage(request, originalContext):
    context = {}

    context["user"] = request.user
    brother = Brother.objects.get(user=request.user)
    context["brother"] = brother
    finingPower = brother.hasFiningPower()
    context["finingPower"] = finingPower

    if "form" not in originalContext:
        context["form"] = NewFineForm()

    # Add fines to table
    context["fines"] = Fine.objects.all()

    # Add user fines to payment module
    context["userFines"] = Fine.objects.filter(brother=brother)

    # Get user's roles for fine creation form.
    context["roles"] = Role.objects.filter(brother=brother)
    context["GT"] = Role.objects.get(name="Grand Treasurer").brother

    context = dict(context.items() + originalContext.items())

    # Just display the finances table if this is a GET request
    if request.method == "GET":
        return render(request, "ksda/finances.html", context)

    return render(request, "ksda/finances.html", context)
Example #16
0
def askquestion(request):
    """提问模板"""
    name = request.session.get("name")
    if request.method == "POST":
        form = QuestionForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            title = data["title"]
            text = data["text"]
            qtype = data["q_type"]
            user = User.objects.get(name=name.split()[0])
            questiontype = QuestionType(name=qtype)
            questiontype.save()
            question = Question(user=user, title=title, text=text, q_type=questiontype)
            question.save()
            # return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
            return JsonResponse({"status": "ok"})
        else:
            # return HttpResponse(request.POST.get('title'))
            return render(request, "askquestion.html")
    if name:
        access_key = "wmN715-Lo5SC1jYIkuqObCLl1bhZoURTxewUGyq2"
        secret_key = "IXXeA4-Rzu9RB6nkf687UjQt9YCOp1JpWptm0C0y"
        bucket_name = "iforj"
        q = qiniu.Auth(access_key, secret_key)
        token = q.upload_token(bucket_name)
        return render(
            request, "askquestion.html", {"QuestionForm": QuestionForm, "uptoken": token, "name": name.split()}
        )
    else:
        return HttpResponseRedirect("/")
Example #17
0
def location(request, pk):
    location = get_object_or_404(models.Locations, id=pk)
    favorite = get_is_favorite(request, location)
    category_tree = []
    fav_pk = pk
    related = models.Locations.objects.filter(map_add=True, admin_check=True, category__in=[location.category]).exclude(
        id=pk
    )
    if location.category:
        category_tree = location.category.get_ancestors(include_self=True)
    if favorite and request.user.is_authenticated():
        fav_pk = location.locatfavoritedescrip_set.filter(user=request.user).last().pk
    if request.is_ajax():
        return render(
            request,
            "favorites/inner/favorite_tag_location.html",
            {"location": location, "favorite": favorite, "fav_pk": fav_pk},
        )
    return render(
        request,
        "location_item/index.html",
        {
            "location": location,
            "category_tree": category_tree,
            "favorite": favorite,
            "fav_pk": fav_pk,
            "related": related,
        },
    )
Example #18
0
def programmer(request, n):
    # 个人主页
    user = User.objects.filter(id=n)  # 这个返回的是数组
    answers = user[0].answer_set.all()  # 一定要加[0]编程一个对象
    answers_count = len(answers)
    questions = user[0].question_set.all()
    questions_count = len(questions)
    q = request.GET.get("q")
    if user:
        if not q or q == "answers":
            return render(
                request,
                "programmer.html",
                {
                    "user": user[0],
                    "answers": answers,
                    "answers_count": answers_count,
                    "questions_count": questions_count,
                },
            )
        elif q == "questions":
            return render(
                request,
                "programmer_questions.html",
                {
                    "user": user[0],
                    "questions": questions,
                    "questions_count": questions_count,
                    "answers_count": answers_count,
                },
            )
        else:
            pass  # 还要添加一些东西
    else:
        return HttpResponseRedirect("/")
Example #19
0
def user_login(request):
    """this view is the login view for the newsletter
    """
    if request.user.is_authenticated():
        try:
            return HttpResponseRedirect(request.GET["next"])
        except:
            return HttpResponseRedirect("%s/newsletter/home/" % (SUBSITE))

    if request.POST:
        form = LoginForm(request.POST)
        if form.is_valid():
            username = request.POST["username"]
            password = request.POST["password"]
            user = authenticate(username=username, password=password)
            if user is not None:
                if user.is_active:
                    login(request, user)
                    try:
                        return HttpResponseRedirect(request.GET["next"])
                    except:
                        return HttpResponseRedirect("%s/newsletter/home/" % (SUBSITE))
                else:
                    return render("inactive user")

    form = LoginForm()

    args = {"form": form, "SUBSITE": SUBSITE}

    return render(request, "login.html", args, context_instance=RequestContext(request))
Example #20
0
def getquestion(request, n):
    """问题页面"""
    questions = Question.objects.get(id=n)
    answers = questions.answer_set.all()
    name = request.session.get("name")
    if name:
        # 当登陆时传递名字
        user = User.objects.get(name=name.split()[0])
        answered = Answer.objects.filter(user=user).filter(question=questions)
        # a = Answer.objects.get(user=user)

        if answered:
            # 如果回答过了传递用户id
            return render(
                request,
                "question.html",
                {"questions": questions, "answers": answers, "name": name.split(), "answered": user.id},
            )
        else:
            # 没回答过显示文本编辑框
            return render(
                request,
                "question.html",
                {"questions": questions, "answers": answers, "uptoken": testtwo(), "name": name.split()},
            )
    else:
        # 没登陆
        return render(request, "question.html", {"questions": questions, "answers": answers})
Example #21
0
def search(request):
    pages = []
    q = None

    if "q" in request.GET:
        form = SearchForm(request.GET)
        if form.is_valid():
            q = form.cleaned_data["q"]

            pages = Page.objects.all().prefetch_related("content_type").search(q)
            paginator, pages = paginate(request, pages)
    else:
        form = SearchForm()

    if request.is_ajax():
        return render(
            request,
            "wagtailadmin/pages/search_results.html",
            {"pages": pages, "query_string": q, "pagination_query_params": ("q=%s" % q) if q else ""},
        )
    else:
        return render(
            request,
            "wagtailadmin/pages/search.html",
            {
                "search_form": form,
                "pages": pages,
                "query_string": q,
                "pagination_query_params": ("q=%s" % q) if q else "",
            },
        )
def dine_query_list(request):
    """
    this function is responsible for turning the input sample dictionary from the query above
    into the results displayed on the Restaurant Queries Page
    """
    dining_queries = Dine_query.objects.order_by("created_date")
    if not dining_queries:
        return render(request, "restaurants/dine_query_list.html", {"headers": ["  No Query Submitted "]})
    else:
        query = dining_queries[0]
        sample, times = process_query(request, query)
        desired_output.append(times[0])
        desired_output.append(times[1])
        algo = prelim_algorithm(sample)

        for i in [times[0], times[1]]:
            desired_output.remove(i)

        for key in day_dict.keys():
            if (times[0], times[1]) == day_dict[key]:
                day_table = key
                break

        c = {
            "dining_query_results": list(algo),
            "headers": ["Restaurants", "Price (1-5) ", "Rating (1-5) "],
            "timing": [day_table + ":" + " " + "Opening Time", day_table + ":" + " " + "Closing Time"],
        }

        return render(request, "restaurants/dine_query_list.html", c)
Example #23
0
def get_location_search(request):
    if "s" in request.GET:
        search_str = request.GET["s"]

        # loc = getLocation(search_str)
        # if loc is not None:

        lat, long = geocode(address=search_str)
        print(lat)
        if not lat == None or not long == None:
            # search = loc[0]
            casas = Casa.objects.filter(latitude__gte=float(lat) - 0.05).filter(latitude__lte=float(lat) + 0.05)
            if casas.count() != 0:
                searched = []
                for casa in casas:
                    if distance_meters(float(lat), float(long), casa.latitude, casa.longitude) < 1500:
                        searched.append(casa)
                return render(request, "web/" + request.session["lang"] + "/search_result.html", {"casas": searched})
            else:
                # No houses in that range
                return render(request, "web/" + request.session["lang"] + "/info.html", {})
        else:
            # Loc not found
            return render(request, "web/" + request.session["lang"] + "/info_no_loc.html", {})
    else:
        # used url /search/ with no parameters
        return render(request, "web/" + request.session["lang"] + "/error.html", {})
    return render(
        request,
        "web/" + request.session["lang"] + "/search_result.html",
        {"latitude": search.latitude, "longitude": search.longitude, "distance": dist},
        context_instance=RequestContext(request),
    )
Example #24
0
def blog(request):
    # get the whole blog list (TODO: pagination)
    if request.method == "GET":
        return render(request, "dashboard/blog.html", {"blogs": request.user.blog_set.all()})
    # create a new blog
    elif request.method == "POST" and "_method" not in request.POST:
        blog_form = BlogForm(request.POST, request.FILES)
        if blog_form.is_valid():
            blog_instance = blog_form.save(commit=False)
            blog_instance.user = request.user
            blog_instance.save()
        return render(
            request,
            "dashboard/blog.html",
            {"blogs": request.user.blog_set.all(), "error_messages": blog_form.errors.iteritems()},
        )
    # update an existing blog
    elif request.method == "POST" and "_method" in request.POST and request.POST["_method"] == "put":
        blog_instance = Blog.objects.get(id=request.GET["id"])
        blog_form = BlogForm(request.POST, instance=blog_instance)
        if blog_form.is_valid():
            blog_form.save()
        return render(
            request,
            "dashboard/blog.html",
            {"blogs": request.user.blog_set.all(), "error_messages": blog_form.errors.iteritems()},
        )
    # delete an existing blog
    elif request.method == "POST" and "_method" in request.POST and request.POST["_method"] == "delete":
        blog_instance = Blog.objects.get(id=request.GET["id"])
        blog_instance.delete()
        return redirect("dashboard:blog")
Example #25
0
def addCourse(request):
    if request.method == "POST":
        form = AddCourseForm(request.POST)
        if form.is_valid():
            user = request.user
            canAddCourse = user.has_perm("stufacultyinfosys.add_course")
            facultyusername = request.POST["facultyusername"]
            majorcode = request.POST["majorcode"]
            major = Major.objects.get(pk=majorcode)
            coursename = request.POST["coursename"]
            coursenum = request.POST["coursenum"]
            if facultyusername == user.username:
                try:
                    faculty = Faculty.objects.get(username=facultyusername)
                    course = Course.createCourse(coursenum, coursename, major, faculty)
                    params = {"form": form, "canAddCourse": canAddCourse, "course": course}
                    return render(request, "stufacultyinfosys/addcourse.html", params)
                except IntegrityError as e:
                    params = {"form": form, "message": e}
                    return render(request, "stufacultyinfosys/addcourse.html", params)

            else:
                message = "Incorrect username !"
                params = {"form": form, "message": message, "canAddCourse": canAddCourse}
                return render(request, "stufacultyinfosys/addcourse.html", params)
    else:
        user = request.user
        canAddCourse = user.has_perm("stufacultyinfosys.add_course")
        form = AddCourseForm()
        params = {"form": form, "canAddCourse": canAddCourse}
        return render(request, "stufacultyinfosys/addcourse.html", params)
Example #26
0
def sites(request, format):
    _json = {}
    mSites = Sitio.objects.all().order_by("nombre").select_related()
    mRegions = Region.objects.all()
    # print simplejson.dumps(list(mSites.values()))
    _jsonRegiones = []
    for region in mRegions:
        _jsonRegiones.append(
            {"pk": region.pk, "nombre": region.nombre, "sites": list(mSites.filter(region=region).values("pk"))}
        )
        # 'id':site.id,
        # 'name':site.nombre,
        # 'neumonico':site.neumonico,
        # 'lat':site.lat,
        # 'lng':site.lng,
        # 'reg':site.region.pk
    _json["sites"] = list(
        mSites.extra(select={"reg": "region_id", "name": "nombre"}).values(
            "pk", "name", "neumonico", "lat", "lng", "reg"
        )
    )
    _json["regiones"] = _jsonRegiones
    data = simplejson.dumps(_json)
    if format:
        return render(request, "simple_data.html", {"data": data}, content_type="application/json")
    return render(request, "sitios.html", {"data": data})
Example #27
0
def index(request):
    if request.POST:
        form = UploadForm(request.POST)
        # first split filename through '.', then trim extension
        extension = str(request.FILES["name"]).split(".")[-1]
        # creating an instance of File model
        try:
            uploadedFile = File(
                name=request.FILES["name"], size=request.FILES["name"].size, type=Type.objects.get(ext=extension)
            )
        except Type.DoesNotExist:
            fileTypes = ", ".join(str(fileType) for fileType in Type.objects.all())
            # on unsuccessful upload - filetype not supported
            return render(
                request,
                "upload/index.jade",
                {"form": form, "error": "file type not fit for upload, allowed file types: %s" % fileTypes},
            )
            # saving uploaded file to the disk and db
        uploadedFile.save()
        # on successful upload
        return render(request, "upload/index.jade", {"form": form, "success": "file uploaded"})
    else:
        # form displaying
        form = UploadForm()
        return render(request, "upload/index.jade", {"form": form})
Example #28
0
def daily_record(request, template_name="kinger/daily_record.html"):
    """日常记录详情页 """
    if not is_vip(request.user):
        return render(request, "403.html")
    current_time = datetime.datetime.now()
    tiles = Tile.objects.get_tiles_baby(request.user)
    category = TileCategory.objects.filter(is_tips=False, parent__pk=10).exclude(pk=9)
    group_date = get_group_date(request)
    page = int(request.GET.get("page", "1"))
    start = (page - 1) * 7
    end = page * 7

    is_first = {"year": 0, "month": 0}
    record_list = []
    for day in group_date[start:end]:
        record_dict = {}
        record_dict["day"] = day[0]
        record_dict["is_first"] = False
        # 判断当年当月的首条记录
        if is_first["year"] != day[0].year or is_first["month"] != day[0].month:
            record_dict["is_first"] = True
            is_first["year"] = day[0].year
            is_first["month"] = day[0].month

        daily_record = get_daily_category_tiles(tiles, category, day[0])
        record_dict["data"] = daily_record
        record_list.append(record_dict)

    ctx = {"channel": "baby", "record_list": record_list, "group_date": group_date}
    return render(request, template_name, ctx)
Example #29
0
def iniciarPeriodo(request):
    global user
    global capContable

    coa = EstadoPeriodo.objects.get(periodoActivo=True)
    if user.has_perm("contable.add_estadoperiodo") == False:
        return render(request, "error.html", {"mensaje": "No tiene permisos", "link": "/index"})
    elif coa is None:
        return render(request, "error.html", {"mensaje": "El periodo sigue activo", "link": "/index"})

    per = EstadoPeriodo()
    per.periodoContador = coa.periodoContador + 1
    per.periodo = time.strftime("%x")
    per.cierre = False
    per.ajuste = False

    coa.periodoActivo = False

    coa.save()
    per.save()

    cr = Cuenta.objects.filter(tipoCuenta=4)
    for c in cr:
        c.delete()
    cc = Cuenta.objects.get(tipoCuenta=3)
    cc.montoAbono = capContable
    cc.save()

    return render(request, "error.html", {"mensaje": "Se ha inciado periodo contable", "link": "/index"})
Example #30
0
def main(request):
    """Render main page."""
    if request.user.is_authenticated():
        events = Event.objects.filter(archived=False)
        return render(request, "index.html", {"events": events, "user": request.user})
    else:
        return render(request, "index.html", {"user": request.user})