def deleteGroup(request,group_id): group_found = None try: group = Group.objects.get(id=group_id) group_found = True really_delete = int(request.POST.get("really_delete", False)) if really_delete == True: group.delete() deleted = True else: deleted=False return render( request, "almsGroups/deleteGroup.html", context = addGlobalContext( { "deleted": deleted, "group": group })) except ObjectDoesNotExist: return render( request, "almsGroups/deleteGroup.html", context = addGlobalContext( { "group_found": group_found }))
def search_member(request): ''' searches the users based on their username only note : Does not attributes other than usernames ''' config.refresh() username = request.GET.get("username", None) if username not in [None, "", "None"]: user = ModUser.objects.filter(username=username) if user.count() == 1: user = user[0] return HttpResponseRedirect( reverse('profile', kwargs={"username": user.username})) else: users = ModUser.objects.filter(username__contains=username) return render( request, 'account/search_user.html', addGlobalContext( {'not_found': True, "users": users, 'username': username} ) ) else: return render( request, 'account/search_user.html', addGlobalContext())
def profile(request, username): ''' this view takes the unique username designated to each user, and displays the user.html with the users data in place. ''' config.refresh() user = get_object_or_404(ModUser, username=username) books_borrowed = Lend.objects.filter(user=user, returned=False) len_books_borrowed = books_borrowed.count() books_saved_by_date = [] if user.is_staff: dates =set() books_saved = BookSaver.objects.filter(user__username=username) len_books_saved = books_saved.count() else: len_books_saved = 0 return render( request, 'account/user.html', addGlobalContext( { 'globals': config, 'date': datetime.date.today(), 'search_user': user, 'books_borrowed': books_borrowed, 'len_books_borrowed': len_books_borrowed, 'len_books_saved': len_books_saved, } ))
def home(request): config = Globals() context = {'config': config} if request.method == "POST": settings = request.POST org_long_name = settings.get("org_long_name", None) org_short_name = settings.get("org_short_name", None) org_motto = settings.get("org_motto", None) late_fees_price = settings.get("late_fees_price", None) max_books_borrow_days = settings.get("max_books_borrow_days", None) membership_valid_days = settings.get("membership_valid_days", None) config = Globals() if org_long_name is not None: config.add("alms", "org_long_name", org_long_name) if org_short_name is not None: config.add("alms", "org_short_name", org_short_name) if org_motto is not None: config.add("alms", "org_motto", org_motto) if late_fees_price is not None: config.add("misc", "late_fees_price", late_fees_price) if max_books_borrow_days is not None: config.add("books", "borrow_max_days", max_books_borrow_days) if membership_valid_days is not None: config.add("misc", "membership_valid_days", membership_valid_days) return HttpResponseRedirect(reverse("settingsHome")) return render(request, "settings/home.html", addGlobalContext(context))
def deleteBookConfirm(request, id): config.reload() if id.isdigit(): book = Book.objects.filter(id=id, state=0) len_book = book.count() if len_book == 0 or len_book > 1: context_dict = { "state": -1, "message": "The No. of book With ID `{}` Was not 1".format(id), } else: context_dict = { "state": 0, "message": "Are You Sure You want to delete this Book?", "book": book[0] } else: context_dict = { "state": -1, "message": "The Accession Number `{}` Is Invalid".format(accNo) } context_dict.update(GLOBAL_CONTEXT) return render(request, "head/delete_book.html", addGlobalContext(context_dict))
def deleteBook(request, id): config.reload() book = Book.objects.get(id=id) book.discard() context_dict = {"book": book} context_dict.update(GLOBAL_CONTEXT) return render(request, "head/deleted_book.html", addGlobalContext(context_dict))
def homeWithArgs(request,group_added,group_name): all_groups = Group.objects.order_by("-id") context = addGlobalContext({ "all_groups": all_groups, "group_added": False, "group_name": group_name }) return render(request,'almsGroups/home.html',context=context)
def homeWithArgs(request, group_added, group_name): all_groups = Group.objects.order_by("-id") context = addGlobalContext({ "all_groups": all_groups, "group_added": False, "group_name": group_name }) return render(request, 'almsGroups/home.html', context=context)
def about(request): config.reload() about_template = "head/about.html" return render( request, about_template, addGlobalContext({ "body_code": RestructuredText.objects.get(name="homeBody").get_html() }))
def addWorkerWithArgs(request, created): ''' a worker is an employee to the library - could be a staff member, a volunteer, an intern etc. A worker is added to a certain group on registration and is given a unique ID. ''' config.refresh() form = CreateWorkerForm() member = None if request.method == "POST": form = CreateWorkerForm(request.POST) if form.is_valid(): # the form is valid, so lets create the member data = form.cleaned_data if (data['first_name'] == '' and data['last_name'] == '') or data['password'] == '': created = False else: first_name =smart_str( data['first_name'].strip(" ").lower()) last_name = smart_str(data['last_name'].strip(" ").lower()) gender = smart_str(data['gender'].strip(' ').lower()) date_of_birth = data['date_of_birth'] group = data['group'] password = data['password'] # creating the username username = create_username(first_name, ModUser.objects.all().count()) worker = ModUser.objects.create( username=username ) if first_name not in ['']: worker.first_name = first_name if last_name not in ['']: worker.last_name = last_name if gender not in ['']: worker.sex = gender if date_of_birth not in ['']: worker.date_of_birth = date_of_birth if group not in ['']: group_grp = Group.objects.filter(name=group) if len(group_grp) == 1: worker.groups.add(group_grp[0]) # school_number and telephone_mobile are not added worker.is_staff = True worker.set_password(password) worker.save() created = True return HttpResponseRedirect(reverse("addWorkerWithArgs", kwargs={"created": created})) return render(request, "account/create_worker.html", context=addGlobalContext({ "form": form, "worker_created": created, "worker": ModUser.objects.order_by("-date_joined")[0] }) )
def return_check_fees(request): config.reload() bookID = request.GET.get("bookID", None) if request.method == "POST": bookID = request.POST.get("bookID", None) if bookID is None: return HttpResponseNotFound() else: book = get_object_or_404(Book, accession_number=bookID) lends = Lend.objects.filter(book=book) # code to return book for _ in lends: _.set_returned() return render( request, 'head/return.html', addGlobalContext({ 'code': "book_returned", 'lend_obj': lends[0] })) if bookID is None: return render(request, 'head/return.html', addGlobalContext({'code': 'None'})) books = Book.objects.filter(accession_number=bookID) if books.count() != 1: return render( request, 'head/return.html', addGlobalContext({ 'code': "not_found", 'accession_number': bookID })) else: lend_obj = Lend.objects.filter(book__accession_number=bookID, returned=False) if lend_obj.count() == 1: lend_obj = lend_obj[0] late_fees = lend_obj.get_late_fees() return render( request, 'head/return.html', addGlobalContext({ 'code': 'success', 'lend_obj': lend_obj, 'late_fees': late_fees, 'has_late_fees': late_fees == 0 }))
def list_all_workers(request): config.refresh() workers = ModUser.objects.filter(is_staff=True) return render( request, 'account/workers.html', addGlobalContext({ 'globals': config, 'date': datetime.date.today(), 'workers': workers }))
def addWorkerWithArgs(request, created): config.refresh() form = CreateWorkerForm() member = None if request.method == "POST": form = CreateWorkerForm(request.POST) if form.is_valid(): # the form is valid, so lets create the member data = form.cleaned_data if (data['first_name'] == '' and data['last_name'] == '') or data['password'] == '': created = False else: first_name = smart_str(data['first_name'].strip(" ").lower()) last_name = smart_str(data['last_name'].strip(" ").lower()) gender = smart_str(data['gender'].strip(' ').lower()) date_of_birth = data['date_of_birth'] group = data['group'] password = data['password'] # creating the username username = create_username(first_name, ModUser.objects.all().count()) worker = ModUser.objects.create(username=username) if first_name not in ['']: worker.first_name = first_name if last_name not in ['']: worker.last_name = last_name if gender not in ['']: worker.sex = gender if date_of_birth not in ['']: worker.date_of_birth = date_of_birth if group not in ['']: group_grp = Group.objects.filter(name=group) if len(group_grp) == 1: worker.groups.add(group_grp[0]) # school_number and telephone_mobile are not added worker.is_staff = True worker.set_password(password) worker.save() created = True return HttpResponseRedirect( reverse("addWorkerWithArgs", kwargs={"created": created})) return render(request, "account/create_worker.html", context=addGlobalContext({ "form": form, "worker_created": created, "worker": ModUser.objects.order_by("-date_joined")[0] }))
def login_user(request): config.refresh() ''' code values and their meaning : 0 : Login Successful 1 : User is Not Active! Accoutn disabled 2 : Invalid Login creds! 3 : Request was not POST ( It was GET (maybe) ) 4 : request wasn't either GET or POST ''' code = None LOGIN_SUCCESS = 0 USER_NOT_ACTIVE = 1 INVALID_LOGIN_CREDS = 2 METHOD_NOT_POST = 3 NO_DATA_GIVEN = 4 if request.user.is_authenticated(): # user is already logged in return HttpResponseRedirect(reverse("home")) if request.method.upper() == "POST": username = unicode(request.POST.get("username", None)) password = unicode(request.POST.get("password", None)) user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) code = LOGIN_SUCCESS else: code = USER_NOT_ACTIVE # user is not active else: code = INVALID_LOGIN_CREDS # invalid login creds else: usrnme = unicode(request.POST.get("username", None)) passwd = unicode(request.POST.get("password", None)) print usrnme, passwd if unicode(request.POST.get('username', None)) is not None or unicode( request.POST.get("password", None)) is not None: code = NO_DATA_GIVEN # request method was not POST else: code = METHOD_NOT_POST if code is not LOGIN_SUCCESS: # error occured during login proc. return render( request, "account/login.html", addGlobalContext({ 'code': code, "code_msg": login_get_code_msg(code), })) else: return HttpResponseRedirect(request.GET.get("next", reverse("home")))
def writeHomeBody(request): homeBody = RestructuredText.objects.get(name="homeBody") context = {"body": homeBody.get_rst()} if request.method == "POST": rst = request.POST.get("rst", None) if rst is not None: homeBody.set_rst(smart_str(rst)) homeBody.save() return HttpResponseRedirect(reverse("writeHomeBody")) return render(request, "restructuredText/editHomePage.html", context=addGlobalContext(context))
def showJournal(request, year, month): year = int(year) month = int(month) month = min(month, 12) #the value of month cannot be greater than 12 date = datetime.date(year, month, 1) date_str = date.strftime("%B of %Y") context = addGlobalContext() context.update({"day": date}) return render(request, "ledger/journalDay.html", context)
def login_user(request): ''' Logs a user in by taking their username and password code values and their meaning : 0 : Login Successful 1 : User is Not Active! Accoutn disabled 2 : Invalid Login creds! 3 : Request was not POST ( It was GET (maybe) ) 4 : request wasn't either GET or POST ''' config.refresh() code = None LOGIN_SUCCESS = 0 USER_NOT_ACTIVE = 1 INVALID_LOGIN_CREDS = 2 METHOD_NOT_POST = 3 NO_DATA_GIVEN = 4 if request.user.is_authenticated(): # user is already logged in return HttpResponseRedirect(reverse("home")) if request.method.upper() == "POST": username = unicode(request.POST.get("username", None)) password = unicode(request.POST.get("password", None)) user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) code = LOGIN_SUCCESS else: code = USER_NOT_ACTIVE # user is not active else: code = INVALID_LOGIN_CREDS # invalid login creds else: usrnme = unicode(request.POST.get("username", None)) passwd = unicode(request.POST.get("password", None)) print usrnme, passwd if unicode(request.POST.get('username', None)) is not None or unicode(request.POST.get("password", None)) is not None: code = NO_DATA_GIVEN # request method was not POST else: code = METHOD_NOT_POST if code is not LOGIN_SUCCESS: # error occured during login proc. return render(request, "account/login.html", addGlobalContext({'code': code, "code_msg": login_get_code_msg(code), })) else: return HttpResponseRedirect(request.GET.get("next", reverse("home")))
def search_member(request): config.refresh() import string username = request.GET.get("username", None) if username not in [None, "", "None"]: user = ModUser.objects.filter(username=username) if user.count() == 1: user = user[0] return HttpResponseRedirect( reverse('profile', kwargs={"username": user.username})) else: users = ModUser.objects.filter(username__contains=username) return render( request, 'account/search_user.html', addGlobalContext({ 'not_found': True, "users": users, 'username': username })) else: return render(request, 'account/search_user.html', addGlobalContext())
def deleteGroup(request, group_id): group_found = None try: group = Group.objects.get(id=group_id) group_found = True really_delete = int(request.POST.get("really_delete", False)) if really_delete == True: group.delete() deleted = True else: deleted = False return render(request, "almsGroups/deleteGroup.html", context=addGlobalContext({ "deleted": deleted, "group": group })) except ObjectDoesNotExist: return render(request, "almsGroups/deleteGroup.html", context=addGlobalContext({"group_found": group_found}))
def writeHomeBody(request): homeBody = RestructuredText.objects.get(name="homeBody") context = { "body": homeBody.get_rst() } if request.method == "POST": rst = request.POST.get("rst", None) if rst is not None: homeBody.set_rst(smart_str(rst)) homeBody.save() return HttpResponseRedirect(reverse("writeHomeBody")) return render(request, "restructuredText/editHomePage.html", context=addGlobalContext(context))
def dashboard(request): import calendar config.reload() logged_in = request.META.get('logged_in', None) today = datetime.date.today() start_date = today - datetime.timedelta(days=TIME_PERIOD * 30) # problem, the _gte filter with `today' excludes the data entered on today...fix this time_period = today - start_date members_added_during_tp = ModUser.objects.exclude( date_joined__gte=today).filter(date_joined__gte=start_date) total_members = ModUser.objects.all() books_cataloged_during_tp = Book.objects.exclude( accessioned_date__gte=today).filter(accessioned_date__gte=start_date, state=0) recently_added_books = list( Book.objects.filter(state=0, accessioned_date=datetime.date.today()).order_by( "-accessioned_date"))[:20] recently_added_books.reverse() total_books = Book.objects.all() return render( request, "head/dashboard.html", addGlobalContext({ "members_added_during_tp": members_added_during_tp, "members_added_before_tp": total_members.exclude(date_joined__gte=start_date), 'total_members': total_members, 'books_cataloged_during_tp': books_cataloged_during_tp, 'books_cataloged_before_tp': total_books.exclude(accessioned_date__gte=start_date), 'total_books': total_books, 'time_period': time_period.days / 30, 'start_date': start_date, 'recently_added_books': recently_added_books, 'recently_added_members': ModUser.objects.order_by("-date_joined"), 'logged_in': logged_in }))
def showJournal(request,year,month): year = int(year) month = int(month) month = min(month,12) #the value of month cannot be greater than 12 date = datetime.date(year,month,1) date_str= date.strftime("%B of %Y") context = addGlobalContext() context.update({ "day": date }) return render(request, "ledger/journalDay.html",context)
def delete_field(request, field_id): state = 1 field = GenericField.objects.get(id=field_id) if request.method.upper() == "POST": delete = request.POST.get("delete", None) if delete is None: pass else: field.delete() state = 0 return HttpResponseRedirect(reverse("miscFieldsHome")) return render(request, "miscFields/delete_field.html", addGlobalContext({ "state": state, "field": field }))
def profile(request, username): config.refresh() user = get_object_or_404(ModUser, username=username) books_borrowed = Lend.objects.filter(user=user, returned=False) len_books_borrowed = books_borrowed.count() books_saved_by_date = [] if user.is_staff: dates = set() books_saved = BookSaver.objects.filter(user__username=username) len_books_saved = books_saved.count() else: len_books_saved = 0 return render( request, 'account/user.html', addGlobalContext({ 'globals': config, 'date': datetime.date.today(), 'search_user': user, 'books_borrowed': books_borrowed, 'len_books_borrowed': len_books_borrowed, 'len_books_saved': len_books_saved, }))
def editGroup(request, group_id): all_perms = Permission.objects.filter(Q(codename__contains="Book")|Q(codename__contains="ModUser")|Q(codename="add_lend")) if request.method == "POST": name = request.POST.get("name", None) if name != None: if group_id == None: groups = Group.objects.filter(name=name) else: groups = Group.objects.filter(id=group_id) groups[0].permissions.clear() if len(groups) > 0: group_exists = True else: group_exists = False permissions = {} for perm in all_perms: permissions[perm.codename] = request.POST.get("perm_"+perm.codename,False) if group_exists is False: group = Group.objects.create(name=name) else: group = groups[0] group.name = name for perm in permissions.items(): if perm[1] is not False: try: group.permissions.get(codename=perm[0]) except ObjectDoesNotExist: perm_spl = perm[0].split("_") if perm_spl[1].lower() == "book": group.permissions.add(Permission.objects.get(codename=perm_spl[0]+"_author")) group.permissions.add(Permission.objects.get(codename=perm_spl[0]+"_publisher")) group.permissions.add(Permission.objects.get(codename=perm_spl[0]+"_gifter")) elif perm_spl[1].lower() == "moduser": group.permissions.add(Permission.objects.get(codename=perm_spl[0]+"_usertype")) group.permissions.add(Permission.objects.get(codename=perm[0])) group.save() group_added = True else: group_added = False ## name is None else: group_added = None ## POST Request not sent if group_added is True: return HttpResponseRedirect(reverse("almsGroupsHomeWithArgs", kwargs={"group_added":int(True),"group_name":smart_str(group.name) })) elif group_added is False: context = addGlobalContext({ "all_permissions": all_perms, 'group_added': int(group_added), 'group': group }) else: if group_id is not None: try: found_group = Group.objects.get(id=group_id) except ObjectDoesNotExist: found_group = None else: found_group=None context = addGlobalContext({ "all_permissions": all_perms, "found_group": found_group }) return render(request, 'almsGroups/new.html', context=context)
def addMemberWithArgs(request, created): config.refresh() form = CreateMemberForm() member = None if request.method == "POST": form = CreateMemberForm(request.POST) if form.is_valid(): # the form is valid, so lets create the member data = form.cleaned_data if data['first_name'] == '' and data['last_name'] == '': created = False else: first_name = smart_str(data['first_name'].strip(" ").lower()) last_name = smart_str(data['last_name'].strip(" ").lower()) gender = smart_str(data['gender'].strip(' ').lower()) ward_no = smart_str(data['ward_no'].strip(' ').lower()) tole = smart_str(data['tole'].strip(' ').lower()) city = smart_str(data['city'].strip(' ').lower()) home_phone = smart_str(data['home_phone'].strip(' ').lower()) parent_name = smart_str(data['parent_name'].strip(' ').lower()) school_name = smart_str(data['school_name'].strip(' ').lower()) school_class = smart_str( data['school_class'].strip(' ').lower()) school_number = data['school_number'] telephone_mobile = data['telephone_mobile'] roll_no = smart_str(data['roll_no'].strip(' ').lower()) date_of_birth = data['date_of_birth'] date_of_expiration = data['date_of_expiration'] ## creating the username username = create_username(first_name, last_name, ModUser.objects.all().count()) member = ModUser.objects.create(username=username) if first_name not in ['']: member.first_name = first_name if last_name not in ['']: member.last_name = last_name if gender not in ['']: member.gender = gender if ward_no not in ['']: member.addr_ward_no = ward_no if tole not in ['']: member.addr_tole = tole if city not in ['']: member.addr_municipality = city if home_phone not in ['']: member.telephone_home = int(home_phone) if parent_name not in ['']: member.parent_name = parent_name if school_name not in ['']: member.school_name = school_name if school_class not in ['']: member.school_class = school_class if roll_no not in ['']: member.school_roll_no = roll_no if date_of_birth not in ['']: if date_of_birth.__class__ == str: member.date_of_birth = BSDate.convert_to_ad( date_of_birth) else: member.date_of_birth = date_of_birth if date_of_expiration not in ['']: member.date_of_expiration = date_of_expiration if school_number not in ['']: member.school_number = school_number if telephone_mobile not in ['']: member.telephone_mobile = telephone_mobile # school_number and telephone_mobile are not added member.groups.add(Group.objects.get(name="Member")) member.save() created = True return HttpResponseRedirect( reverse("addMemberWithArgs", kwargs={"created": created})) return render(request, "account/create_member.html", context=addGlobalContext({ "form": form, "member_created": created, "member": ModUser.objects.order_by("-date_joined")[0] }))
def copyBook(request): return render(request, "head/copyBook.html", addGlobalContext())
def editGroup(request, group_id): all_perms = Permission.objects.filter( Q(codename__contains="Book") | Q(codename__contains="ModUser") | Q(codename="add_lend")) if request.method == "POST": name = request.POST.get("name", None) if name != None: if group_id == None: groups = Group.objects.filter(name=name) else: groups = Group.objects.filter(id=group_id) groups[0].permissions.clear() if len(groups) > 0: group_exists = True else: group_exists = False permissions = {} for perm in all_perms: permissions[perm.codename] = request.POST.get( "perm_" + perm.codename, False) if group_exists is False: group = Group.objects.create(name=name) else: group = groups[0] group.name = name for perm in permissions.items(): if perm[1] is not False: try: group.permissions.get(codename=perm[0]) except ObjectDoesNotExist: perm_spl = perm[0].split("_") print perm_spl, perm if perm_spl[1].lower() == "book": group.permissions.add( Permission.objects.get(codename=perm_spl[0] + "_author")) group.permissions.add( Permission.objects.get(codename=perm_spl[0] + "_publisher")) group.permissions.add( Permission.objects.get(codename=perm_spl[0] + "_gifter")) elif perm_spl[1].lower() == "moduser": group.permissions.add( Permission.objects.get(codename=perm_spl[0] + "_usertype")) elif perm_spl[1].lower() == "lend": group.permissions.add( Permission.objects.get(codename="add_lend")) group.permissions.add( Permission.objects.get(codename="change_lend")) group.permissions.add( Permission.objects.get(codename=perm[0])) group.save() group_added = True else: group_added = False ## name is None else: group_added = None ## POST Request not sent if group_added is True: return HttpResponseRedirect( reverse("almsGroupsHomeWithArgs", kwargs={ "group_added": int(True), "group_name": smart_str(group.name) })) elif group_added is False: context = addGlobalContext({ "all_permissions": all_perms, 'group_added': int(group_added), 'group': group }) else: if group_id is not None: try: found_group = Group.objects.get(id=group_id) except ObjectDoesNotExist: found_group = None else: found_group = None context = addGlobalContext({ "all_permissions": all_perms, "found_group": found_group }) return render(request, 'almsGroups/new.html', context=context)
def __borrow__(request, acc_no=None, username=None): config.reload() username = request.POST.get("username", None) bookID = request.POST.get("bookID", None) date = request.POST.get("date", None) if date is None: date = datetime.date.today() else: date_arr = [int(x) for x in date.split("-")] if username is None or bookID is None: return render( request, "head/borrow.html", addGlobalContext({ "borrowed": 4, "date_add": date.isoformat(), })) book = get_object_or_404(Book, accession_number=bookID) user = get_object_or_404(ModUser, username=username) lends = Lend.objects.filter(user=user, returned=False) if lends.count() > MAX_NUM_OF_BOOKS_TO_BORROW: borrowed = 3 else: lends = Lend.objects.filter(book=book, user=user, returned=False) if lends.count() != 0: borrowed = 0 elif lends.count() == 1 and lends.user == user: borrowed = 2 else: # the book can be lended lend_obj = Lend.objects.create(book=book, user=user, lending_date=date) date = [int(_) for _ in date.split("-")] lend_obj.date = datetime.date(date[0], date[1], date[2]) lend_obj.save() book.state = 2 book.save() borrowed = 1 # borrowed has the following values: # 0 - book is already borrowed by someone # 1 - book was successfully borrowed # 2 - book is already borrowed by the same user # 3 - User has borrowed MAX_NUM_OF_BOOKS_TO_BORROW books already # 4 - username and bookID were not given context = addGlobalContext({ 'date_val': date, 'borrowed': borrowed, 'book': book, 'got_user': user, 'book_acc': borrowed }) if username is not None: context.update({'username': username}) if acc_no is not None: context.update({"acc_no": acc_no}) return render(request, 'head/borrow.html', context)
def bookInfo(request, id): config.reload() books = Book.objects.filter(id=id) if books.count() == 0: return HttpResponse("Book Not Found") else: book = books[0] lends = Lend.objects.filter(book=book) if lends.count() > 0: lends = lends[len(lends) - 1] days_ago = datetime.date.today() - lends.lending_date is_borrowed = True if days_ago.days == 0: days_ago = "today" else: days_ago = str(days_ago.days) + " days ago" else: is_borrowed = False lends = None days_ago = None if lends is not None: late_fees = lends.get_late_fees() else: late_fees = 0 # get data for all generic fields. # if the book doesnt have value for generic field, give an empty string :) generic_fields = [] for _ in GenericField.objects.all(): try: genFieldLink = _.value.get(book=book) except ObjectDoesNotExist: genFieldLink = None if genFieldLink is not None: generic_fields.append((_, genFieldLink.get_value())) else: generic_fields.append((_, "")) ''' when someone searches for the book, ?source=search is appended to the url. WHen sources=search is found in request.GET, a view is added to the book, then the user is redirected to a url for the book without the ?source=search tail. This is because views are only added when a book is searched, not simply when the page is refreshed. ''' ''' If the book is simply refreshed, then views are not added, but if the book is searhced for, or found some other way, then a view is added ''' get_source = request.GET.get("source", None) refreshedHttpRedir = HttpResponseRedirect( reverse('book', kwargs={'id': book.id}) + "?search=refreshed") if get_source != "refreshed" and get_source is not None: book.add_view() return refreshedHttpRedir elif get_source == "": # don't add view if nothing is specified return refreshedHttpRedir return render( request, "head/book.html", addGlobalContext({ "book": book, 'lends': lends, 'late_fees': late_fees, 'is_borrowed': is_borrowed, 'days_ago': days_ago, "types": TYPES, "genericFields": generic_fields }))
def searchBook(request): config.load() value = request.GET.get("search", None) type_ = request.GET.get("type", None) booklist = [] ''' Search algorithm : Step 1 : Check if the query matches any books as a whole Step 2a : Check if each word in the query matches a book Step 2b : If each word matches queries then find the queries which match all the words in the query Step 2c : If no book matches all the words in the book then find the book(s) which matches most of the words in the query < Note : In Step 2c, meaning of the word "most" is very flexible. > ''' page = request.GET.get("page", 1) all_books = Book.objects.filter( state=0) # state - 0 is books which are available if value is not None: value = value.split(" ") if type_.startswith( "." ): # search in generic fields. ( generic field types start with .) gen_field = GenericField.objects.filter(key=type_[1:]) if len(gen_field) == 1: gen_field = gen_field[0] books = searchGenericField(" ".join(value), gen_field) if type_ == config.text['title']: books = searchBookTitle(" ".join(value), all_books) elif type_ == config.text['call_number']: books = Book.objects.filter(call_number__contains=value[0], state=0) elif type_ == config.text['accession_number']: books = Book.objects.filter(Q(accession_number=no_to_en(value[0])), Q(state=0)) elif type_ == config.text['keyword']: books = searchBookKeywords(" ".join(value), all_books) elif type_ == config.text['publisher']: books = Book.objects.filter(publisher__name__contains=value[0], state=0) for each in value[1:]: bookf = books.filter(publisher__name__contains=each, state=0) if bookf.count() > 0: books = bookf else: break elif type_ == config.text['author']: books = searchBookAuthor(" ".join(value), all_books) booklist = books if len(booklist) == 0: not_found = True else: not_found = False else: value = [] not_found = None paginator = Paginator(booklist, NO_OF_BOOKS_PER_PAGE) total_book_len = len(booklist) try: booklist = paginator.page(page) except PageNotAnInteger: booklist = paginator.page(1) except EmptyPage: booklist = paginator.page(paginator.num_pages) return render( request, "head/search_books.html", addGlobalContext({ 'total_books_len': total_book_len, "books": booklist, "book_pages": list(range(1, min(paginator.num_pages + 1, 9))), "value": " ".join(value), "type": type_, "not_found": not_found }))
def home(request): miscFields = GenericField.objects.order_by('-last_modified') return render(request, 'miscFields/home.html', addGlobalContext({'miscfields': miscFields}))
def addMemberWithArgs(request, created): ''' the frontend {html} form is filled with the required details. These details are then sent via post method to this function where they are designated to their respective places. Using the data, a new member is created ''' config.refresh() form = CreateMemberForm() member = None if request.method == "POST": form = CreateMemberForm(request.POST) if form.is_valid(): # the form is valid, so lets create the member data = form.cleaned_data if data['first_name'] == '' and data['last_name'] == '': created = False else: first_name =smart_str( data['first_name'].strip(" ").lower()) last_name = smart_str(data['last_name'].strip(" ").lower()) gender = smart_str(data['gender'].strip(' ').lower()) ward_no = smart_str(data['ward_no'].strip(' ').lower()) tole = smart_str(data['tole'].strip(' ').lower()) city = smart_str(data['city'].strip(' ').lower()) home_phone = smart_str(data['home_phone'].strip(' ').lower()) parent_name = smart_str(data['parent_name'].strip(' ').lower()) school_name = smart_str(data['school_name'].strip(' ').lower()) school_class = smart_str(data['school_class'].strip(' ').lower()) roll_no = smart_str(data['roll_no'].strip(' ').lower()) date_of_birth = data['date_of_birth'] ## creating the username username = create_username(first_name, last_name,ModUser.objects.all().count()) member = ModUser.objects.create( username=username ) if first_name not in ['']: member.first_name = first_name if last_name not in ['']: member.last_name = last_name if gender not in ['']: member.gender = gender if ward_no not in ['']: member.addr_ward_no = ward_no if tole not in ['']: member.addr_tole = tole if city not in ['']: member.addr_municipality = city if home_phone not in ['']: member.telephone_home = int(home_phone) if parent_name not in ['']: member.parent_name = parent_name if school_name not in ['']: member.school_name = school_name if school_class not in ['']: member.school_class = school_class if roll_no not in ['']: member.school_roll_no = roll_no if date_of_birth not in ['']: member.date_of_birth = date_of_birth # school_number and telephone_mobile are not added member.groups.add(Group.objects.get(name="Member")) member.save() created = True return HttpResponseRedirect(reverse("addMemberWithArgs", kwargs={"created": created})) return render(request, "account/create_member.html", context=addGlobalContext( { "form": form, "member_created": created, "member": ModUser.objects.order_by("-date_joined")[0] }) )
def home(request): context = addGlobalContext({}) return render(request, "booktool/home.html", context=context)
def home(request): config.reload() home_template = "head/home.html" context = addGlobalContext( {"popular_books": Book.objects.order_by("?")[0:3]}) return render(request, home_template, context)
def editEntry(request, id): config.reload() book_exists = True if id is not None: books = Book.objects.filter(id=id) if len(books) < 1: return HttpResponseRedirect(reverse("entry")) else: book = books[0] clear_fields = False else: book_exists = False book = None clear_fields = True columns_for_table = list(enumerate(config.books_columns.items(), 1)) columns_for_generic_fields = list( enumerate([(x.key, "__gen_" + x.get_programatic_key()) for x in GenericField.objects.all()])) for _ in columns_for_generic_fields: columns_for_table.append(_) columns_for_entry = list(enumerate((_[1] for _ in columns_for_table), 1)) columns_for_entry_div = [ columns_for_entry[c:c + NO_OF_ROWS_IN_ENTRY] for c in range(0, len(columns_for_entry) + 1, NO_OF_ROWS_IN_ENTRY) ] columns_for_generic_fields_div = [ columns_for_generic_fields[c:c + NO_OF_ROWS_IN_ENTRY] for c in range(0, len(columns_for_generic_fields) + 1, NO_OF_ROWS_IN_ENTRY) ] total_no_of_cols_table = len(columns_for_table) total_no_of_cols_entry = len(columns_for_entry) if total_no_of_cols_entry <= 12: div_len = 12 / total_no_of_cols_entry div_offset = (12 - (div_len * total_no_of_cols_entry)) / 2 else: div_len = total_no_of_cols_entry / 12 div_offset = ((div_len * total_no_of_cols_entry) - 12) / 2 return render( request, "head/entry.html", addGlobalContext({ 'globals': config, 'date': datetime.date.today(), "columns_for_table": columns_for_table, "columns_for_entry": columns_for_entry, "columns_for_entry_div": columns_for_entry_div, 'no_of_rows': NO_OF_ROWS_IN_ENTRY, 'div_len': div_len, 'book': book, 'is_edit': int(book_exists), 'div_offset': div_offset, 'total_columns_table': total_no_of_cols_table, 'total_columns_entry': total_no_of_cols_entry, 'columns_entry_json': json.dumps(columns_for_entry, indent=4), 'columns_table_json': json.dumps(columns_for_table, indent=4), 'largest_accession_number': AccessionNumberCount.get_no(), 'clear_fields': int(clear_fields) }))