Esempio n. 1
0
def tweet_create_view_django(request, *arg, **kwargs):
    '''
    REST API CREATE VIEW
    '''
    # The tweetForm class can be initialize with data or not
    user = request.user
    if not request.user.is_authenticated:
        user = None
        if request.is_ajax():
            return JsonResponse({}, status=401)
        return redirect(settings.LOGIN_URL)
    form = TweetForm(request.POST or None)
    next_url = request.POST.get("next") or None
    if form.is_valid():
        obj = form.save(commit=False)
        # do other form related logic
        # obj.user = request.user or None # Annonymous users
        obj.user = user
        obj.save()
        # if we receive an ajax call we don't need the redirect but we can return json response.
        if request.is_ajax():
            return JsonResponse(obj.serialize(), status=201)
        if next_url != None and is_safe_url(next_url, ALLOWED_HOSTS):
            return redirect(next_url)
            # reinitialize a blank form
        form = TweetForm()
    if form.errors:
        if request.is_ajax():
            return JsonResponse(form.errors, status=400)

    return render(request, 'components/form.html', context={"form": form})
Esempio n. 2
0
def contact_page(request):
    contact_form = ContactForm(request.POST or None)
    context = {
        "title": "Contact",
        "content": " Welcome to the contact page.",
        "form": contact_form,
    }

    if contact_form.is_valid():
        #print(contact_form.cleaned_data)
        if request.is_ajax():
            return JsonResponse({"message": "Thank you"})
    if contact_form.errors:
        errors = contact_form.errors.as_json()
        if request.is_ajax():
            return HttpResponse(errors,
                                status=400,
                                content_type='application/json')

    # if request.method == "POST":
    #    # print(request.POST)
    #    print(request.POST.get('fullname'))
    #    print(request.POST.get('email'))
    #    print(request.POST.get('content'))
    return render(request, "contact/view.html", context)
Esempio n. 3
0
def tweet_create_view_pure_django(request, *args, **kwargs):
    user = request.user
    if not request.user.is_authenticated:
        if request.is_ajax():
            return JsonResponse({}, status=401)
        return redirect(settings.LOGIN_URL)
    form = TweetForm(request.POST or None)
    next_url = request.POST.get("next") or None
    if form.is_valid():
        obj = form.save(commit=False)
        obj.user = user
        obj.save()
        if request.is_ajax():
            return JsonResponse(obj.serialize(), status=201)

        if next_url != None and is_safe_url(next_url, ALLOWED_HOSTS):
            return redirect(next_url)
        form = TweetForm()

    if form.errors:
        if request.is_ajax():
            return JsonResponse(form.errors, status=400)

    context = {"form": form}
    return render(request, "components/form.html", context)
Esempio n. 4
0
def detail(request, id):
    context = common()
    current_post = Meals.objects.filter(id=id).last()
    context['object'] = current_post
    # me = Meals.objects.all().filter(user=current_post.user).count()
    current_post_comment = current_post.commentpost_set.all()
    pagination = Paginator(current_post_comment, 4)
    context["current_post_comment"] = pagination.get_page(request.GET.get('page'))
    context["page_range"] = pagination.page_range
    if request.user.is_authenticated:
        context['check_like'] = Like.objects.filter(post_id=id, user=request.user)
    # context["current_post_comment"] = current_post_comment
    context["form"] = CommentForm()
    if request.method == "POST" and request.is_ajax():
        post_id_cm = request.POST.get("post_id_cm")
        print(post_id_cm)
        if post_id_cm:
            text_coment = request.POST.get('text_comment')
            CommentPost.objects.create(
                user=request.user,
                comment=text_coment,
                post=Meals.objects.filter(id=post_id_cm).last(),
            )
            return JsonResponse({
                'append': True,
                'image': request.user.profile_photo.url,
                'user': request.user.username,
                'text_comment': text_coment,
                'comment_count': current_post_comment.count()
            })
    return render(request, 'DetailFood.html', context)
Esempio n. 5
0
def Read(request):
    if request.is_ajax():
        param = request.POST['param0']
        param2 = request.POST['param1']
        print(param)
    creds = None
    if os.path.exists('token' + param + '.pickle'):
        with open('token' + param + '.pickle', 'rb') as token:
            creds = pickle.load(token)
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'media/mailbox/' + param, SCOPES)
            creds = flow.run_local_server(port=0)
        with open('token' + param + '.pickle', 'wb') as token:
            pickle.dump(creds, token)
    service = build('gmail', 'v1', credentials=creds)
    results = service.users().messages().list(userId='me',
                                              labelIds=[param2]).execute()
    messages = results.get('messages', [])
    if not messages:
        print("No messages found.")
    else:
        list = []
        print("Message snippets:")
        for message in messages:
            msg = service.users().messages().get(userId='me',
                                                 id=message['id']).execute()
            print(msg['snippet'])
            list.append(msg['snippet'])

        return JsonResponse({'code': list})
Esempio n. 6
0
def add_to_cart(request):
    cart = Cart(request)
    if not request.is_ajax():
        id = request.POST.get("id")
        item = get_object_or_404(Item, id=id)
        print(item)
        form = CartAddItemForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            cart.add(item=item,
                     quantity=cd['quantity'],
                     update_quantity=cd['update'])
    else:
        item_id = int(request.POST.get('id'))
        item_quantity = int(request.POST.get('quantity'))
        update_quantity = bool(int(request.POST.get('update_quantity', False)))
        print(
            f'{item_id=} {item_quantity=} {type(item_quantity)=} {update_quantity=}'
        )
        cart.add(item=get_object_or_404(Item, id=item_id),
                 quantity=item_quantity,
                 update_quantity=update_quantity)
        count = cart.count_items(item_id)

        data = {
            'id': item_id,
            'quantity': count,
            'cart_count': len(cart),
        }
        # request.session.modified = True
        # return render(request, 'shop/cart.html', {})
        return JsonResponse(data)

    return redirect(request.POST.get('url_from'))
Esempio n. 7
0
def add_to_favorites(request):
    if request.method == 'POST':
        add_data = {
            'type': request.POST.get('type'),
            'id': request.POST.get('id'),
            # 'user': request.user.username
        }
        user = request.user

        # print(add_data)
        if user.is_authenticated and user.is_active:
            if add_data['id'] and not Favorite.objects.filter(
                    user=user, item_id=add_data['id']):
                Favorite.objects.create(user=user,
                                        item_id=request.POST.get('id'))
        else:
            message = "Залогиньтесь для добавления в избранное"

    if request.is_ajax():
        print('is ajax')
        data = {
            'type': request.POST.get('type'),
            'id': request.POST.get('id'),
        }
        # request.session.modified = True
        return JsonResponse(data)
    return redirect(request.POST.get('url_from'))
Esempio n. 8
0
def like_view(request):
    if request.method == "POST" and request.is_ajax():
        post_id = request.POST.get("post_id")
        post = Meals.objects.filter(id=post_id).last()
        if post:
            like = Like.objects.filter(post=post, user=request.user).last()
            if like:
                like.delete()
                return JsonResponse({
                    "like_count": post.like_set.all().count(),
                    "status": False
                })
            else:
                Like.objects.create(
                    user=request.user,
                    post=post
                )
                return JsonResponse({
                    "like_count": post.like_set.all().count(),
                    "status": True
                })
        else:
            return redirect("/")
    else:
        return redirect("/")
Esempio n. 9
0
def add_activity(request):
    # by dqn14 Nov 2, 2016
    # use this if-else to block violent access
    if request.is_ajax() and request.method == 'POST':
        name = request.POST.get('name')
        date_begin = request.POST.get('date_begin')
        date_end = request.POST.get('date_end')
        teacher_id = request.session.get('teacher_id', -1)
        if teacher_id == -1:
            return JsonResponse({'success':'N'})
        print name, date_begin, date_end
        try:
            begin_list = date_begin.split('-')
            end_list = date_end.split('-')
            back.createTimerbyDict({Timer.NAME:name,
                                    Timer.START_TIME: datetime.date(int(begin_list[0]), int(begin_list[1]), int(begin_list[2])),
                                    Timer.END_TIME: datetime.date(int(end_list[0]), int(end_list[1]), int(end_list[2])),
                                    Timer.TEACHER_ID: int(teacher_id)
                                    })
            t = {}
            t['success']='Y'
            t['message']= u'活动创建成功'
            print 't', t
            return JsonResponse(t)
        except:
            t = {}
            t['success']='N'
            t['message']=u'创建失败'
            return JsonResponse(t)
    else:
        return HttpResponse('Access denied.')
Esempio n. 10
0
 def post(self, request, *args, **kwargs):
     if request.is_ajax():
         form = self.form_class(request.POST)
         if form.is_valid():
             nuevo_usuario = Usuarios(
                 rut=form.cleaned_data.get('rut'),
                 username=form.cleaned_data.get('username'),
                 nombres=form.cleaned_data.get('nombres'),
                 apellidos=form.cleaned_data.get('apellidos'),
                 correo=form.cleaned_data.get('correo'),
                 user_administrador=form.cleaned_data.get(
                     'user_administrador'),
             )
             nuevo_usuario.set_password(form.cleaned_data.get('password1'))
             nuevo_usuario.save()
             mensaje = f'Usuario registrado correctamente'
             error = 'Sin errores'
             response = JsonResponse({'mensaje': mensaje, 'error': error})
             response.status_code = 201
             return response
         else:
             mensaje = f'Error al registrar usuario'
             error = form.errors
             response = JsonResponse({'mensaje': mensaje, 'error': error})
             response.status_code = 400
             return response
     else:
         return redirect('/inicio_usuarios')
Esempio n. 11
0
def like_view(request):
    if request.method == "POST" and request.is_ajax():
        post_id = request.POST.get("post_id")
        post = Post.objects.filter(id=post_id).last()
        if post:
            like = Like.objects.filter(post=post, user=request.user).last()
            if like:
                post.like_count -= 1
                post.save()
                like.delete()
                return JsonResponse({
                    "like_count": post.like_count,
                    "status": False
                })
            else:
                post.like_count += 1
                post.save()
                Like.objects.create(
                    user=request.user,
                    post=post
                )

                return JsonResponse({
                    "like_count": post.like_count,
                    "status": True
                })
        else:
            return redirect("explore")
    else:
        return redirect("explore")
Esempio n. 12
0
def newGroup(request):
    #gen random string
    #gen new db entry w string as title
    #return string in json

    if request.is_ajax():

        print(" NEW AJAX REQUEST FOR GROUP")
        print(request)
        #gen random id
        unique_id = get_random_string(length=16)

        #create database entry with that id as title
        listFresh = list(Restaurant.objects.filter(region="UC").values())
        dictFresh = {}

        c = 0
        for item in listFresh:
            dictFresh.update({c: listFresh[c]})
            c = c + 1

        newProfile = filters(
            title=unique_id,
            restaurantInfo=json.dumps(dictFresh),
            filterInfo=json.dumps(defaultFilters),
            filterUsernamesVotedUp=json.dumps(defaultUsernamesVoted),
            filterUsernamesVotedDown=json.dumps(defaultUsernamesVoted))
        print(newProfile.filterInfo)
        #print(newProfile.title)
        newProfile.save()

        json_response = {'urlString': {'url': unique_id}}
        return HttpResponse(json.dumps(json_response),
                            content_type='application/json')
    return render(request, 'blog/newGroup.php', {'urlString': ''})
Esempio n. 13
0
def new_message_to_group(request):
    # by dqn14 Nov 7, 2016
    # use this if-else to block violent access
    if request.is_ajax() and request.method == 'POST':
        try:
            title = request.POST.get('title')
            target_group = request.POST.get('group_val')
            text = request.POST.get('maintext')
            teacher_id = request.session.get('teacher_id', -1)
            print title, target_group, text, teacher_id

            group = back.getGroupbyDict({Group.ID: int(target_group)})[0]
            stu_id_list_str = getattr(group, Group.STU_LIST).split('_')
            if '' in stu_id_list_str:
                stu_id_list_str.remove('')
            stu_id_list = []
            for item in stu_id_list_str:
                stu_id_list.append(int(item))

            back.createNoticebyDict({Notice.TITLE: title,
                                     Notice.TEXT: text,
                                     Notice.TEACHER_ID: int(teacher_id),
                                     Notice.RECEIVE_STU: stu_id_list})
            t = {}
            t['success']='Y'
            t['message']=u'发布成功'
            return JsonResponse(t)

        except:
            t = {}
            t['success']='N'
            t['message']=u'发布失败'
            return JsonResponse(t)
    else:
        return HttpResponse('Access denied.')
Esempio n. 14
0
def busqueda(request):
    if request.is_ajax():
        queryset = request.GET.get('nombre')
        actio = request.GET.get('action')
        if actio == 'organismo':
            if queryset != 0:
                if Organismo.objects.filter(nombrecientifico__icontains=queryset):
                    data = Organismo.objects.filter(nombrecientifico__icontains=queryset).values(
                        'nombrecientifico', 'genero', 'ph', 'aw')
        else:
            if actio == 'reactor':
                if Reactor.objects.filter(modelo__icontains=request.GET['nombre']):
                    data = Reactor.objects.filter(modelo__icontains=request.GET['nombre']).values(
                        'modelo', 'marca', 'especificaciontecnica', 'foto1')
            else:
                if actio == 'batch':
                    if CaBatch.objects.filter(titulo__icontains=request.GET['nombre']):
                        data = CaBatch.objects.filter(titulo__icontains=request.GET['nombre']).values(
                            'id', 'titulo', 'descripcion', 'y', 'ks', 'umax', 'ms', 'f', 't', 'v0', 'v', 'vf', 'so',
                            'n', 'x')
                else:
                    if actio == 'tiempo':
                        if CaPrediccion.objects.filter(titulo__icontains=request.GET['nombre']):
                            data = CaPrediccion.objects.filter(titulo__icontains=request.GET['nombre']).values(
                                'titulo', 'descripcion', 'x', 'v', 'so', 'umax', 'y', 'sf', 'tb')

        return HttpResponse(json.dumps(list(data)), content_type='application/json')
    else:
        return HttpResponse("Solo Ajax");
Esempio n. 15
0
def batch_add_to_group(request):
    # by dqn14 Nov 7, 2016
    # use this if-else to block violent access
    if request.is_ajax() and request.method == 'POST':
        stu_num = int(request.POST.get('student_num'))
        group_id = int(request.POST.get('group'))    # This is a string

        key_list = []
        for i in range(0, stu_num):
            key_list.append('student_id_%s'%(str(i)))
        id_list = []
        for item in key_list:
            id_list.append(int(request.POST.get(item)))

        group = back.getGroupbyDict({Group.ID: group_id})[0]
        stu_list = getattr(group, Group.STU_LIST).split('_')
        if '' in stu_list:
            stu_list.remove('')
        for item in id_list:
            item = str(item)
            if item not in stu_list:
                stu_list.append(item)

        back.setGroup(group, Group.STU_LIST, '_'.join(stu_list))


        t = {}
        if stu_num > 0:
            t['success'] = 'Y'
        else:
            t['success']='N'
            t['message']='该组已满'
        return JsonResponse(t)
    else:
        return HttpResponse('Access denied.')
Esempio n. 16
0
def list_question(request):
    # by dqn14 Oct 27, 2016
    # use this if-else to block violent access
    if request.is_ajax() and request.method == 'POST':
        test_id = request.POST.get('id')
        list = test_id.split('_')
        year = find_item_index_in_list(int(list[0]), YEAR_LIST)
        province = find_item_index_in_list(list[1], SHITI_LIST)
        subject = find_item_index_in_list(list[2], SUBJECT_LIST)
        dic = {
            Picture.YEAR: year,
            Picture.PROVINCE: province,
            Picture.SUBJECT: subject,
            Picture.IS_TITLE: 0
        }
        pic_list = pic.getPicturebyDict(dic)
        t = []
        for item in pic_list:
            pic_dic = pic.getPictureAllDictByObject(item)
            c = {}
            c['num'] = pic_dic[Picture.NUMBER]
            c['type'] = CATEGORY_LIST[pic_dic[Picture.CATEGORY]]
            c['maxscore'] = pic_dic[Picture.SCORE]
            t.append(c)
        return JsonResponse(t, safe=False)
    else:
        return HttpResponse('Access denied.')
Esempio n. 17
0
def get_next_question_num(request):
    # by dqn14 Oct 27, 2016
    # use this if-else to block violent access
    if request.is_ajax() and request.method == 'POST':
        test_id = request.POST.get('test_id')
        info = test_id
        info_list = info.split('_')
        print info_list
        year = int(info_list[0]) - YEAR_LIST[1] + 1
        province = find_item_index_in_list(info_list[1], PROVINCE_LIST)
        subject = find_item_index_in_list(info_list[2], SUBJECT_LIST)
        dict = {
            Picture.YEAR: year,
            Picture.PROVINCE: province,
            Picture.SUBJECT: subject,
            Picture.IS_TITLE: 0
        }
        pic_list = pic.getPicturebyDict(dict)
        num_list = []
        for picture in pic_list:
            info_dic = pic.getPictureAllDictByObject(picture)
            num_list.append(info_dic[Picture.NUMBER])
        num = 1
        for i in range(1, 99999):
            if i not in num_list:
                num = i
                break
        t = {'num': num}
        return JsonResponse(t)
    else:
        return HttpResponse('Access denied.')
Esempio n. 18
0
def release_test(request):
    # by dqn14 Oct 26, 2016
    # use this if-else to block violent access
    if request.is_ajax() and request.method == 'POST':
        id = request.POST.get('id')
        print 'fabu ',id
        list = id.split('_')
        year = find_item_index_in_list(int(list[0]), YEAR_LIST)
        province = find_item_index_in_list(list[1], SHITI_LIST)
        subject = find_item_index_in_list(list[2], SUBJECT_LIST)
        dic = {
            Picture.YEAR: year,
            Picture.PROVINCE: province,
            Picture.SUBJECT: subject,
        }
        pic_list = pic.getPicturebyDict(dic)
        t = {}
        for item in pic_list:
            flag = pic.setPicture(item, Picture.IS_DELEVERED, 1)
            if flag is False:
                t['success'] = 'N'
                t['message'] = '管理员正忙'
                return JsonResponse(t)

        t['success'] = 'Y'
        t['message'] = 'ok'
        print 'ttt ', t
        return JsonResponse(t)
    else:
        return HttpResponse('Access denied.')
Esempio n. 19
0
def remove_test(request):
    # by dqn14 Oct 26, 2016
    # use this if-else to block violent access
    if request.is_ajax() and request.method == 'POST':
        id = request.POST.get('id')
        list = id.split('_')
        year = find_item_index_in_list(int(list[0]), YEAR_LIST)
        province = find_item_index_in_list(list[1], SHITI_LIST)
        subject = find_item_index_in_list(list[2], SUBJECT_LIST)
        dic = {
            Picture.YEAR: year,
            Picture.PROVINCE: province,
            Picture.SUBJECT: subject,
        }
        pic.removePictureIDByDic(dic)
        t={}
        t['success'] = 'Y'
        t['message'] = 'ok'


        student_list = stu.getAllInStudent()
        for student in student_list:
            account = getattr(student, Student.ACCOUNT)
            estimate = eval(getattr(student, Student.ESTIMATE_SCORE))
            if id in estimate.keys():
                estimate.pop(id)
            stu.setStudent(account, Student.ESTIMATE_SCORE, estimate)


        return JsonResponse(t)
    else:
        return HttpResponse('Access denied.')
Esempio n. 20
0
def test_list_all(request):
    # by dqn14 Oct 26, 2016
    # use this if-else to block violent access
    if request.is_ajax() and request.method == 'POST':
        t = []
        pic_list = pic.getPicturebyDict({Picture.IS_TITLE: 1})
        for item in pic_list:
            c = {}
            dic = pic.getPictureAllDictByObject(item)
            c['id'] = '%s_%s_%s' % (str(YEAR_LIST[dic[Picture.YEAR]]),
                                    SHITI_LIST[dic[Picture.PROVINCE]],
                                    SUBJECT_LIST[dic[Picture.SUBJECT]])
            c["year"] = str(YEAR_LIST[dic[Picture.YEAR]])
            c["place"] = SHITI_LIST[dic[Picture.PROVINCE]]
            c["subject"] = SUBJECT_LIST[dic[Picture.SUBJECT]]


            if dic[Picture.IS_DELEVERED] == 1:
                c["released"] = "Y"
            else:
                c["released"] = "N"
            t.append(c)
        return JsonResponse(t, safe=False)
    else:
        return HttpResponse('Access denied.')
Esempio n. 21
0
def deleteMember(request):
    if request.POST:
        print(request.POST)
        template1 = 'groups/showGroupMemberNewCycle.html'
        member_id = request.POST['member_id']
        group_id = request.POST['group_id']
        group = Groups.objects.get(id=group_id)
        try:
            cal_period = CalculationPeriod.objects.get(group_id=group_id, is_active=True)
            print(cal_period)
            context = {
                'memberIngroup': group,
                'messageNoDelete': 'Deletion failed. Calculation period is still active. Settle calculation first and '
                                   'try again. '
            }
        except CalculationPeriod.DoesNotExist:
            group.group_members.remove(member_id)
            context = {
                'memberIngroup': group,
                'messageDelete': 'Member deleted.'
            }

    if request.is_ajax():
        html = render_to_string('groups/showGroupMember.html', context, request=request)
        groupMemberCycle = render_to_string(template1, context, request=request)
    return JsonResponse({'post': html, 'groupMemberCycle': groupMemberCycle})
Esempio n. 22
0
def deletepost(request, pk):
    post = get_object_or_404(Post, id=pk)
    if request.is_ajax():
        Post.objects.filter(pk=pk).update(deleted=True)
        print("deleted")
        return JsonResponse({"message": "success"})
    return JsonResponse({"message": "Wrong route"})
Esempio n. 23
0
def consultar_desc_obj(request):

    if request.is_ajax():
        objetivo = Objetivo.objects.get(id=request.GET['id'])
        response = JsonResponse({'descripcion': objetivo.descripcion})
        return HttpResponse(response.content)
    else:
        return redirect('/')
Esempio n. 24
0
def add_black_comment(request):
    if request.is_ajax() and request.method == 'POST':
        if request.POST.get('text', None):
            blc = BlackListComment.objects.create(
                author=request.user,
                post_id=request.POST['post_id'],
                text=request.POST['text'])
            return render(request, 'news/black_comment.html', {'comment': blc})
Esempio n. 25
0
def promottoadmin(request):
    if request.is_ajax():
        userid = request.GET['id']
        user = get_object_or_404(User, id=userid)
        user.is_superuser = 1
        user.save()
        return JsonResponse({"userid": user.id}, safe=False)
    raise Http404
Esempio n. 26
0
def replyDelete(request, pk):
    if request.method == "POST" and request.is_ajax():
        reply_id = request.POST.get('replyid')
        print(reply_id)
        commentspecific = Comment.objects.filter(id=reply_id).update(deleted=True)
        return JsonResponse({"message": "success"})
    else:
        return JsonResponse({"message": "fail"})
Esempio n. 27
0
def actor_ajax(request):

    if request.is_ajax():
        actor = Actor.objects.get(id=request.GET['id'])
        response = JsonResponse({'descripcion': actor.descripcion})
        return HttpResponse(response.content)
    else:
        return redirect('/')  # redirecciona a la misma pagina
Esempio n. 28
0
def choose_del_file(request, pk):
    file_del = FilesForLessons.objects.get(id=pk)
    data = {}
    if request.is_ajax():
        data['file'] = str(file_del)
        data['link'] = str(file_del.id)
        data['status'] = 'ok'
        return JsonResponse(data)
Esempio n. 29
0
def updateServerFilters(request):
    print("updating server filters")
    if request.is_ajax():
        #print(request.GET.get('filterChanged', ''))
        #print('is ajax')
        #now we need to change the database
        title = request.GET.get('title', '')
        filterChanged = request.GET.get('filterChanged', '')
        filterValue = request.GET.get('filterValue', '')

        #now we need to access and update the database
        profile = filters.objects.get(title=title)

        if (filterChanged == '0'):
            if (profile.filter1 == 'f'):
                profile.filter1 = 't'
            else:
                profile.filter1 = 'f'
        elif (filterChanged == '1'):
            if (profile.filter2 == 'f'):
                profile.filter2 = 't'
            else:
                profile.filter2 = 'f'
        elif (filterChanged == '2'):
            if (profile.filter3 == 'f'):
                profile.filter3 = 't'
            else:
                profile.filter3 = 'f'
        elif (filterChanged == '3'):
            if (profile.filter4 == 'f'):
                profile.filter4 = 't'
            else:
                profile.filter4 = 'f'
        elif (filterChanged == '4'):
            if (profile.filter5 == 'f'):
                profile.filter5 = 't'
            else:
                profile.filter5 = 'f'
        elif (filterChanged == '5'):
            if (profile.filter6 == 'f'):
                profile.filter6 = 't'
            else:
                profile.filter6 = 'f'
        elif (filterChanged == '6'):
            if (profile.filter7 == 'f'):
                profile.filter7 = 't'
            else:
                profile.filter7 = 'f'
        elif (filterChanged == '7'):
            if (profile.filter8 == 'f'):
                profile.filter8 = 't'
            else:
                profile.filter8 = 'f'
        profile.save()

    else:
        print('not ajax request')
    return render(request, 'blog/updateServerFilters.php')
Esempio n. 30
0
def remove_volunteer_by_id(request):
    # by dqn14 Oct 15, 2016
    # use this if-else to block violent access
    if request.is_ajax() and request.method == 'POST':
        id = request.POST.get('id')
        vol.removeVolunteerAccount(vol.idToAccountVolunteer(id))
        return JsonResponse({})  # return nothing
    else:
        return HttpResponse('Access denied.')
Esempio n. 31
0
def extraerLote(request):
    if request.user.groups.filter(name='Encargados de Sala').exists() or request.user.groups.filter(name='Encargados de Extraccion').exists():
        if request.is_ajax():
            id = request.GET.get('id')
            peso = float(request.GET.get('peso'))
            observacion = request.GET.get('observacion')
            user = request.user
            lote = Lote.objects.get(pk=id)
            if lote.estadoActual.__class__.__name__ == "Ingresado":
                lote.extraer(user, peso, observacion)
                return HttpResponse("")
    else:
        return HttpResponse('No tiene permisos para realizar esta tarea')
Esempio n. 32
0
def desactivarSocio(request):
    #-- funcion para cambiar el estado del socio a 'INACTIVO' --#
    if request.is_ajax():
        id = request.GET.get('id')
        user = request.user
        socio = Socio.objects.get(pk=id)
        if socio.estadoActual.__class__.__name__ == "Activo":
            print "antes de extraer"
            socio.desactivar()
            return HttpResponse("Socio inactivo")
        return HttpResponse("El socio no se pudo desactivar")
    else:
        return HttpResponse('No es una peticion Ajax')
Esempio n. 33
0
def probarSocio(request):
    #-- funcion para cambiar el estado del socio a 'A PRUEBA'  --#
    if request.is_ajax():
        print "entre al ajax"
        id = request.GET.get('id')
        user = request.user
        socio = Socio.objects.get(pk=id)
        if socio.estadoActual.__class__.__name__ == "Prueba":
            print "antes de extraer"
            socio.probar('un anio')
            return HttpResponse("Socio a prueba")
        return HttpResponse("El socio no se pudo ingresar en periodo de prueba")
    else:
        return HttpResponse('No es una peticion Ajax')
Esempio n. 34
0
def activarSocio(request):
    #--  funcion para cambiar el estado del socio a 'ACTIVO'  --#
    if request.is_ajax():
        print "entre al ajax"
        id = request.GET.get('id')
        user = request.user
        socio = Socio.objects.get(pk=id)
        print socio.estadoActual.__class__.__name__
        if socio.estadoActual.descripcion == "A Prueba":
            print "antes de extraer"
            socio.activar()
            return HttpResponse("Socio activo")
        return HttpResponse("El socio no se pudo activar")
    else:
        return HttpResponse('No es una peticion Ajax')
Esempio n. 35
0
def dextraerLote(request):
    if request.user.groups.filter(name='Encargados de Sala').exists() or request.user.groups.filter(name='Encargados de Extraccion').exists():
        if request.is_ajax():
            id = request.GET.get('id')
            peso = float(request.GET.get('peso'))
            observacion = request.GET.get('observacion')
            user = request.user
            lote = Lote.objects.get(pk=id)
            if (lote.estadoActual.__class__.__name__ == "Extraido") or (lote.estadoActual.__class__.__name__ == "Devuelto"):
                lote.extraerDeNuevo(user, peso, observacion)
                return HttpResponse("Lote Extraido")
            return HttpResponse("El lote no se puede extraer")
        else:
            return HttpResponse('No es una peticion Ajax')
    else:
        return HttpResponse('No tiene permisos para realizar esta tarea')
Esempio n. 36
0
def devolverLote(request):
    if request.user.groups.filter(name='Encargados de Sala').exists() or request.user.groups.filter(name='Encargados de Entrada y Salida').exists():
        if request.is_ajax():
            print "entre al ajax"
            id = request.GET.get('id')
            user = request.user
            lote = Lote.objects.get(pk=id)
            if lote.estadoActual.__class__.__name__ == "Extraido":
                print "antes de devolver"
                lote.devolver(user)
                return HttpResponse("Lote Devuelto")
            return HttpResponse("El lote no se puede devolver")
        else:
            return HttpResponse('No es una peticion Ajax')
    else:
        return HttpResponse('No tiene permisos para realizar esta tarea')
Esempio n. 37
0
def login_email_submit(request, redirect_field_name=REDIRECT_FIELD_NAME):
    """
    index page
    :param request:
    :return:
    """

    #Displays the login form and handles the login action.
    redirect_to = request.REQUEST.get(redirect_field_name, '')
    resp = {
        'error': {},
        'success': {'pass': False, 'message': ''},
        'redirect_to': redirect_to,
        'csrfCookie': None
    }
    override_msg = None
    if request.method == "POST" and request.is_ajax():

        data = json.loads(str(request.body, 'utf-8'))
        form = AuthenticationForm(request, data)
        #import ipdb; ipdb.set_trace()
        try:
            if form.is_valid():
                # Ensure the user-originating redirection url is safe.
                if not is_safe_url(url=redirect_to, host=request.get_host()):
                    resp['redirect_to'] = resolve_url(settings.LOGIN_REDIRECT_URL)

                # Okay, security check complete. Log the user in.
                auth_login(request, form.get_user())
                user = form.get_user()
                if user is not None:
                    # the password verified for the user
                    if user.is_active:
                        resp['success']['pass'] = True
                        resp['success']['message'] = "Welcome."
                        # remove once cookie catch is done.
                        resp['csrfToken'] = request.META.get('CSRF_COOKIE')

        except Exception as e:
            override_msg = "An error occurred. Please contact the system admin."
        resp['error'] = form.get_formatted_errors(override_msg=override_msg)

    response = HttpResponse(json.dumps(resp))
    response['Content-Type'] = 'application/json'
    return response
Esempio n. 38
0
def tasks_list(request):
    tasks = TaskModel.objects.all()
    c_tasks = ComplTaskModel.objects.all()

    for c_task in c_tasks:
        for task in tasks:
            if task.checkbox == True:
                # the line below added to not replace existing objects
                c_task = ComplTaskModel(c_task_content='', c_check_list=False)
                #
                c_task.c_task_content = task.task_content
                task.delete()
                c_task.save()
                return HttpResponse(1)
            if c_task.c_check_list == True:
                # the line below added to not replace existing objects
                task = TaskModel(task_content='', checkbox=False)
                #
                task.task_content = c_task.c_task_content
                c_task.delete()
                task.save()
                return HttpResponse(1)

    if request.is_ajax():
        data = request.POST
        present = data['present'] and True or False
        task = TaskModel.objects.get(pk=data['pk'])
        if present == True:
            task.checkbox = True
            task.save()
            return HttpResponse(1)
    else:
        if tasks == False:
            return render(request, 'week_plan.html', {'c_tasks': c_tasks})
        else:
            return render(request, 'week_plan.html', {'tasks': tasks, 'c_tasks': c_tasks})