Example #1
0
def staff_list(request):
    """
    Tests:
        - GETTest
        - SecurityTest
    """
    # User must be staff or admin to get to this page
    if not request.user.is_staff:
        t = loader.get_template('403.html')
        c = RC(request, {})
        return HttpResponseForbidden(t.render(c))
    users = User.objects.all().order_by('last_name')
    page_num = get_number(request.GET, 'page', PAGE_NUM)
    users_per_page = get_number(request.GET, 'per_page', PER_PAGE)
    paginator = Paginator(users, users_per_page)
    try:
        page_of_users = paginator.page(page_num)
    except (EmptyPage, InvalidPage):
        page_of_users = paginator.page(paginator.num_pages)
    if request.GET.get('dir', '') == 'asc': dir = 'desc'
    else: dir = 'asc'
    var_dict = {
        'users': page_of_users,
        'per_page': users_per_page,
        'page': page_num,
        'field': request.GET.get('field', 'any_field'),
        'filter_text': request.GET.get('filter', ''),
        'dir': dir,
    }
    template = 'books/staff.html'
    return rtr(template, var_dict, context_instance=RC(request))
Example #2
0
def selector(request):
    if request.method == 'POST':
        print request.POST
        error = False
        id_error = False
        no_exists = False
        if '_url' in request.POST:
            d = urlUnregistered(request)
            if d['Error'] == 'analyzing':
                return render_to_response('error/analyzing.html', RC(request))
            elif d['Error'] == 'MultiValueDict':
                error = True
                return render_to_response('main/main.html', {'error': error},
                                          RC(request))
            elif d['Error'] == 'id_error':
                id_error = True
                return render_to_response('main/main.html',
                                          {'id_error': id_error}, RC(request))
            elif d['Error'] == 'no_exists':
                no_exists = True
                return render_to_response('main/main.html',
                                          {'no_exists': no_exists},
                                          RC(request))
            else:
                if d["mastery"]["points"] >= 15:
                    return render_to_response(
                        "upload/dashboard-unregistered.html", d)
                elif d["mastery"]["points"] > 7:
                    return render_to_response(
                        "upload/dashboard-unregistered.html", d)
                else:
                    return render_to_response(
                        "upload/dashboard-unregistered.html", d)
    else:
        return HttpResponseRedirect('/')
Example #3
0
def edit_profile(request):
    """
    Allows users to edit their own profile
    
    Tests:
       None yet
    """
    if request.method == 'GET':
        #Show the edit form
        form = UserForm({'email' : request.user.email})
        var_dict = { 'form' : form }
        template = 'users/edit_profile.html'
        return rtr(template, var_dict, context_instance=RC(request))
    elif request.method == 'POST':
        #Apply changes
        form = UserForm(request.POST)
        if form.is_valid():
            request.user.email = form.cleaned_data['email']
            request.user.save()
            return HttpResponseRedirect(reverse('cube.users.views.profile'))
        if not form.is_valid():
            # The form has bad data. send the user back
            var_dict = {'form' : form}
            template = 'users/edit_profile.html'
            return rtr(template, var_dict, context_instance=RC(request))
Example #4
0
def bad_unholds(request):
    """
    Tests:
        - GETTest
        - SecurityTest
    """
    # TODO bad method of identifying the superuser. Start using django's groups
    if not request.user == User.objects.get(pk=1):
        t = loader.get_template('403.html')
        c = RC(request, {})
        return HttpResponseForbidden(t.render(c))
    entries = []
    for book in Book.objects.all():
        logs = Log.objects.filter(book=book)
        for r_log in logs.filter(action='R'):
            bad_actions = ['M', 'P', 'S', 'T', 'D']
            bad_logs = logs.filter(action__in=bad_actions,
                                   when__lte=r_log.when)
            if bad_logs.count() > 0:
                # If a book has been marked as Missing, On Hold, Sold
                # To Be Deleted of Deleted before having a hold removed
                entry = []
                for log in logs:
                    entry.append((log, True if log == r_log else False))
                entries.append(entry)
    var_dict = {
        'entries': entries,
    }
    return rtr('books/admin/bad_unholds.html',
               var_dict,
               context_instance=RC(request))
Example #5
0
def per_status(request):
    """
    Shows the number of books per status
    
    Tests:
        - GETTest
        - SecurityTest
    """
    # User must be staff or admin to get to this page
    if not request.user.is_staff:
        t = loader.get_template('403.html')
        c = RC(request, {})
        return HttpResponseForbidden(t.render(c))
    var_dict = {
        "for_sale": Book.objects.filter(status='F').count(),
        "missing": Book.objects.filter(status='M').count(),
        "on_hold": Book.objects.filter(status='O').count(),
        "seller_paid": Book.objects.filter(status='P').count(),
        "sold": Book.objects.filter(status='S').count(),
        "to_be_deleted": Book.objects.filter(status='T').count(),
        "deleted": Book.objects.filter(status='D').count(),
    }
    return rtr('books/reports/per_status.html',
               var_dict,
               context_instance=RC(request))
Example #6
0
def holds_by_user(request):
    """
    Tests:
        - GETTest
        - SecurityTest
    """
    if request.method == "POST":
        t = loader.get_template('405.html')
        c = RC(request)
        return HttpResponseNotAllowed(t.render(c), ['POST'])
    # User must be staff or admin to get to this page
    if not request.user.is_staff:
        t = loader.get_template('403.html')
        c = RC(request, {})
        return HttpResponseForbidden(t.render(c))
    books_on_hold = Book.objects.filter(status='O')
    user_dict = {}
    for book in books_on_hold:
        if not user_dict.has_key(book.holder):
            user_dict[book.holder] = Book.objects.filter(
                status='O', holder=book.holder).count()
    user_list_by_user = user_dict.items()
    user_list_by_count = []
    for item in user_list_by_user:
        user_list_by_count.append((item[1], item[0]))
    user_list_by_count.sort(reverse=True)
    var_dict = {'user_list': user_list_by_count}
    return rtr('books/reports/holds_by_user.html',
               var_dict,
               context_instance=RC(request))
Example #7
0
def metabook(request, metabook_id):
    """
    Tests:
        - GETTest
        - SecurityTest
    """
    if request.method == "POST":
        t = loader.get_template('405.html')
        c = RC(request)
        return HttpResponseNotAllowed(t.render(c), ['POST'])
    # User must be staff or admin to get to this page
    if not request.user.is_staff:
        t = loader.get_template('403.html')
        c = RC(request, {})
        return HttpResponseForbidden(t.render(c))
    try:
        metabook = MetaBook.objects.get(id=metabook_id)
    except MetaBook.DoesNotExist:
        message = "Invalid MetaBook Ref #: %s" % metabook_id
        return tidy_error(request, message)
    var_dict = {
        'metabook': metabook,
        'books': Book.objects.filter(metabook=metabook).order_by('list_date'),
    }
    return rtr('books/reports/metabook.html',
               var_dict,
               context_instance=RC(request))
Example #8
0
def remove_holds_by_user(request):
    """
    Tests:
        - GETTest
        - SecurityTest
        - NotAllowedTest
    """
    if not request.method == "POST":
        t = loader.get_template('405.html')
        c = RC(request)
        return HttpResponseNotAllowed(t.render(c), ['POST'])
    # User must be staff or admin to get to this page
    if not request.user.is_staff:
        t = loader.get_template('403.html')
        c = RC(request)
        return HttpResponseForbidden(t.render(c))
    for key, value in request.POST.items():
        if "holder_id" == key:
            holder = User.objects.get(pk=int(value))
            break
    books = Book.objects.filter(holder=holder, status='O')
    for book in books:
        Log(action='R', book=book, who=request.user).save()
    var_dict = {'removed': books.count()}
    books.update(status='F', hold_date=None, holder=None)
    template = 'books/update_book/remove_holds.html'
    return rtr(template, var_dict, context_instance=RC(request))
Example #9
0
def user(request, user_id):
    """
    Tests:
        - GETTest
        - SecurityTest
    """
    if request.method == "POST":
        t = loader.get_template('405.html')
        c = RC(request)
        return HttpResponseNotAllowed(t.render(c), ['POST'])
    # User must be staff or admin to get to this page
    if not request.user.is_staff:
        t = loader.get_template('403.html')
        c = RC(request, {})
        return HttpResponseForbidden(t.render(c))
    try:
        user_obj = User.objects.get(id=user_id)
    except User.DoesNotExist:
        user_obj = import_user(user_id)
    if user_obj == None:
        message = "Invalid Student ID: %s" % user_id
        return tidy_error(request, message)
    logs_of_books_for_sale = Log.objects.filter(book__seller=user_obj).filter(
        action='A')
    var_dict = {
        'user_obj': user_obj,
        'logs': Log.objects.filter(who=user_obj).order_by('when'),
        'logs_of_books_for_sale': logs_of_books_for_sale,
    }
    return rtr('books/reports/user.html',
               var_dict,
               context_instance=RC(request))
Example #10
0
def add_book(request):
    """
    Tests:
        - GETTest
        - SecurityTest
    """
    # User must be staff or admin to get to this page
    if not request.user.is_staff:
        t = loader.get_template('403.html')
        c = RC(request)
        return HttpResponseForbidden(t.render(c))
    if request.method == "POST":
        form = BookForm(request.POST)
        if form.is_valid():
            student_id = form.cleaned_data['seller']
            price = form.cleaned_data['price']
            barcode = form.cleaned_data['barcode']
            try:
                metabook = MetaBook.objects.get(barcode=barcode)
            except MetaBook.DoesNotExist:
                initial = {
                    'barcode': barcode,
                    'seller': student_id,
                    'price': price,
                    'edition': '1',
                }
                form = NewBookForm(initial=initial)
                var_dict = {'form': form}
                template = 'books/add_new_book.html'
                return rtr(template, var_dict, context_instance=RC(request))
            try:
                seller = User.objects.get(id=student_id)
            except User.DoesNotExist:
                seller = import_user(student_id)
                if seller == None:
                    message = "Invalid Student ID: %s" % student_id
                    return tidy_error(request, message)
            book = Book(price=price,
                        status="F",
                        metabook=metabook,
                        seller=seller)
            book.save()
            Log(book=book, who=request.user, action='A').save()
            var_dict = {'title': metabook.title, 'book_id': book.id}
            template = 'books/update_book/added.html'
            return rtr(template, var_dict, context_instance=RC(request))
        # the form isn't valid. send the user back.
        var_dict = {'form': form}
        template = 'books/add_book.html'
        return rtr(template, var_dict, context_instance=RC(request))
    else:
        # the user is hitting the page for the first time
        form = BookForm()
        var_dict = {'form': form}
        template = 'books/add_book.html'
        return rtr(template, var_dict, context_instance=RC(request))
Example #11
0
def profile(request):
    """
    Allow users to view their profile
    """
    if not request.method == "GET":
        t = loader.get_template('405.html')
        c = RC(request)
        return HttpResponseNotAllowed(t.render(c), ['GET'])
    template = 'users/profile.html'
    return rtr(template, {}, context_instance=RC(request))
Example #12
0
def staff_edit(request):
    """
    Displays an edit page for user permissions
    If the data needs to be updated (e.g. delete or save)
    then it passes the request on to update_staff

    Tests:
        - GETTest
        - StaffTest
        - SecurityTest
    """
    # User must be staff or admin to get to this page
    if not request.user.is_staff:
        t = loader.get_template('403.html')
        c = RC(request, {})
        return HttpResponseForbidden(t.render(c))
    if request.method == "POST":
        users = []
        too_many = False
        if request.POST.get('Action', '') == "Delete":
            return update_staff(request)
        users = []
        if request.POST.get('Action', '') == "Edit":
            edit = True
            for key, value in request.POST.items():
                if "idToEdit" in key:
                    users.append(User.objects.get(id=value))
            if len(users) > 1: too_many = True
            if len(users) == 0:
                # They clicked edit without selecting any users. How silly.
                return staff_list(request)
        else:
            users.append(User())
            edit = False
    else:
        too_many = False
        users = [User()]
        edit = False
    var_dict = {
        'edit': edit,
        'too_many': too_many,
        'name': users[0].get_full_name(),
        'student_id': users[0].id,
        'email': users[0].email,
        'current_role': 'admin' if users[0].is_superuser else 'staff'
    }
    template = 'books/staff_edit.html'
    return rtr(template, var_dict, context_instance=RC(request))
Example #13
0
def update_user(request, user_id=None):
    user = get_object_or_404(User,
                             userprofile__supervisor=request.user,
                             pk=user_id)
    if request.POST:
        user_form = UserUpdateForm(request.POST)
        if user_form.is_valid():
            # create the user and update profile information
            user.first_name = user_form.cleaned_data['first_name']
            user.last_name = user_form.cleaned_data['last_name']
            user.email = user_form.cleaned_data['email']
            if user_form.cleaned_data['password']:
                user.set_password(user_form.cleaned_data['password'])
            user.save()

            request.flash.now['notice'] = "Teller successfully updated!"
            user_form = UserUpdateForm()
        else:
            errors_list = [
                user_form.errors[key] for key in user_form.errors.keys()
            ]
            error_messages = ["<br />".join(x) for x in errors_list]
            error_messages = "<br />".join(error_messages)
            request.flash.now['error'] = error_messages
    else:
        user_form = UserUpdateForm()
    context = {'form': user_form}
    context['user'] = user

    return render_to_response("webapp/update_user.html",
                              context,
                              context_instance=RC(request))
Example #14
0
def update_transaction(request, tpin=None):
    qs = Q(financial_institution=None) | Q(
        financial_institution=request.user.get_profile().financial_institution)
    txn = get_object_or_404(Transaction.objects.filter(qs), tpin=tpin)
    context = {'page_title': 'Update Transactions'}
    if request.POST:
        update_form = TransactionUpdateForm(request.POST, instance=txn)
        if update_form.is_valid():
            update_form.save()

            # update the financial institution of the transaction to that of the editor
            txn.financial_institution = request.user.get_profile(
            ).financial_institution
            txn.save()

            # attached a success message to the flash
            request.flash.now['notice'] = "Transaction updated."
            return HttpResponseRedirect(reverse('search-txn'))
        else:
            # form is invalid
            print update_form.errors
            request.flash.now[
                'error'] = "The update wasn't made due to some errors in the form"
    else:
        update_form = TransactionUpdateForm(instance=txn)
    context['txn'] = txn
    context['form'] = update_form
    return render_to_response("webapp/update_transaction.html",
                              context,
                              context_instance=RC(request))
Example #15
0
def self_view(request):
    if request.method == 'GET':
        try:
            followed = FollowRelation.objects.filter(user=request.user)[:12]
            follower = FollowRelation.objects.filter(
                follower=request.user)[:12]
        except:
            followed = 0
            follower = 0
        topics_all = Topic.objects.filter(
            Q(author=request.user)
            | Q(conversation__author=request.user)).order_by('-created')
        topics_count = topics_all.count()
        members = Member.objects.all()
        paginator = Paginator(topics_all, 10)
        try:
            page = int(request.GET.get('page', '1'))
        except ValueError:
            page = 1
        try:
            topics = paginator.page(page)
        except (EmptyPage, InvalidPage):
            topics = paginator.page(paginator.num_pages)

    return render_to_response("self.html", {
        'topics': topics,
        'members': members,
        'paginator': paginator,
        'follower': follower,
        'followed': followed,
        'page_type': 'self',
        'view_user': request.user,
        'has_side': True,
    },
                              context_instance=RC(request))
Example #16
0
def add_user(request):
    if request.POST:
        user_form = UserCreationForm(request.POST)
        if user_form.is_valid():
            # create the user and update profile information
            user = User.objects.create_user(user_form.cleaned_data['username'],
                                            user_form.cleaned_data['email'],
                                            user_form.cleaned_data['password'])
            user.first_name = user_form.cleaned_data['first_name']
            user.last_name = user_form.cleaned_data['last_name']
            user.save()
            profile = user.get_profile()
            profile.supervisor = request.user
            profile.financial_institution = request.user.get_profile(
            ).financial_institution
            profile.save()

            request.flash.now['notice'] = "Teller successfully created!"
            user_form = UserCreationForm()
        else:
            errors_list = [
                user_form.errors[key] for key in user_form.errors.keys()
            ]
            error_messages = ["<br />".join(x) for x in errors_list]
            error_messages = "<br />".join(error_messages)
            request.flash.now['error'] = error_messages
    else:
        user_form = UserCreationForm()

    return render_to_response("webapp/add_user.html", {'form': user_form},
                              context_instance=RC(request))
Example #17
0
def menu(request):
    """
    Tests:
        - GETTest
        - SecurityTest
    """
    # User must be staff or admin to get to this page
    if not request.user.is_staff:
        t = loader.get_template('403.html')
        c = RC(request, {})
        return HttpResponseForbidden(t.render(c))
    var_dict = {
        'date_range_form': DateRangeForm(),
    }
    return rtr('books/reports/menu.html',
               var_dict,
               context_instance=RC(request))
Example #18
0
def myRoles(request):
    """Show the roles in Doctor Scratch"""
    if request.user.is_authenticated():
        user = request.user.username
        return render_to_response("myRoles/content-roles.html",
                                  context_instance=RC(request))
    else:
        return HttpResponseRedirect("/")
Example #19
0
def edit_setting(request, setting_id):
    """
    This view is used to update the values for an Application Setting
    
    Tests:
        - GETTest
        - SecurityTest
    """

    if request.method == "POST":
        t = loader.get_template('405.html')
        c = RC(request)
        return HttpResponseNotAllowed(t.render(c), ['POST'])

    # User must be staff or admin to get to this page
    if not request.user.is_staff:
        t = loader.get_template('403.html')
        c = RC(request, {})
        return HttpResponseForbidden(t.render(c))
    try:
        setting_obj = AppSetting.objects.get(id=setting_id)
    except AppSetting.DoesNotExist:
        # We need at least 1 thing to edit, otherwise bad things can happen
        var_dict = {
            'message': "Didn't get any settings to process",
        }
        t = loader.get_template('400.html')
        c = RC(request, var_dict)
        return HttpResponseBadRequest(t.render(c))

    initial = {
        'name': setting_obj.name,
        'value': setting_obj.value,
        'description': setting_obj.description,
    }

    form = SettingForm(initial)
    var_dict = {
        'form': form,
        'name': setting_obj.name,
        'value': setting_obj.value,
        'description': setting_obj.description,
        'id': setting_obj.id,
    }
    template = 'appsettings/update/edit.html'
    return rtr(template, var_dict, context_instance=RC(request))
Example #20
0
def books_sold_within_date(request):
    """
    Shows a list of all books sold within a given date range
    
    Test:
        - GETTest
        - SecurityTest
    """
    if not request.method == "POST":
        t = loader.get_template('405.html')
        c = RC(request)
        return HttpResponseNotAllowed(t.render(c), ['POST'])
    # User must be staff or admin to get to this page
    if not request.user.is_staff:
        t = loader.get_template('403.html')
        c = RC(request, {})
        return HttpResponseForbidden(t.render(c))
    date_range_form = DateRangeForm(request.POST)
    if not date_range_form.is_valid():
        var_dict = {
            'date_range_form': date_range_form,
        }
        return rtr('books/reports/menu.html',
                   var_dict,
                   context_instance=RC(request))

    to_date = date_range_form.cleaned_data['to_date']
    from_date = date_range_form.cleaned_data['from_date']
    book_sale_logs = Log.objects.filter(
        action='S', when__gte=from_date).exclude(when__gt=to_date)

    # Find all the books for the related Logs
    books_sold = Book.objects.filter(id__in=book_sale_logs.values('book_id'))

    # Sum up the price of all the books retrieved previously
    total_money = books_sold.aggregate(total=Sum('price'))['total']

    var_dict = {
        'book_sale_logs': book_sale_logs.order_by('book__sell_date'),
        'total_money': total_money,
        'from_date': from_date,
        'to_date': to_date,
    }
    return rtr('books/reports/books_sold_within_date.html',
               var_dict,
               context_instance=RC(request))
Example #21
0
def attach_book(request):
    """
    Tests:
        - GETTest
        - SecurityTest
        - NotAllowedTest
    """
    # User must be staff or admin to get to this page
    if not request.user.is_staff:
        t = loader.get_template('403.html')
        c = RC(request)
        return HttpResponseForbidden(t.render(c))
    if not request.method == 'POST':
        t = loader.get_template('405.html')
        c = RC(request)
        return HttpResponseNotAllowed(t.render(c), ['POST'])
    form = NewBookForm(request.POST)
    if not form.is_valid():
        # The form has bad data. send the user back
        var_dict = {'form': form}
        template = 'books/attach_book.html'
        return rtr(template, var_dict, context_instance=RC(request))
    # shorten our code line lengths below
    goc = Course.objects.get_or_create
    cd = form.cleaned_data

    # Get the course if it exists, otherwise create it.
    tpl = goc(department=cd['department'], number=cd['course_number'])
    course = tpl[0]

    metabook = MetaBook()
    metabook.title = form.cleaned_data['title']
    metabook.author = form.cleaned_data['author']
    metabook.barcode = form.cleaned_data['barcode']
    metabook.edition = form.cleaned_data['edition']
    metabook.save()
    metabook.courses.add(course)
    metabook.save()

    book = Book.objects.get(pk=form.cleaned_data['book_id'])
    book.metabook = metabook
    book.save()
    var_dict = {'book': book}
    template = 'books/attached.html'
    return rtr(template, var_dict, context_instance=RC(request))
Example #22
0
def save_setting(request):
    """
    Applies changes to an AppSetting on the edit page
    
    Tests:
    """
    if not request.method == "POST":
        t = loader.get_template('405.html')
        c = RC(request)
        return HttpResponseNotAllowed(t.render(c), ['POST'])
    # User must be staff or admin to get to this page
    if not request.user.is_staff:
        t = loader.get_template('403.html')
        c = RC(request)
        return HttpResponseForbidden(t.render(c))
    form = SettingForm(request.POST)
    if form.is_valid():
        id_to_edit = request.POST.get('IdToEdit')
        try:
            setting = AppSetting.objects.get(id=id_to_edit)
        except AppSetting.DoesNotExist:
            message = 'Application Setting with ref# "%s" does not exist' % id_to_edit
            return tidy_error(request, message)

        setting.name = form.cleaned_data['name']
        setting.value = form.cleaned_data['value']
        setting.description = form.cleaned_data['description']
        setting.save()

        var_dict = {'appsetting': setting}
        template = 'appsettings/update/edited.html'
        return rtr(template, var_dict, context_instance=RC(request))

    elif request.POST.get('IdToEdit'):
        # form isn't valid, but we have an id to work with. send user back
        id_to_edit = request.POST.get('IdToEdit')
        var_dict = {
            'form': form,
            #            'too_many' : False,
            'id': id_to_edit,
            #            'logs' : Log.objects.filter(setting=id_to_edit),
        }

        template = 'appsettings/update/edit.html'
        return rtr(template, var_dict, context_instance=RC(request))
Example #23
0
def book_list(request):
    """
    Shows a list of all the books listed.
    Does pagination, sorting and filtering.
    
    Tests:
        - GETTest
        - SearchBookTest
        - SortBookTest
    """
    house_cleaning()
    # Filter for the search box
    if request.method == 'GET':
        filter_form = FilterForm(request.GET)
        if filter_form.is_valid():
            cd = filter_form.cleaned_data
            all_books = Book.objects.all()
            books = book_filter(cd['filter'], cd['field'], all_books)
        elif request.GET.has_key("sort_by") and request.GET.has_key("dir"):
            books = book_sort(request.GET["sort_by"], request.GET["dir"])
        else:
            books = Book.objects.all()

    # Filter according to permissions
    if not request.user.is_staff:
        # Non staff can only see books which are for sale.
        books = filter(lambda x: x.status == 'F', books)
    # Staff want to see the unsold books first so if we sort them ascending, that should do
    else:
        # This alphabet is the order in which book statuses should be displayed
        alphabet = "AFOPMTSD"
        # Sort by the index value of the book status in the alphabet
        books = sorted(books, key=lambda book: [alphabet.index(book.status)])

    # Pagination
    page_num = get_number(request.GET, 'page', PAGE_NUM)
    books_per_page = get_number(request.GET, 'per_page', PER_PAGE)

    paginator = Paginator(books, books_per_page)
    try:
        page_of_books = paginator.page(page_num)
    except (EmptyPage, InvalidPage):
        page_of_books = paginator.page(paginator.num_pages)

    # Template time
    if request.GET.get('dir', '') == 'asc': dir = 'desc'
    else: dir = 'asc'
    var_dict = {
        'books': page_of_books,
        'per_page': books_per_page,
        'page': page_num,
        'field': request.GET.get('field', 'any_field'),
        'filter_text': request.GET.get('filter', ''),
        'dir': dir
    }
    return rtr('books/book_list.html', var_dict, context_instance=RC(request))
Example #24
0
def main(request):
    """Main page"""
    if request.user.is_authenticated():
        user = request.user.username
    else:
        user = None
    # The first time one user enters
    # Create the dashboards associated to users
    createDashboards()
    return render_to_response('main/main.html', {'user': user}, RC(request))
Example #25
0
def myHistoric(request):
    """Show the progress in the application"""
    if request.user.is_authenticated():
        user = request.user.username
        mydashboard = Dashboard.objects.get(user=user)
        projects = mydashboard.project_set.all()
        return render_to_response("myHistoric/content-historic.html",
                                  {'projects': projects},
                                  context_instance=RC(request))
    else:
        return HttpResponseRedirect("/")
Example #26
0
def myProjects(request):
    """Show all projects of dashboard"""
    if request.user.is_authenticated():
        user = request.user.username
        mydashboard = Dashboard.objects.get(user=user)
        projects = mydashboard.project_set.all()
        return render_to_response("myProjects/content-projects.html",
                                  {'projects': projects},
                                  context_instance=RC(request))
    else:
        return HttpResponseRedirect("/")
Example #27
0
def createUser(request):
    """Method for to sign up in the platform"""
    logout(request)
    if request.method == "POST":
        form = NewUserForm(request.POST)
        if form.is_valid():
            nickName = form.cleaned_data['nickname']
            emailUser = form.cleaned_data['emailUser']
            passUser = form.cleaned_data['passUser']
            user = User.objects.create_user(nickName, emailUser, passUser)
            return render_to_response("profile.html", {'user': user},
                                      context_instance=RC(request))
Example #28
0
def metabook_list(request):
    """
    List all metabooks in the database
    
    Tests:
        - GETTest
        - SecurityTest
    """
    # User must be staff or admin to get to this page
    if not request.user.is_staff:
        t = loader.get_template('403.html')
        c = RC(request)
        return HttpResponseForbidden(t.render(c))
    if request.GET.has_key("sort_by") and request.GET.has_key("dir"):
        metabooks = metabook_sort(request.GET["sort_by"], request.GET["dir"])
    else: metabooks = MetaBook.objects.all()

    # Pagination
    page_num = get_number(request.GET, 'page', PAGE_NUM)
    metabooks_per_page = get_number(request.GET, 'per_page', PER_PAGE)

    paginator = Paginator(metabooks, metabooks_per_page)
    try:
        page_of_metabooks = paginator.page(page_num)
    except (EmptyPage, InvalidPage):
        page_of_metabooks = paginator.page(paginator.num_pages)

    # Template time
    if request.GET.get('dir', '') == 'asc': dir = 'desc'
    else: dir = 'asc'
    var_dict = {
        'metabooks' : page_of_metabooks,
        'per_page' : metabooks_per_page,
        'page' : page_num,
        'dir' : 'desc' if request.GET.get('dir', '') == 'asc' else 'asc'
    }

    template = 'books/list_metabooks.html'
    return rtr(template, var_dict, context_instance=RC(request))
Example #29
0
def signup_view(request):
  if request.method == 'POST':
    form = MyUserCreationForm(request.POST)
    if form.is_valid():
      new_user = form.save()
      new_user.backend="%s.%s" %('django.contrib.auth.backends','ModelBackend')
      auth.login(request, new_user)
      return HttpResponseRedirect("/")
  else:
    form = MyUserCreationForm()
  return render_to_response("signup.html", {
  'form': form,
  },context_instance=RC(request))
Example #30
0
def setting_list(request):
    """
    Shows a list of all the application settings.
    Does pagination, sorting and filtering.
    
    Tests:
    """
    house_cleaning()
    # Filter for the search box
    if request.method == 'GET':
        filter_form = FilterForm(request.GET)
        if filter_form.is_valid():
            cd = filter_form.cleaned_data
            all_settings = AppSetting.objects.all()
            settings = settings_filter(cd['filter'], cd['field'], all_settings)
        elif request.GET.has_key("sort_by") and request.GET.has_key("dir"):
            settings = setting_sort(request.GET["sort_by"], request.GET["dir"])
        else:
            settings = AppSetting.objects.all()


# This filter for permissions was copied from the books view but probably isn't needed here
# Filter according to permissions
#    if not request.user.is_staff:
# Non staff can only see books which are for sale.
#        books = filter(lambda x: x.status == 'F', books)

# Pagination
    page_num = get_number(request.GET, 'page', PAGE_NUM)
    settings_per_page = get_number(request.GET, 'per_page', PER_PAGE)

    paginator = Paginator(settings, settings_per_page)
    try:
        page_of_settings = paginator.page(page_num)
    except (EmptyPage, InvalidPage):
        page_of_settings = paginator.page(paginator.num_pages)

    # Template time
    if request.GET.get('dir', '') == 'asc': dir = 'desc'
    else: dir = 'asc'
    var_dict = {
        'appsettings': page_of_settings,
        'per_page': settings_per_page,
        'page': page_num,
        'field': request.GET.get('field', 'any_field'),
        'filter_text': request.GET.get('filter', ''),
        'dir': dir
    }
    return rtr('appsettings/settings_list.html',
               var_dict,
               context_instance=RC(request))