예제 #1
0
파일: views.py 프로젝트: ailling/gatestapp
def book_view(request):
    if request.method == "GET":
        form = BookForm()
    else:
        form = BookForm(request.POST)

    """
    WARING: this line will technically work, but is horribly sub-optimal.
    djangoperformance.com will make you aware of that sub-optimality by telling
    you how many queries are being generated for each view, and what those queries are
    """
    #    books = Book.objects.all()

    """
    this is a simple solution to reduce the number of queries issued to the database.
    this should not be considered a recipe for optimizing all applications, and is only
    used here to illustrate expected use case of djangoperformance.com
    (you may, for example, want to use a custom model manager if you're doing something complicated
    in your application)
    """
    books = Book.objects.select_related("publisher").all().prefetch_related("authors")

    if not form.is_valid() or request.method == "GET":
        return render_to_response(
            "books.html", {"form": form, "object_list": books}, context_instance=RequestContext(request)
        )
    else:
        newitem = form.save()
        messages.success(request, "Book %s was added" % newitem)
        return HttpResponseRedirect(request.build_absolute_uri())
예제 #2
0
파일: views.py 프로젝트: minisin/muxi_site
def bookin():
    """
    书籍录入

        输入书籍的名字,将书籍的

            书名, 封面, 简介 录入数据库
    """
    if current_user.role_id == 2:
        form = BookForm()

        if form.validate_on_submit():
            bookname = form.bookname.data
            get_url = "https://api.douban.com/v2/book/search?q=%s" % bookname
            resp_1 = json.loads(urlopen(get_url).read().decode('utf-8'))
            book_id = resp_1['books'][0]['id']
            url = "https://api.douban.com/v2/book/%s" % book_id
            resp_2 = json.loads(urlopen(url).read().decode('utf-8'))
            book = Book(url=url, name=resp_2['title'], author=resp_2['author'][0], \
                        tag=form.tag.data, summary=resp_2['summary'], \
                        image=resp_2['images'].get('large'), user_id=None, end=None, \
                        status=False)
            db.session.add(book)
            db.session.commit()
            flash('书籍已录入!')
            return redirect(url_for('books.bookin'))
        return render_template('bookin.html', form=form)
    else:
        return redirect(url_for('books.home'))
예제 #3
0
def check_books(request):
    form = BookForm(request.POST, request.FILES) # A form bound to the POST data
    if not form.is_valid(): # All validation rules pass
        return render(request, "index.html", {"form": form})
    
    # Process the data in form.cleaned_data -- but what about the location data?
    book_file = form.cleaned_data['book_file']
    google_url = form.cleaned_data['google_url']
    lib_location = form.cleaned_data['lib_location']
    if book_file:
        booklist = process_book_file(book_file) # returns list of title and author
    elif google_url:
        print google_url
        booklist = read_spreadsheet(google_url)
    # print "%r"%lib_location 
    gr_rating = 0
    checked_in_books = []
    for book_title, author in booklist:
        library_base_url = create_library_url(book_title, lib_location)
        details = get_details(book_title, author, lib_location, library_base_url)
        if details:
            checked_in_books.append(details)
            print "processed!"
    # print booklist
    sorry_msg = """
    Sorry, no amount of fairy dust can check in 
    any of these books for you. Check back again in a few days.
    """
    return render(
        request,'booklist.html', 
        { 'booklist': checked_in_books }
        )
예제 #4
0
def create_listing():
    form = BookForm()
    if form.validate_on_submit():
        new_book = Book(isbn=int(form.isbn.data), owner=current_user.user_id)

        session = Session()
        session.add(new_book)
        session.commit()

        new_transaction = Transaction(
            seller=current_user.user_id,
            book=new_book.book_id,
            address_from=form.streetNameNum.data + " " + form.city.data +
            ", " + form.state.data + " " + form.zipcode.data)

        session.add(new_transaction)
        user = session.query(User).filter(
            User.user_id == current_user.user_id).first()
        user.credits += 1
        user.totalcredit += 1
        session.commit()

        return redirect(
            url_for(
                "index",
                msg=
                "The Magic Bookshelf📚 applauds your generosity! You have earned [✨Arcane Dust x1]"
            ))
    # Very important, make sure to initialize the field of the OWNER's
    # associated user's ID after the post request. To be handled later
    return render_template('create_listing.html', form=form)
예제 #5
0
def newBook():
	form = BookForm(formdata=request.form or None)
	print form.category.data, form.publisher.data, form.author.data
	if request.method == 'POST':
		if request.form and form.validate():
			category = Category.query.get(form.category.data)
			publisher = Publisher.query.get(form.publisher.data)
			author = Author.query.get(form.author.data)
			number = len(category.books.all()) + 1
			categoryShortName = category.shortName
			b = Book(number=number,
					title=form.title.data,
					author=[author],
					category=[category],
					publisher=[publisher],
					edition=form.edition.data,
					price=form.price.data,
					)
			#db.session.add(b)
			db.session.commit()
			return redirect(url_for('books', page=1))
		else:
		    flash('There was an error with your input: %s' % form.errors)
		    return redirect(url_for('newBook'))
		return redirect(redirectUrl)
	else:
		return render_template('newBook.html', form=form)
예제 #6
0
def check_books(request):
    form = BookForm(request.POST,
                    request.FILES)  # A form bound to the POST data
    if not form.is_valid():  # All validation rules pass
        return render(request, "index.html", {"form": form})

    # Process the data in form.cleaned_data -- but what about the location data?
    book_file = form.cleaned_data['book_file']
    google_url = form.cleaned_data['google_url']
    lib_location = form.cleaned_data['lib_location']
    if book_file:
        booklist = process_book_file(
            book_file)  # returns list of title and author
    elif google_url:
        print google_url
        booklist = read_spreadsheet(google_url)
    # print "%r"%lib_location
    gr_rating = 0
    checked_in_books = []
    for book_title, author in booklist:
        library_base_url = create_library_url(book_title, lib_location)
        details = get_details(book_title, author, lib_location,
                              library_base_url)
        if details:
            checked_in_books.append(details)
            print "processed!"
    # print booklist
    sorry_msg = """
    Sorry, no amount of fairy dust can check in 
    any of these books for you. Check back again in a few days.
    """
    return render(request, 'booklist.html', {'booklist': checked_in_books})
예제 #7
0
파일: views.py 프로젝트: rasiel/mibooklist
def add(request):
    """View to add a book, we will check if the seller is active first"""
    try:
        seller = Seller.objects.get(user=request.user.id)
    except Seller.DoesNotExist:
        seller = None
    if seller and seller.account_status == 'AC':
        can_add_book = True
        seller_id = seller.id
    else:
        can_add_book = False
        seller_id = None
        
    if request.method == 'POST': # If the form has been submitted...
        form = BookForm(request.POST, request.FILES) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            # Process the data in form.cleaned_data
            # ...
            form.save()
            return redirect('/accounts/books/') # Redirect after POST
    else:
        form = BookForm(initial={'seller': seller_id}) # An unbound form

    return render_to_response('books/book_form.html', {
        'form': form,
        'can_add_book': can_add_book,
        'seller': seller
    },context_instance=RequestContext(request))
예제 #8
0
def book():
	form = BookForm(request.form)
	if request.method == 'POST' and form.validate():
		building = form.building.data
		roomNum = form.room.data
		client = form.renter.data
		startDate = form.startDate.data
		endDate = form.endDate.data

		#write to database
		aRoom = db.session.query(Room).filter_by(building_id = building, number = roomNum).first()
		if not aRoom:
			err = "Room number " + str(roomNum) + " is not valid for the building " + str(building)
			return render_template('error.html', msg=err)
		aClient = db.session.query(Client).filter_by(name = client).first()
		if not aClient:
			session['bookInfo'] = json.dumps({'room' : roomNum, 'newRenterName':client, 'bookRoomId':xstr(aRoom.roomId), 'stDate':xstr(startDate), 'endDate':xstr(endDate)})
			return redirect(url_for('newRenter'))
		res = Reservation(arrive = startDate, depart = endDate, roomId = aRoom.roomId, clientId = aClient.clientId)

		termsDict = {'building': xstr(building), 'room':roomNum, 'client': '', 'stDate':xstr(startDate), 'endDate':xstr(endDate)}
		preRes = doSearch(termsDict)
		if bookDateCompare(preRes, termsDict):
			return render_template('error.html', msg="There is an issue with that room and date combination")
		try:
			db.session.add(res)
			db.session.commit()
		except (exc.InvalidRequestError, exc.ProgrammingError):
			db.session.rollback()
			err = "There is an issue booking that room for that set of dates, please try again. It is most likely there is a record for this user on those dates already."
			return render_template('error.html', msg=err)
		
	return render_template('book.html', form=form)
예제 #9
0
def books_list():
    form = BookForm()
    error = ""
    if request.method == "POST":
        if form.validate_on_submit():
            books.create(form.data)
            books.save_all()
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            flash("File is uploaded")
            return redirect(url_for('uploaded_file', filename=filename))
        if form.validate_on_submit():
            books.create(form.data)
            books.save_all()
        return redirect(url_for("books_list"))

    return render_template("books.html", form=form, books=books.all(), error=error)
예제 #10
0
파일: views.py 프로젝트: shustrik113/myweb
def create_book(request):
    if request.POST:
        form = BookForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/books/')
    else:
        form = BookForm()

    args = {}
    args.update(csrf(request))
    args['form'] = form

    # right box
    args['menu'] = Menu.objects.all()
    args['pop_books'] = Book.objects.all().order_by('likes').reverse()[:10]
    args['new_books'] = Book.objects.all().order_by('date').reverse()[:10]
    args['cats'] = Category.objects.all()
    args['tags'] = Tag.objects.all()
    args['current_item'] = 'книги'

    # user
    args['username'] = auth.get_user(request).username

    # poll
    args['question_web'] = Question.objects.get(text=u"Как вам наш сайт?")
    args['choices'] = Choice.objects.filter(question_id=args['question_web'].id)
    return render_to_response('book/create_book.html', args)
예제 #11
0
파일: views.py 프로젝트: piIorama/des
def addbook(request,id=1):
	if request.POST:
		form = BookForm(request.POST)
		if form.is_valid():
			book=form.save(commit=False)
			form.save()
	return redirect('/books/all',)
예제 #12
0
def nominations(request, poll_id):
    poll = Poll.objects.get(id=poll_id)
    books = Book.objects.filter(poll=poll_id)
    disabled = ''
    votes = {}

    for book in books:
        if book.user == request.user:
            disabled = 'disabled="disabled"'

    if request.method == "POST":
        form = BookForm(request.POST)
        if form.is_valid():
            title = form.cleaned_data['title']
            author = form.cleaned_data['author']
            description = form.cleaned_data['description']
            book = Book(title=title,
                        author=author,
                        description=description,
                        poll=poll,
                        user=request.user)
            book.save()
            return redirect('/polls/nominations/' + str(poll_id))
    else:
        form = BookForm()

    context = RequestContext(request, {
        'poll': poll,
        'books': books,
        'form': form,
        'disabled': disabled,
    })
    return render(request, 'polls/nominations.html', context)
예제 #13
0
def bookin():
    """
    书籍录入

        输入书籍的名字,将书籍的

            书名, 封面, 简介 录入数据库
    """
    if current_user.username == 'neo1218':
        form = BookForm()

        if form.validate_on_submit():
            bookname = form.bookname.data
            get_url = "https://api.douban.com/v2/book/search?q=%s" % bookname
            resp_1 = json.loads(urlopen(get_url).read().decode('utf-8'))
            book_id = resp_1['books'][0]['id']
            url = "https://api.douban.com/v2/book/%s" % book_id
            resp_2 = json.loads(urlopen(url).read().decode('utf-8'))
            book = Book(url=url, name=resp_2['title'], author=resp_2['author'][0], \
                        tag=form.tag.data, summary=resp_2['summary'], \
                        image=resp_2['images'].get('large'), user_id=None, end=None, \
                        status=False)
            db.session.add(book)
            db.session.commit()
            flash('书籍已录入!')
            return redirect(url_for('bookin'))
        return render_template('bookin.html', form=form)
    else:
        return redirect(url_for('home'))
예제 #14
0
def book():
    form = BookForm()
    if form.validate_on_submit():
        if session.get('is_admin'):
            if form.g_id.data is None:
                flash('Input guest id')
                return render_template('book.html', form=form)
            else:
                session['g_id'] = form.g_id.data
        else:
            session['g_id'] = session.get('user_id')
        today = datetime.date.today()
        check_in = form.check_in.data
        check_out = form.check_out.data
        if check_out <= check_in or check_in < today:
            flash('Illegal date input')
            return render_template('book.html', form=form)
        cur = mysql.connection.cursor()
        # 从所有房间中找出还没被预定的房间
        check_in = check_in.strftime('%Y-%m-%d')
        check_out = check_out.strftime('%Y-%m-%d')
        cur.execute(
            'select * from room where r_id not in (select r_id from booking where `from`<%s and `to`>%s)',
            [check_out, check_in])
        rooms = cur.fetchall()
        session['check_in'] = check_in
        session['check_out'] = check_out
        session['meal'] = form.meal.data
        session['num_adult'] = form.num_adult.data
        session['num_child'] = form.num_child.data
        return render_template('select_rooms.html', rooms=rooms)
    return render_template('book.html', form=form)
예제 #15
0
def add():
    form = BookForm()
    print form.name.data
    if form.validate_on_submit():
        if b_img:
            b_img = form.imgname.data
        else:
            b_img = 'default.jpg'
        b_name = form.name.data
        b_category = form.category.data
        b_press = form.press.data
        b_author = form.author.data
        b_note = form.note.data
        b = Book(name=b_name,
                 img=b_img,
                 category=b_category,
                 press=b_press,
                 author=b_author,
                 note=b_note,
                 status=False,
                 num=0)
        db.session.add(b)
        db.session.commit()
        if is_not_admin():
            time = datetime.now()
            give = Give(author=g.user.id, book_id=b.id, time=time, status=0)
            db.session.add(give)
            db.session.commit()
            flash("添加成功,等待管理员审核")
        return redirect(url_for('info', b_id=b.id))

    return render_template('book_add.html', g=g, form=form)
예제 #16
0
def edit_book(request):
    form = BookForm(request.POST)
    if request.method == 'POST' and form.validate():
        form.populate_obj(user)
        user.save()
        redirect('edit_profile')
    return render_response('edit_profile.html', form=form)
예제 #17
0
def bookform():
    form = BookForm()
    if form.validate_on_submit():

        conn = sqlite3.connect('bookdata')
        cur = conn.cursor()
        all_books = cur.execute('SELECT * FROM BooksTable;').fetchall()
        id = str(uuid.uuid4())
        fileName = 'bookPhoto_' + str(id)
        book_dict = {
            'Author': form.author.data,
            'Title': form.title.data,
            'Rating': int(form.rating.data),
            'Description': form.description.data,
            'FileName': fileName,
            'ID': id
        }

        form.photo.data.save("static/userImages/" + fileName + ".png")

        cur.execute("INSERT INTO BooksTable VALUES (?,?,?,?,?,?)", [
            book_dict["ID"], book_dict["Title"], book_dict["Author"],
            book_dict["Rating"], book_dict["FileName"],
            book_dict["Description"]
        ])
        conn.commit()
        conn.close()
        return redirect('/index')
    return render_template('bookform.html', form=form)
예제 #18
0
def addbook():
    if current_user.status == 1:
        bookform = BookForm()
        if request.method == "POST":
            isbn = request.form.get('isbn')
            name = request.form.get('name')
            price = request.form.get('price')
            author = request.form.get('author')
            book = Book(isbn=isbn,
                        price=price,
                        name=name,
                        author=author,
                        num=1)
            if bookform.validate_on_submit():
                try:
                    db.session.add(book)
                    db.session.commit()
                    flash('添加图书成功')

                except Exception as e:
                    flash('添加书籍失败')
                return redirect(url_for('showallbooks'))
        return render_template('addbook.html', bookform=bookform)
    else:
        return ' permission denied'
예제 #19
0
def index():
    form = BookForm()
    if form.validate_on_submit():
        results = models.Book.select().where(
            models.Book.ISBN_13 == form.ISBN_13.data.strip()
            or models.Book.ISBN_10 == form.ISBN_10.data.strip()).limit(1)
        if len(results) > 0:
            book = results[0]
        else:
            book = None
        if book == None:
            models.Book.create(image=form.image.data.strip(),
                               title=form.title.data.strip(),
                               author=form.author.data.strip(),
                               ISBN_13=form.ISBN_13.data.strip(),
                               ISBN_10=form.ISBN_10.data.strip(),
                               date_published=form.date_published.data.strip(),
                               description=form.description.data.strip(),
                               total_pages=form.total_pages.data)
            flash("Added new book, titled: {}".format(form.title.data),
                  "alert alert-success")
            book = models.Book.get(
                models.Book.ISBN_13 == form.ISBN_13.data.strip()
                or models.Book.ISBN_10 == form.ISBN_10.data.strip())
        return redirect("/setgoal/{}".format(book.id))

    return render_template("add_book.html", title="Add Form", form=form)
예제 #20
0
 def post(self, request):
     form = BookForm(request.POST)
     if form.is_valid():  # 验证表单数据
         print(form.cleaned_data)  # 获取验证后的表单数据
         return HttpResponse("OK")
     else:
         return render(request, 'book.html', {'form': form})
예제 #21
0
def default():
    form = BookForm(request.form)
    if (request.method == 'POST' and form.validate()):
        print(form.data)
        add_book(form.data)
        book_list = get_books()
        return render_template('/home.html', bks=book_list)
    return render_template('create.html', form=form)
예제 #22
0
def add_book():
    form = BookForm(request.form)
    if request.method == 'POST' and form.validate():
        book = Book(form.title.data, form.authors.data)
        session.add(book)
        session.commit()
        return redirect(url_for('index'))
    return render_template('book_form.html', form=form, action="/book/add")
예제 #23
0
def add_book():
    """
    Function to load WTForm for adding book and render to html and add
    to database. Checks first whether a user is logged in, before
    performing function.
    WTForms code adapted from Corey Shafer's tutorial found at
    https://www.youtube.com/watch?v=UIJKdCIEXUQ&list=PL-osiE80TeTs4UjLw5MM6OjgkjFeUxCYH&index=3
    """
    
    # Check to see if user logged in and render html
    if g.user:
        form = BookForm()
        
        # Validation of form and insert in collection
        if form.validate_on_submit():
            flash(f"New book added: {form.title.data.title()}!", "success")
            book = {
                "title": form.title.data.lower(),
                "author_fname": form.author_fname.data.lower(),
                "author_lname": form.author_lname.data.lower(),
                "category_id": form.category_id.data,
                "user_id": g.user,
                "up_votes": 0,
                "down_votes": 0,
                "date_added": date.today().strftime("%Y/%m/%d"),
                "cover_url": form.cover_url.data,
                "csrf_token": form.csrf_token.data
            }
            books = mongo.db.books
            books.insert_one(book)
            return redirect(
                url_for(
                    "get_books",
                    _scheme="https",
                    _external=True))
        
        # Check to see type of user and return of form for correction
        else:
            super_user = mongo.db.users.find_one({"username": "******"})
            if g.user == str(super_user["_id"]):
                return render_template(
                    "addbook.html",
                    form=form,
                    categories=mongo.db.categories.find().sort("category_name"),
                    super_user=g.user)
            else:
                return render_template(
                    "addbook.html",
                    form=form,
                    categories=mongo.db.categories.find().sort("category_name"),
                    regular_user=g.user)
    else:
        flash(f"You need to log in first...", "warning")
        return redirect(
            url_for(
                "log_user_in",
                _scheme="https",
                _external=True))
예제 #24
0
def book_details(book_id):
    book = books.get(book_id - 1)
    form = BookForm(data=book)

    if request.method == "POST":
        if form.validate_on_submit():
            books.update(book_id - 1, form.data)
        return redirect(url_for("books_list"))
    return render_template("book.html", form=form, book_id=book_id)
예제 #25
0
def index():
    form = BookForm(csrf_enabled=False)
    if form.validate_on_submit():
        # Check the password and log the user in
        # [...]
        artist=Main.main(form.book.data)
        return redirect(url_for('index'))
        return redirect(url_for('qwerty'))
    return render_template('index.html', form=form)
예제 #26
0
파일: main.py 프로젝트: zemlanin/Libr
def addbook():
    form = BookForm(request.form)
    if form.validate():
        b = Book(form.title.data)
        db_session.add(b)
        db_session.commit()
        return redirect(url_for("singlebook", b_id=b.id))
    else:
        return redirect(url_for("index"))
예제 #27
0
def cadastro():
    form = BookForm()
    if form.validate_on_submit():
        book = Book(titulo=request.form['titulo'], autor=request.form['autor'], editora=request.form['editora'], categoria=request.form['categoria'], tipo=request.form['tipo'], status=request.form['status'], quantidade=request.form['quantidade'], descricao=request.form['descricao'])
        db.session.add(book)
        flash('Livro inserido com sucesso!!')
        db.session.commit()
        return redirect(url_for('cadastro'))

    return render_template('cadastro.html', form=form)
예제 #28
0
파일: views.py 프로젝트: bilunyk/elibrary
 def dispatch_request(self):
     form = BookForm()
     form.authors.query = Author.query.all()
     if request.method == "POST":
         if form.validate_on_submit():
             obj = Book()
             form.populate_obj(obj)
             obj.save()
             return redirect("/books/")
     return render_template("book_add.html", form=form)
예제 #29
0
def home():
    phrase = None
    sentence = None
    form = BookForm()
    if form.validate_on_submit():
       phrase = form.book.data
       MarkovChain = TextCreator(form.book.data)
       sentence = MarkovChain.generate_text(output_length=20)
       form.book.data = ''
    return render_template('home.html', form=form, phrase=phrase, sentence=sentence)
예제 #30
0
def books_list_api_v1():
    form = BookForm()
    error = ""

    if request.method == "POST":
        if form.validate_on_submit():
            books.create(form.data)
        return redirect(url_for("books_list_api_v1"))

    return render_template("books.html", form=form, books=books.all(), error=error)
예제 #31
0
def create_book():
    form = BookForm()
    if form.validate_on_submit():
        book = Book(title = form.title.data, timestamp = datetime.utcnow(), author = g.user)
        db.session.add(book)
        db.session.commit()
        return redirect(url_for('search'))
    else:
        return render_template('create_book.html', 
            form = form)
예제 #32
0
파일: views.py 프로젝트: bilunyk/elibrary
 def dispatch_request(self, obj_id):
     obj = Book.query.get_or_404(obj_id)
     form = BookForm(obj=obj)
     form.authors.query = Author.query.join(Book.authors).union(Author.query)
     if request.method == "POST":
         if form.validate_on_submit():
             form.populate_obj(obj)
             obj.save()
             return redirect("/books/")
     return render_template("book_edit.html", form=form, obj=obj)
예제 #33
0
def show_library():
    error=""
    book_form = BookForm()

    if request.method == "POST":
        if book_form.validate_on_submit(): 
            services.add_book(book_form)
            return redirect(url_for('show_library'))
            
    books_list = services.load()
    return render_template("homepage.html", form = book_form, books = books_list, error=error)
예제 #34
0
def books_edit(book_id):
    book = Book.query.get_or_404(book_id)
    form = BookForm(request.form, obj=book)

    if request.method == "POST" and form.validate():
        book.title = form.data.get('title')
        db.session.commit()
        flash("Book changed")
        return redirect(url_for('books_view_all'))

    return render_template('books/edit.html', **locals())
예제 #35
0
def create_book():
    form = BookForm()
    if request.method == 'POST' and form.validate_on_submit():
        db.execute(
            "INSERT INTO books (title, author) VALUES (:title, :author);", {
                "title": form.title.data,
                'author': form.author.data
            })
        db.commit()
        # data = Book(form.title.data, form.author.data, form.isbn.data, form.year.data, )
    return render_template('book.html', form=form)
예제 #36
0
def books_add():
    form = BookForm(request.form)

    if request.method == "POST" and form.validate():
        new_book = Book(title=form.data.get('title'))
        new_book.authors = form.data.get('authors')
        db.session.add(new_book)
        db.session.commit()
        flash("Book added")
        return redirect(url_for('books_view_all'))

    return render_template('books/add.html', **locals())
예제 #37
0
파일: main.py 프로젝트: ssergiienko/flasktz
def create_book():
    if request.method == 'GET':
        form = BookForm()
    else:   # POST
        form = BookForm(request.form)
        if form.validate():
            book = Book('')
            form.populate_obj(book)
            db.session.add(book)
            db.session.commit()
            return redirect(url_for('edit_books'))
    return render_template('books_edit_page.html', form=form)
예제 #38
0
def edit_book(book_id):
    form = BookForm(request.form)
    if request.method == 'GET':
        form = BookForm(request.form, session.query(Book).get(book_id))
    if request.method == 'POST' and form.validate():
        book_edited = Book(form.title.data, form.authors.data)
        book_db = session.query(Book).get(book_id)
        book_db.title = book_edited.title
        book_db.authors = book_edited.authors
        session.commit()
        return redirect(url_for('index'))
    return render_template('book_form.html', form=form, action="/book/%s/edit" % book_id, submit_text="Save")
예제 #39
0
def book():
    form = BookForm(request.form)
    if request.method == 'POST' and form.validate():
        building = form.building.data
        roomNum = form.room.data
        client = form.renter.data
        startDate = form.startDate.data
        endDate = form.endDate.data

        #write to database
        aRoom = db.session.query(Room).filter_by(building_id=building,
                                                 number=roomNum).first()
        if not aRoom:
            err = "Room number " + str(
                roomNum) + " is not valid for the building " + str(building)
            return render_template('error.html', msg=err)
        aClient = db.session.query(Client).filter_by(name=client).first()
        if not aClient:
            session['bookInfo'] = json.dumps({
                'room': roomNum,
                'newRenterName': client,
                'bookRoomId': xstr(aRoom.roomId),
                'stDate': xstr(startDate),
                'endDate': xstr(endDate)
            })
            return redirect(url_for('newRenter'))
        res = Reservation(arrive=startDate,
                          depart=endDate,
                          roomId=aRoom.roomId,
                          clientId=aClient.clientId)

        termsDict = {
            'building': xstr(building),
            'room': roomNum,
            'client': '',
            'stDate': xstr(startDate),
            'endDate': xstr(endDate)
        }
        preRes = doSearch(termsDict)
        if bookDateCompare(preRes, termsDict):
            return render_template(
                'error.html',
                msg="There is an issue with that room and date combination")
        try:
            db.session.add(res)
            db.session.commit()
        except (exc.InvalidRequestError, exc.ProgrammingError):
            db.session.rollback()
            err = "There is an issue booking that room for that set of dates, please try again. It is most likely there is a record for this user on those dates already."
            return render_template('error.html', msg=err)

    return render_template('book.html', form=form)
예제 #40
0
def create(request):
	if request.method == 'POST':
		form = BookForm(request.POST, request.FILES)
		if form.is_valid:
			form.save()
			messages.add_message(request, messages.SUCCESS, 'Your book was added!')
			return HttpResponseRedirect('/')
	else:
		form = BookForm()
	args = {}
	#args.update(csrf(request))
	args['form'] = form
	return render(request, 'create_book.html', args)
예제 #41
0
def book_update(id):
    """
    update books
    """
    book = Book.query.get(id)
    book_form = BookForm(obj=book)
    if request.method == 'POST':
        if book_form.validate_on_submit():
            book_form.populate_obj(book)
            db.session.add(book)
            db.session.commit()
            return redirect('/')
    return render_template('book_edit.html', book_form=book_form)
예제 #42
0
def book_add():
    """
    returns book add function
    """
    book = Book()
    book_form = BookForm(obj=book)
    if request.method == 'POST':
        if book_form.validate_on_submit():
            book_form.populate_obj(book)
            db.session.add(book)
            db.session.commit()
            return redirect('/')
    return render_template('book_edit.html', book_form=book_form)
예제 #43
0
파일: app.py 프로젝트: xcrider/book_library
def library_list():
    form = BookForm()
    error = ""
    if request.method == "POST":
        if form.validate_on_submit():
            library.create(form.data)
            library.save_all()
        return redirect(url_for("library_list"))

    return render_template("library.html",
                           form=form,
                           library=library.all(),
                           error=error)
예제 #44
0
파일: app.py 프로젝트: nastyako/prom-ua
def add_book():
    form = BookForm(request.form)
    if request.method == 'POST' and form.validate():
        book = Book(form.title.data, form.author.data)
        session.add(book)
        session.commit()
        return redirect(url_for('index'))
    return render_template('book_form.html',
                           form=form,
                           action="/book/add",
                           user_name=current_user.name,
                           user_picture=current_user.picture,
                           if_administrator=verify_administrator())
예제 #45
0
def edit_book(id):
    form = BookForm()
    book = data_services.get_book_by_id(id)
    if request.method == 'GET':
        authors = ""
        for author in book.author:
            authors = author + ", "
        form = BookForm(obj=book)
        form.author.data = authors
        subscribers = data_services.get_all_subscriber()
        form.subscriber.choices = [(subscriber.id, subscriber.email)
                                   for subscriber in subscribers]
        form.subscriber.process_data(subscribers[0].id)
        publishers = data_services.get_all_publishers()
        form.publisher.choices = [(publisher.id, publisher.name)
                                  for publisher in publishers]
        form.publisher.process_data(book.publisher.id)
        return render_template('edit_book.html', form=form, status='edit')
    elif request.method == 'POST':
        if form.update.data:
            if form.validate_on_submit():
                authors = []
                for a in form.author.data.split(","):
                    if a != "" and a != " ":
                        authors.append(a)
                publisher = data_services.get_publisher(form.publisher.data)
                data_services.update_book(bk=book,
                                          title=form.title.data,
                                          author=form.author.data,
                                          pages=form.pages.data,
                                          publish_date=form.publish_date.data,
                                          publisher=publisher)
                flash('Book created successfully', 'success')
            else:
                for k, v in form.errors.items():
                    flash(v[0], 'danger')
                return render_template('edit_book.html',
                                       form=form,
                                       status='edit')
        elif form.delete.data:
            data_services.delete_book(book)
            flash('Book deleted successfully', 'success')
        elif form.borrow.data:
            subscriber = data_services.get_subscriber_by_id(
                form.subscriber.data)
            data_services.book_add_subscriber(bk=book,
                                              subscriber=subscriber,
                                              start=form.start.data,
                                              end=form.end.data)
            flash('Book borrow created successfully', 'success')
        return redirect('/book/list')
예제 #46
0
def book():
    form = BookForm(request.form)
    print(form)
    catgories = db_session.query(Category).all()
    # create category list
    catgories_list = [(category.id, category.name) for category in catgories]
    form.category.choices = catgories_list
    if request.method == 'POST' and form.validate():
        # auto generate category id in bettwen 10 - 20000
        book = Book(randint(10, 20000), form.category.data, form.name.data,
                    form.author.data, form.price.data, form.description.data,
                    form.image.data)
        db_session.add(book)
        return redirect('/home')
    return render_template('book_create.html', form=form)
예제 #47
0
def edit(request, book_id):
	b = Book.objects.get(id=book_id)
	if request.method == 'POST':
		form = BookForm(request.POST, request.FILES)
		if form.is_valid:
			c = form.save(commit=False)
			c.book = b
			c.save()
			messages.add_message(request, messages.SUCCESS, 'Your book was edited!')
			return HttpResponseRedirect('/books/get/%s' % book_id)
	else:
		form = BookForm()
	args = {}
	args['form'] = form
	return render(request, 'create_book.html', args)
예제 #48
0
파일: views.py 프로젝트: zedzew/zlibrary
def book_add():
    form = LoginForm()
    book_form = BookForm(request.form)
    book_form.authors.choices = [(p.id, p.name) for p in db_session.query(Author).order_by('id')]

    if book_form.validate_on_submit():
        book = Book()
        book.title = book_form.title.data
        book.authors = [db_session.query(Author).get(o) for o in book_form.authors.data]
        db_session.add(book)
        db_session.commit()
        flash('Successfully added.', 'success')
        return redirect(url_for('index'))

    return render_template("add_book.html", bform=book_form, form=form, user=current_user, is_authenticated=True)
예제 #49
0
파일: routes.py 프로젝트: vinodhmvk/Library
def edit(id):
    qry = db.session.query(Book).filter(Book.id == id)
    book = qry.first()

    if book:
        form = BookForm(formdata=request.form, obj=book)
        if request.method == 'POST' and form.validate():
            # save edits
            save_changes(book, form, current_user)

            flash('Book updated successfully!')
            return redirect('/mybooks')
        return render_template('edit_book.html', form=form)
    else:
        return 'Error loading #{id}'.format(id=id)
예제 #50
0
파일: views.py 프로젝트: rasiel/mibooklist
def edit(request, id):
    """Edit a book, using the passed id"""
    book = Book.objects.get(pk=id)
    if request.method == 'POST': # If the form has been submitted...
        form = BookForm(request.POST, request.FILES, instance=book) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            # Process the data in form.cleaned_data
            form.save()
            return redirect('/accounts/books/') # Redirect after POST
    else:
        form = BookForm(instance=book) # Lets bound the form

    return render_to_response('books/book_form.html', {
        'form': form,
        'can_add_book': True
    },context_instance=RequestContext(request))
예제 #51
0
파일: views.py 프로젝트: zedzew/zlibrary
def book_edit(id):
    form = LoginForm()
    book = db_session.query(Book).get(id)
    book_form = BookForm(request.form, obj=book)
    book_form.authors.choices = [(p.id, p.name) for p in db_session.query(Author).order_by('id')]

    if book_form.validate_on_submit():
        book = db_session.query(Book).get(id)
        book.title = book_form.title.data
        book.authors = [db_session.query(Author).get(o) for o in book_form.authors.data]
        db_session.commit()
        flash('Saved.', 'info')
        return redirect(url_for('index'))

    book_form.authors.data = [p.id for p in book.authors]
    return render_template("book.html", bform=book_form, form=form, book=book, user=current_user, is_authenticated=True)
예제 #52
0
def index():

    login_form = LoginForm(flask.request.form)
    book_form = BookForm(flask.request.form)
    if login_form.validate():
        username = login_form.username.data
        password = login_form.password.data
        user_info = {
            'id': username,
            'pwd': password,
            'act': 'login',
            '_': '1512131406585',
        }
        my_session = requests.Session()
        m = my_session.post(login_url, data=user_info, headers=headers)
        if 'ok' in json.loads(m.content.decode())['msg']:
            session['username'] = username
            session['password'] = password
            name = json.loads(m.content.decode())['data']['name']

            book_form.select.choices = [(result[1], result[1])
                                        for result in results]
            return render_template("index.html",
                                   title='Home',
                                   form=book_form,
                                   session=session,
                                   name=name)
        else:
            return u'错误'

    return u"错误"
예제 #53
0
def insert_book():
    form = BookForm()
    form2 = BookFormDelete()
    if (form.validate_on_submit and form.title.data and form.author.data):
        conn = get_db_connection()
        query = f"INSERT INTO books (title, author) VALUES ('{form.title.data}','{form.author.data}');"
        execute_query(conn, query)
        conn.close()
        flash(f'Book added: {form.title.data}', 'success')
        return redirect(url_for('home'))

    elif (form2.validate_on_submit and form2.isbn.data):
        conn = get_db_connection()
        tc = search_books_isbn(conn, form2.isbn.data)[0][3]
        query = f"DELETE FROM books WHERE isbn={form2.isbn.data};"
        execute_query(conn, query)
        if (tc != None):  #bu kısmı triggerla yap!!!
            query = f"UPDATE borrowers SET number_of_books=number_of_books-1 WHERE tc={tc};"
            #execute_query(conn,query)
        conn.close()
        flash(f'Book deleted: {form2.isbn.data}', 'success')
        return redirect(url_for('home'))

    return render_template('insertbook.html',
                           title='Add book',
                           form=form,
                           form2=form2)
예제 #54
0
def addbook(request):
	args={}
	args.update(csrf(request))
	args['form']=BookForm()
	args['username'] = auth.get_user(request).username
	if request.POST:
		form=BookForm(request.POST, request.FILES)
		if form.is_valid():
			book = form.save(commit=False)
			book.book_from = request.user
			book.book_date = timezone.now()
			book.save()
			return redirect('/books/get/%s/' %book.id)
	else:
		form=BookForm()
	return render_to_response('AddBook.html', args)
예제 #55
0
def book(request):
    logger.info("Showing the booking form")
    if request.method == 'POST': # If the form has been submitted...
        form = BookForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            # Process the data in form.cleaned_data
            study_type = form.cleaned_data['study_type']

            start_time = datetime.datetime.strptime(form.cleaned_data.get("start_time"), "%H:%M:%S")
            end_time = datetime.datetime.strptime(form.cleaned_data.get("end_time"), "%H:%M:%S")

            start_datetime = datetime.datetime.combine(form.cleaned_data.get('start_date'),
                                                       start_time.time())

            end_datetime = datetime.datetime.combine(form.cleaned_data.get('end_date'),
                                                     end_time.time())

            gmt = pytz.timezone('Europe/London')
            start_datetime = gmt.localize(start_datetime)
            end_datetime = gmt.localize(end_datetime)

            request.session['start_datetime'] = start_datetime
            request.session['end_datetime'] = end_datetime

            try:
                pods = Pod.objects.filter(study_types__id__exact=study_type).exclude(
                    booking__start_datetime__gt=start_datetime - datetime.timedelta(hours=1),
                    booking__end_datetime__lt=end_datetime - datetime.timedelta(hours=1)
                ).prefetch_related('configset_set')

                for pod in pods:
                    pod.my_configs = pod.configset_set.filter(user=request.user.username)
                    pod.my_config_count = pod.my_configs.count()

                pods = sorted(pods, key=operator.attrgetter('my_config_count'), reverse=True)

                return render_to_response("book/pod_available.html", {'pods': pods},
                                          context_instance=RequestContext(request))

            except Pod.DoesNotExist:
                return HttpResponse("Ouch, no pods available at that time")

    else:
        form = BookForm()

    return render_to_response("book/book.html", {'form': form}, context_instance=RequestContext(request))
예제 #56
0
def search(request):
    """Search view."""
    if request.GET:
        form = BookForm(request.GET)
        if form.is_valid():
            name = form.cleaned_data.get('name_field')
            books = Book.objects.filter(name__icontains=name)
            context = {
                'books_list': books
            }
            return render(request, 'shop/results.html', context)

    form = BookForm()
    context = {
        'form': form
    }
    return render(request, 'shop/search.html', context)
예제 #57
0
def new_book():
    form = BookForm(request.form)
    if request.method == 'POST' and form.validate():
        book = Book()
        book.room_id = form.room_id.data
        book.dates = [form.date_from.data, form.date_to.data]
        book.client_id = form.client_id.data
        payment = Payment()
        payment.type = form.ptype.data
        payment.done = form.pdone.data
        book.payment = payment
        try:
            add_book(book)
        except ValidationError as e:
            return render_template('bookform.html', form=form, ermes=e.message)
        return redirect(url_for('history'))
    return render_template('bookform.html', form=form)