Example #1
0
def add_sale():
    form = AddForm()

    if form.validate_on_submit():
        new_sale = TractortekSales(sales_team_lead=form.sales_team_lead.data,
                                   item_code=form.item_code.data,
                                   emp_id=form.emp_id.data,
                                   year=form.year.data,
                                   week=form.week.data,
                                   quantity=form.quantity.data)

        sql = (
            f"Insert into tractortek_sales (sales_team_lead, item_code, emp_id, year, week, quantity) "
            f"values ('{form.sales_team_lead.data}', "
            f"'{form.item_code.data}',"
            f"'{form.emp_id.data}', "
            f"'{form.year.data}', "
            f"'{form.week.data}', "
            f"'{form.quantity.data}');")
        #repr(eval(sql))
        db.engine.execute(sql)

        return redirect(url_for("index"))
    else:
        return render_template('add.html', form=form)
Example #2
0
def add_student():
    form = AddForm()
    student = Student.query.all()
    next_index = 0
    if len(student) == 0:
        next_index = 1
    else:
        next_index = len(student) + 1

    if form.validate_on_submit():
        student = Student(student_id=u"MKT%s" % str(next_index),
                          first_name_en=form.first_name_en.data,
                          last_name_en=form.last_name_en.data,
                          first_name_kh=form.first_name_kh.data,
                          last_name_kh=form.last_name_kh.data,
                          gender=form.gender.data,
                          date_of_birth=form.date_of_birth.data,
                          phone=form.phone.data,
                          email=form.email.data,
                          address=form.address.data)
        db.session.add(student)
        db.session.commit()

        flash('Student has been registered successfuly!', category='success')
        return redirect(url_for('index', option='active'))
    return render_template('add_student.html', form=form)
Example #3
0
def add(request):
    if request.method=='POST':
        form = AddForm(request.POST)
        if form.is_valid():
            blog = form.save()
            return HttpResponseRedirect(reverse('blog_list'))
    return render_to_response('blog/add.html',RequestContext(request,{'form':AddForm()}))
Example #4
0
def begin(request):
    def parse(feed):
        feed = feedparser.parse(settings.FEED_DIR+feed)
        feed.channel.description = feed.channel.description.encode('utf-8')
        return {'data': feed,
                'edit_form': AddForm(QueryDict(urllib.urlencode(feed.channel)))}
    
    #feeds = map(parse, os.listdir(settings.FEED_DIR))

    if request.method == 'POST':
        form = AddForm(request.POST)
        if form.is_valid():
            rmg = RichMetadataGenerator.getInstance()
            m = rmg.getRichMetadata()

            m.setTitle(form.cleaned_data['title'])
            #m.setLanguage(form.cleaned_data['language'])
            #m.setGenre(form.cleaned_data['genre'])
            
            print rmg.prettyPrint(rmg.build(m))
            

            return HttpResponseRedirect('/')
    else:
        form = AddForm()

    context = {'feeds': [],
               'MEDIA_URL': settings.MEDIA_URL,
               'add_form': form}
    context.update(csrf(request))
    
    return render_to_response('browse.html', context)
Example #5
0
def add_data():
    form = AddForm()

    if form.validate_on_submit():
        name = form.name.data
        age = form.age.data
        tsh = form.tsh.data
        t3 = form.t3.data
        tt4 = form.tt4.data
        t4u = form.t4u.data
        fti = form.fti.data

        # Add new Puppy to database
        new_data = Hypothyroid(name, age, tsh, t3, tt4, t4u, fti)
        db.session.add(new_data)
        db.session.commit()
        input_values = new_data.input_data()
        data_arr = new_data.data_array()
        predictions = hypothyroid_pred(data_arr)
        # return redirect(url_for('list_data')),
        # return redirect('json.html', json_data=json_data)
        return render_template('result.html',
                               input_values=input_values,
                               data_arr=data_arr,
                               predictions=predictions)
    else:
        return render_template('add.html', form=form)
Example #6
0
File: iot.py Project: rlunding/iot
def request_add_photon():
    """Request add photon

    This endpoint will make the node search for the appropriate node of which
    the photon should be added to. If such a node is found without any error,
    the photon will be added to it.

    :param photon_id: the particle-io id of the photon that should be added to the network.
    :returns: html page with node information, and information about the operation.
    """
    add_form = AddForm()
    if add_form.validate_on_submit():
        photon_id = request.form.get('photon_id')
        if node.request_photon_add(photon_id):
            key = encode_key(photon_id)
            flash(
                'Successfully added photon to the network, with key: ' +
                str(key), 'success')
        else:
            flash('Failed to add photon to the network', 'danger')
        return redirect(url_for('home'))
    join_form = JoinForm()
    search_form = SearchForm()
    return render_template('home.html',
                           node=node,
                           join_form=join_form,
                           add_form=add_form,
                           search_form=search_form)
Example #7
0
def add(request):
    if request.method == 'POST':
        form = AddForm(request.POST)
        if form.is_valid():
            hostname = form.cleaned_data['hostname']
            asset = form.cleaned_data['ip']
            group_id = form.cleaned_data['group_id']
            template_id = form.cleaned_data['template_id']
            if asset.ip:
                ip = asset.ip
            elif asset.other_ip:
                ip = asset.other_ip
            else:
                ip = '127.0.0.1'
            if asset.asset_type in [2, 3]:
                returns = zabbixAPI.addSnmpDevice(hostname, ip, group_id,
                                                  template_id)
            else:
                returns = zabbixAPI.addHost(hostname, ip, group_id,
                                            template_id)
            messages.add_message(request, messages.SUCCESS,
                                 u'创建成功:{0}'.format(returns))
            return HttpResponseRedirect(reverse('ADD'))
    else:
        form = AddForm()
    return render(request, 'zabbix/add.html', locals())
Example #8
0
def add_data():
    form = AddForm()

    if form.validate_on_submit():
        name = form.name.data
        age = form.age.data
        tsh = form.tsh.data
        t3 = form.t3.data
        tt4 = form.tt4.data
        t4u = form.t4u.data
        fti = form.fti.data

        if name == "" or age == "" or tsh == "" or t3 == "" or tt4 == "" or t4u == "" or fti == "":
            return render_template('add.html', form=form)

        else:
            new_data = Hypothyroid(name, age, tsh, t3, tt4, t4u, fti)
            db.session.add(new_data)
            db.session.commit()
            input_values = new_data.input_data()
            data_arr = new_data.data_array()
            predictions = hypothyroid_pred(data_arr)

            return render_template('result.html',input_values=input_values, \
                data_arr=data_arr, predictions=predictions)
    else:
        return render_template('add.html', form=form)
Example #9
0
def add():
    """

    :return:
    """
    form = AddForm(request.form)
    if request.method == 'POST' and form.validate():
        data = request.form
        filename = 'item-10.jpg'
        if 'image' in request.files:
            photo = request.files['image']
            try:
                check_fold = os.path.isfile(
                    os.path.abspath(os.getcwd()) + '/' +
                    app.config['UPLOADED_PHOTOS_DEST'] + '/' + photo.filename)
                if check_fold is not False:
                    filename = str(photo.filename)
                else:
                    filename = photos.save(photo)
            except UploadNotAllowed:
                return redirect(url_for('error',
                                        message='INVALID FILE UPLOAD'))
        good = Goods(name=data['name'].title(),
                     price=data['price'],
                     quantity=data['quantity'],
                     image=filename)
        db.session.add(good)
        db.session.commit()
        return redirect(url_for('index'))
    else:
        print(form.errors)
    return render_template('add.html', form=form)
Example #10
0
def add_bt7j0srn69():
    form = AddForm()
    if form.validate_on_submit():
        playlist_id = form.playlist.data
        db.seed_playlist.insert({"playlist_id": playlist_id})
        flash('Playlist added')
        return redirect('/add_bt7j0srn69')
    return render_template('add.html', form=form)
Example #11
0
def update(request,id):
    blog = get_object_or_404(Blog,pk=int(id))
    if request.method == 'POST':
        form = AddForm(request.POST,instance=blog)
        if form.is_valid():
            blog = form.save()
            return HttpResponseRedirect(reverse("blog_list"))
    return render_to_response('blog/add.html',RequestContext(request,{'form':AddForm(instance=blog)}))
Example #12
0
 def add_unicorn():
     form=AddForm()
     if form.validate_on_submit():
         name=form.name.data
         new_unicorn=Unicorn(name)
         db.session.add(new_unicorn)
         db.session.commit()
         return redirect(url_for('list_unicorn'))
     return render_template('add.html',form=form)
Example #13
0
def add_monkey():
    form = AddForm(request.form)
    if form.validate_on_submit():
        monkey = Monkey(name=form.name.data, age=form.age.data,
                        email=form.email.data, friends=[], bf=None)
        db.session.add(monkey)
        db.session.commit()
        flash(monkey.name + ' successfully added')
        return redirect(url_for('list_monkeys'))
    return render_template('add.html', form=form)
def add_pup():
    form = AddForm()

    if form.validate_on_submit():
        name = form.name.data
        pup_name = Puppy(name)
        db.session.add_all([pup_name])
        db.session.commit()
        return (redirect(url_for('list_pup')))
    return (render_template('add.html', form=form))
Example #15
0
def add_pup():
    form = AddForm()
    if form.validate_on_submit():
        name = form.name.data
        # Add new Puppy to DB
        new_pup = Puppy(name)
        db.session.add(new_pup)
        db.session.commit()
        return redirect(url_for("list_pup"))
    return render_template("add.html", form=form)
Example #16
0
def adddevice():
    form = AddForm()

    # Eingabe
    if request.method == 'GET':
        # get args from home
        if request.args.get('servername'):
            sn = request.args.get('servername')
            print(sn)
            dn = "(servername=%s)" % sn
            print(dn)
            vms = ldap_search(dn)
            print(vms)

            form.servername.data = (vms[0][0][1]["servername"][0])
            form.internalname.data = (vms[0][0][1]["internalname"][0])
            form.mainresponsible.data = (vms[0][0][1]["mainresponsible"][0])
            form.substitute.data = (vms[0][0][1]["substitute"][0])
            form.costcenter.data = (int(vms[0][0][1]["costcenter"][0]))
            form.location.data = (vms[0][0][1]["location"][0])
            form.department.data = (vms[0][0][1]["department"][0])
            form.servertype.data = bool(vms[0][0][1]["servertype"][0])
            form.serverdescription.data = (
                vms[0][0][1]["serverdescription"][0])
            form.serverservice.data = (vms[0][0][1]["serverservice"][0])
            form.workloadservice.data = int(vms[0][0][1]["workloadservice"][0])
            form.workloadintime.data = (vms[0][0][1]["workloadintime"][0])
            form.privacyrelatedfiles.data = bool(
                vms[0][0][1]["privacyrelatedfiles"][0])
            form.dependencies.data = (vms[0][0][1]["dependencies"][0])
            form.redundancy.data = (vms[0][0][1]["redundancy"][0])
            form.bootorder.data = (vms[0][0][1]["bootorder"][0])
            form.impactforotherserver.data = (
                vms[0][0][1]["impactforotherserver"][0])
            form.departmentaffected.data = (
                vms[0][0][1]["departmentaffected"][0])
            form.furtherwork.data = bool(vms[0][0][1]["furtherwork"][0])
            form.cost.data = float(vms[0][0][1]["cost"][0])
            form.serviceaccount.data = (vms[0][0][1]["serviceaccount"][0])
            form.purposeaccount.data = (vms[0][0][1]["purposeaccount"][0])
            form.manuallyrestart.data = (vms[0][0][1]["manuallyrestart"][0])
            form.otherinformation.data = (vms[0][0][1]["otherinformation"][0])
            return render_template('add.html', form=form)
        else:
            return render_template('add.html', form=form)

    elif request.method == 'POST':
        # Fehler
        if not form.validate():
            flash('Error, validation faild.')
            return render_template('add.html', form=form)
        else:
            print(form.servername.data)
            return render_template('add.html', form=form)
Example #17
0
def add_character():

    form = AddForm()
    if form.validate_on_submit():
        name = form.p_name.data
        date = form.p_date.data
        new_date = Characters(date)
        new_char = Characters(name)
        db.session.add(new_char, new_date)
        db.commit()
        return redirect(url_for('characters'))
    return render_template('add-character.html', form=form)
Example #18
0
def add():
    form = AddForm(csrf_enabled=False)
    if request.method == "POST" and form.validate_on_submit():
        user = Data()
        print form.data
        code = user.add(
            form.data["firstname"], form.data["lastname"], form.data["number"], middlename=form.data["middlename"]
        )

        return render_template("add.done.html", code=code, data=form.data)
    else:
        return render_template("add.html", form=form)
Example #19
0
def add():
    # Adding Addform so we can get the data from the home page
    add_form = AddForm()
    #If it does not validate, return home
    if not add_form.validate_on_submit():
        flash("Name or Description too long")
        return redirect(url_for('home'))
    # Setting variable to data for easy reading
    item_name = add_form.name.data
    description = add_form.description.data
    add_backpack(item_name, description)
    return redirect(url_for('home'))
Example #20
0
def add_student():
    form = AddForm()

    if form.validate_on_submit():
        name = form.name.data

        new_student = Student(name)
        db.session.add(new_student)
        db.session.commit()

        return redirect(url_for('list_student'))

    return render_template('add.html', form=form)
Example #21
0
def menusetup(user):
    form = AddForm()
    available = []
    localrepopath = settings.WORKING_DIR + user.nickname
    for sub in os.listdir(localrepopath):
	subpath = localrepopath + "/" + sub
        if os.path.isdir(subpath):
           available.extend([(sub,sub)])
	   available.extend(allsubdirectories(user, sub, "|-", localrepopath))
    form.location.choices = available

    types = [("None","Other"), ("mkdir","Directory")]
    languages = Language.query.all()
    for lang in languages:
	types.extend([(lang.filetype,"." + lang.filetype)])
    form.type.choices = types
    
    if request.form.get('bar', None) == 'Add':
        if form.validate_on_submit():
	    userlocation = form.location.data	     
	    locationpath = settings.WORKING_DIR + user.nickname + "/" + userlocation
	    if os.path.isdir(locationpath):
		filepath = locationpath + "/" + form.filename.data
		if form.type.data == "mkdir":
		    if not os.path.isdir(filepath):
			p1 = subprocess.Popen(["sudo", "mkdir", filepath])
                	p1.wait()
			flash('New Directory Created', 'success')
		    else:
		    	flash('Directory already exists', 'error')    
		else:
		    if not form.type.data == "None":
		    	filepath = filepath + "." + form.type.data
        	    if not os.path.exists(filepath):
            	    	open(filepath, 'a').close()
		    	repository = userlocation.split("/")[0]
            	    	myrepo = user.repos.filter_by(repourl= "/" + repository + "/" ).first()
			filename = form.filename.data
            	    	if not form.type.data == "None":
				filename = form.filename.data + "." + form.type.data
			f = File(filename=filename, path=userlocation, type="txt", repo=myrepo)
			
			flash("Created file " + filename + " in " + userlocation, 'success')
            	    	db.session.add(f)
            	    	db.session.commit()
		    else:
			flash('File or directory already exists', 'error')
        else:
	    flash('Name of new file or directory must not have spaces or slashes', 'error')
    cleanprocess()
    return form
Example #22
0
def add_book():
    form = AddForm()

    if form.validate_on_submit():
        title = form.title.data
        author = form.author.data
        price = form.price.data
        new_book = Books(title, author, price)
        db.session.add(new_book)
        db.session.commit()

        return redirect(url_for('book_list'))

    return render_template('add_book.html', form=form)
Example #23
0
def adddevice():
    form = AddForm()

    # Eingabe
    if request.method == 'GET':
        # get args from home
        if request.args.get('servername'):
            sn = request.args.get('servername')
            print(sn)
            dn = "(servername=%s)" % sn
            print(dn)
            vms = ldap_search(dn)
            print(vms)

            form.servername.data = (vms[0][0][1]["servername"][0])
            form.internalname.data = (vms[0][0][1]["internalname"][0])
            form.mainresponsible.data = (vms[0][0][1]["mainresponsible"][0])
            form.substitute.data = (vms[0][0][1]["substitute"][0])
            form.costcenter.data = (int(vms[0][0][1]["costcenter"][0]))
            form.location.data = (vms[0][0][1]["location"][0])
            form.department.data = (vms[0][0][1]["department"][0])
            form.servertype.data = bool(vms[0][0][1]["servertype"][0])
            form.serverdescription.data = (vms[0][0][1]["serverdescription"][0])
            form.serverservice.data = (vms[0][0][1]["serverservice"][0])
            form.workloadservice.data = int(vms[0][0][1]["workloadservice"][0])
            form.workloadintime.data = (vms[0][0][1]["workloadintime"][0])
            form.privacyrelatedfiles.data = bool(vms[0][0][1]["privacyrelatedfiles"][0])
            form.dependencies.data = (vms[0][0][1]["dependencies"][0])
            form.redundancy.data = (vms[0][0][1]["redundancy"][0])
            form.bootorder.data = (vms[0][0][1]["bootorder"][0])
            form.impactforotherserver.data = (vms[0][0][1]["impactforotherserver"][0])
            form.departmentaffected.data = (vms[0][0][1]["departmentaffected"][0])
            form.furtherwork.data = bool(vms[0][0][1]["furtherwork"][0])
            form.cost.data = float(vms[0][0][1]["cost"][0])
            form.serviceaccount.data = (vms[0][0][1]["serviceaccount"][0])
            form.purposeaccount.data = (vms[0][0][1]["purposeaccount"][0])
            form.manuallyrestart.data = (vms[0][0][1]["manuallyrestart"][0])
            form.otherinformation.data = (vms[0][0][1]["otherinformation"][0])
            return render_template('add.html', form=form)
        else:
            return render_template('add.html', form=form)

    elif request.method == 'POST':
        # Fehler
        if not form.validate():
            flash('Error, validation faild.')
            return render_template('add.html', form=form)
        else:
            print (form.servername.data)
            return render_template('add.html', form=form)
Example #24
0
def add_tractor():
    form = AddForm()

    if form.validate_on_submit():
        name = form.name.data

        # Add new Tractor to database
        new_tractor = Tractor(name)
        db.session.add(new_tractor)
        db.session.commit()

        return redirect(url_for('list_tractor'))

    return render_template('add.html',form=form)
Example #25
0
def add_pup():
    form = AddForm()

    if form.validate_on_submit():
        name = form.name.data

        # Add new Puppy to database
        new_pup = Puppy(name)
        db.session.add(new_pup)
        db.session.commit()

        return redirect(url_for('list_pup'))

    return render_template('add_pup.html', form=form)
Example #26
0
def create():
    """
    create page: get sentences from users via form
    if the information is valid then redirect back to index page
    """
    form = AddForm(request.form)
    # check if the information entered in the form is valid
    # if valid then store the sentence in the database
    if request.method == 'POST' and form.validate():
        sentence = Sentences(sentence=form.sentence.data)
        db.session.add(sentence)
        db.session.commit()
        return redirect(url_for('index'))
    return render_template('create.html', form=form)
def add_user():
    form = AddForm()

    if form.validate_on_submit():
        name = form.name.data
        email = form.email.data

        # Add new User to database
        new_user = User(name, email)
        db.session.add(new_user)
        db.session.commit()

        return redirect(url_for('list_user'))

    return render_template('add.html',form=form)
Example #28
0
def new(request):
	if request.method == 'POST':
		form = AddForm(request.POST)
		if form.is_valid():	
			#cd = form.cleaned_data
			newtask_name = form.cleaned_data['taskname']
			newtask_description = form.cleaned_data['taskdescription']
			#newdeadline_date = form.cleaned_data['deadlinedate']
			t = Task(task_name=newtask_name, task_description=newtask_description, deadline_date=timezone.now())
			t.save()
		return HttpResponseRedirect('/tasker/')
	else:
		form = AddForm()
	time = str(timezone.now())
	lol = time
	return render(request, 'tasker/new.html', {'form': form})
Example #29
0
def add(request):
    form = AddForm(request.POST or None)
    if form.is_valid():
        # add object
        data = {
            "status": "ok",
            "next_url": '/',
        }
    else:
        context = {'form': form, }
        html = render_to_string('main/form.html', context)
        data = {
            "status": 'invalid',
            "html": html
        }
    return HttpResponse(json.dumps(data), content_type="application/json")
Example #30
0
def update(request,id):

    BookDB=get_object_or_404(Book,pk=int(id)) 
    if request.method=="POST":

        form=AddForm(request.POST,instance=BookDB)

        if form.is_valid():

            BookDB=form.save()

            

            return HttpResponseRedirect(reverse("BookDB_list"))

    return render_to_response('update.html', {'form': AddForm(instance=BookDB)})    
Example #31
0
def add():
    form = AddForm(request.form)
    if request.method != "POST" or not form.validate():
        return render_template("admin_add.html", add_form=form)

    shortcode = form.shortcode.data
    target_url = form.target_url.data
    random = form.is_random.data

    if (not shortcode or len(shortcode) == 0) and not random:
        return abort("No shortcode specified.", 400)

    if random:
        # Make sure the target doesn't already have a random shortcode
        target = database_helper.find_by_target(target_url)
        if target and target.is_random:
            flash("Shortcode '%s' for this URL already exists. %s" % (target.shortcode, url_for_code(target.shortcode, target.target_url)), category="info")
            return render_template("admin_add.html", add_form=form)

        # Find an unused random shortcode
        count = 0
        while True:
            shortcode = get_random_shortcode(current_app.config["SHORTCODE_LENGTH"])
            if database_helper.get_shortcode_target(shortcode) is None:
                break
                
            # Make sure we don't loop endlessly
            count = count + 1
            if count > 4:
                flash("Could not find usable shortcode after 5 tries.", category="danger")
                return render_template("admin_add.html", add_form=form)
    else:
        # Make sure this shortcode doesn't already exist
        target = database_helper.get_shortcode_target(shortcode)
        if target:
            flash("Shortcode '%s' already exists to %s." % (shortcode, target.target_url), category="warning")
            return render_template("admin_add.html", add_form=form)

    if database_helper.insert_shortcode(shortcode, target_url, random):
        msg = "Shortcode '%s' added successfully. %s" % (shortcode, url_for_code(shortcode, target_url))
        category = "success"
    else:
        msg = "Failed to create shortcode."
        category = "danger"

    flash(msg, category)
    return redirect(url_for(".add"))
Example #32
0
 def add(self):
     from uliweb.utils import date
     from forms import AddForm
     
     form = AddForm()
     if request.method == 'GET':
         today = date.today()
         form.bind({'begin_date':today})
         return {'form':form}
     elif request.method == 'POST':
         #对提交的数据进行校验
         if form.validate(request.POST):
             obj = self.model(**form.data)
             obj.save()
             return redirect(url_for(self.__class__.index))
         else:
             return {'form':form}
Example #33
0
def add(request):
    if request.method == 'POST':
        form = AddForm(request.POST)
        if form.is_valid():
            newDate = form.cleaned_data['date']
            newWeight = form.cleaned_data['weight']
            w = Weight(weight=newWeight, date=newDate, username=request.user.username)
            w.save()
            return HttpResponseRedirect('/weight/')
    else:
        form = AddForm()
        t = loader.get_template('templates/weight_add.html')
        c = RequestContext(request,{
            'form': form,
            'user':request.user,
        })
        return HttpResponse(t.render(c))
Example #34
0
def edit(shortcode):
    result = database_helper.get_shortcode_target(shortcode)
    if result is None:
        return abort(404)

    form = AddForm(request.form, obj=result)
    if request.method != "POST" or not form.validate():
        return render_template("admin_edit.html", add_form=form, data=result)

    target_url = form.target_url.data

    if database_helper.update_shortcode(shortcode, target_url):
        msg = "Shortcode '%s' updated successfully. %s" % (shortcode, url_for_code(shortcode, target_url))
        category = "success"
    else:
        msg = "Failed to update shortcode."
        category = "danger"

    flash(msg, category)
    return redirect(url_for(".list"))
Example #35
0
def addItem():
    """
    Logged in user attempts to add an item

    :return: GET : Renders Add Item Form
             POST : Inserts added item to database and redirects user
             dashbiard page
    """
    form = AddForm()

    if form.validate_on_submit():
        item = Item(name=bleach.clean(form.name.data),
                    description=bleach.clean(form.description.data),
                    owner_id=int(current_user.get_id()),
                    category_id=int(form.category.data))

        db.session.add(item)
        db.session.commit()
        return redirect(url_for('main.dashboard'))

    return render_template('main/addItem.html', form=form)
Example #36
0
def add():
    bookname = None
    author = None
    sortedd = None
    introduction = None
    commentt = None
    score = None
    state = None

    if "s" not in session:
        return redirect(url_for("login"))

    form = AddForm()
    if form.validate_on_submit():
        bookname = form.bookname.data
        author = form.author.data
        sortedd = form.sortedd.data
        introduction = form.introduction.data
        commentt = form.commentt.data
        score = form.score.data
        state = form.state.data

        # file1=open('1.txt','a')
        # file1.write(score.encode('utf-8'))
        # file1.close()
        # session['bookname_a']=bookname
        # print bookname+"=="+author+"=="+sortedd+"=="+introduction+"=="+comment+"=="+score+"=="+state
        if not bookname and not author:
            flash(u"请重新填写")
        form.bookname.data = ""
        form.author.data = ""
        form.sortedd.data = ""
        form.introduction.data = ""
        form.commentt.data = ""
        form.score.data = ""
        form.state.data = ""

        addbooklist = books_record(
            id="id",
            bookname=bookname,
            author=author,
            sortedd=sortedd,
            introduction=introduction,
            commentt=commentt,
            score=score,
            state=state,
        )
        db.session.add(addbooklist)
        db.session.commit()

    return render_template(
        "add.html",
        form=form,
        bookname=bookname,
        author=author,
        sortedd=sortedd,
        introduction=introduction,
        commentt=commentt,
        score=score,
        state=state,
    )
Example #37
0
def edit_table(row_number_delete=None, row_number_update=None):
    try:
        table_name = request.form['table-name']
        session['table_name'] = table_name
    except KeyError:
        table_name = session['table_name']
    tables = {'books': Books, 'authors': Authors}
    model = tables[table_name]

    if row_number_delete is not None:
        item = model.query.filter_by(id=row_number_delete).first()
        db.session.delete(item)
        db.session.commit()
        return redirect(url_for('edit_table'))

    if row_number_update is not None:
        item = model.query.filter_by(id=row_number_update).first()
        columns_names = item.columns_names()[1:]
        columns_data = item.columns_data()
        if request.method == 'POST':
            if model == Books:
                new_book_title = request.form['name1']
                Books.query.filter_by(id=row_number_update).update(
                    {'book_title': new_book_title},
                    synchronize_session=False
                )

                new_authors_list = request.form['name2'].split(',')
                new_authors_list = [author_name.strip() for author_name in new_authors_list]
                authors_id_list = Books.query.filter_by(id=row_number_update).first().get_authors_id()
                for index, author_id in enumerate(authors_id_list):
                    try:
                        Authors.query.filter_by(id=author_id).update(
                            {'author_name': new_authors_list[index]},
                            synchronize_session=False
                        )
                        db.session.commit()
                    except IndexError:
                        item = Authors.query.filter_by(id=author_id).first()
                        db.session.delete(item)
                        db.session.commit()
                if len(authors_id_list) > len(new_authors_list) or not authors_id_list:
                    for new_author in new_authors_list[len(authors_id_list):]:
                        item = Authors(new_author)
                        db.session.add(item)
                        Book = Books.query.filter_by(id=row_number_update).first()
                        Book.append_author(item)
                        db.session.commit()

            else:
                Authors.query.filter_by(id=row_number_update).update(
                    {'author_name': request.form['name1']},
                    synchronize_session=False
                )
                db.session.commit()
            return redirect(url_for('edit_table'))
        return render_template('edit-row.html',
                               columns_names=columns_names,
                               columns_data=columns_data)

    form = AddForm(request.form)
    if form.one_of_two_validate():
        book_title = form.book_title.data.strip()
        authors_list = form.author_name.data.split(',')
        authors_list = [author_name.strip() for author_name in authors_list]
        if book_title and authors_list:
            item = Books(book_title, [Authors(author_name) for author_name in authors_list])
            db.session.add(item)
        elif not authors_list:
            item = Books(book_title)
            db.session.add(item)
        else:
            items = (Authors(author_name) for author_name in authors_list)
            [db.session.add(i) for i in items]
        db.session.commit()

    rows = model.query.all()
    rows = [row.columns_data() for row in rows]
    rows.insert(0, model.columns_names())
    return render_template('edit-table.html',
                           rows=rows,
                           table_name=table_name)