Python Daily
2.57K subscribers
1.48K photos
53 videos
2 files
38.8K links
Daily Python News
Question, Tips and Tricks, Best Practices on Python Programming Language
Find more reddit channels over at @r_channels
Download Telegram
I am struggling a dynamic form field, need guidance please.

In my Flask application I have 2 directories and 1 file.

directory1: templates

directory2: static

file: __ init __.py


My __ init __.py files content look like this (I know i have literally deleted all of my stupid request/get/post code so as not to confuse you and myself so that we can start from scratch.

from flask import Flask, render_template
app = Flask(__name__)

@app.route('/')
def indexPage():
return render_template('index.html')


if __name__ == "__main__":
app.run()


This is something i will add later to the page (but just wanted to let you know my intentions..


@app.route('/resultsPage')
def futurefunc():
#api call using string html from form field
#return results from api call
#pass those results onto another html page.


I have an index.html file in the templates directory. A css and a js file in the static directory.

The link below shows what my index.html page looks like and the HTML form code, JS and CSS code that supports it.

Link: http://codepen.io/hecalu/pen/EVQvmv

Overall it is a simple page with a search bar. But, for the life of me, and believe me, I have been trying for ages... to create a post request that takes information from the index pages form field and passes it into a python script (which I am planning to add later). This simple task has been so complicated for me because I have very limited basic knoweldge of JS, CSS and HTML. I hope that someone knows how i can pass a string from this specific form field as mentioned/shown in the link to a backend python script. In the future I hope to run an api call from the string entered and return the api results on a new page. Please, help me out, I am in dire need. Thank you!



/r/flask
https://redd.it/5xevzl
Trouble getting Filtering working with ViewSet

I'm relatively new to Django but generally have figured out how to use filtering quite effectively. However, I have encountered a situation that I can't resolve:

class FeatureStatsViewSet(ModelViewSet):
queryset = FeatureStats.objects.all()
serializer_class = FeatureStatsSerializer
permission_classes = (permissions.IsAuthenticated,)

# TODO: Not sure why this is only returning one record during testing!
def get_queryset(self):
user = self.request.user
pipelines = Pipeline.objects.filter(createdBy=user.id)
features = Feature.objects.filter(pipeline=pipelines)
return FeatureStats.objects.filter(feature=features)
#return FeatureStats.objects.all()


What this code is supposed to do is return 'FeatureStats' for the currently authenticated user. My approach has worked correctly for lots of other tables but not for this one.

"FeatureStats.objects.all()" returns all 10 records in my test data, which is correct.
"FeatureStats.objects.filter(feature=features)" is supposed to return 9 records, which are the ones that belong to the currently authenticated user via the Pipeline class, which has a UserId field. Unfortunately it only returns 1 record.

I added "print()" statements from top to bottom in the aforementioned code. Everything appeared correct down to "features", which showed only the 11 features connected to the authenticated user and not the 1 feature which belonged to another user. But then the last statement just doesn't function correctly, returning only one record.

Any ideas what I might be doing wrong?

Robert

/r/django
https://redd.it/6anhyn
What is up with this return redirect line?

main is just my homepage and / is the url. For some reason, I can't get signUp to return back to the homepage after finishing.
return redirect(function) goes return redirect(main) (since thats the name of home being rendered.

I can also confirm 'here' and 'Registered' get printed. Also, in my terminal, i get

127.0.0.1 - - [23/Apr/2018 23:13:51] "GET / HTTP/1.1" 200 -

Which means it SHOULD be going to home, because I get the same line when I just click the home link on the page. It redirects too. What happens with the flask is it just stays on the login page. Nothing else, no errors thrown. Just sits there.

@app.route("/")
def main():
return render_template('Senty.html')

@app.route('/signUp',methods=['POST','GET'])
def signUp():
# still need to create signup class and transfer below code to new file
conn = mysql.connect()
cur = conn.cursor()

try:
_name = request.form['inputName']
_email = request.form['inputEmail']
_password = request.form['inputPassword']

# validate the received values
if _name and _email and _password:

cur.callproc('sp_createUser',(_name,_email,_password,))
print ("Registered")
data = cur.fetchall()

conn.commit()
json.dumps({'message':'User created successfully !'})
print('here')
return redirect(url_for('main'))

#else:
#return json.dumps({'html':'<span>Enter the required fields</span>'})

#except Exception as e:
#return json.dumps({'error':str(e)})

finally:
cur.close()
conn.close()

@app.route('/showSignIn')
def showSignIn():
return(render_template('login.html'))

I'm not sure where to go. I feel like I've tried everything.


/r/flask
https://redd.it/8ei5hq
Custom error handing in Flask

I have developed an upload form to take specific .xlsx file as upload. The requirement is to handle any exceptions for upload of non xlsx (for e.g. zip, exe file). I am using pyexcel library for reading the upload. I tried creating following code to handle this exception:

&#x200B;

https://i.redd.it/1zncaibdnwz11.png

&#x200B;

&#x200B;

https://i.redd.it/3l29byqgnwz11.png

&#x200B;

The error handling code is as follows:

&#x200B;

`class FILE_TYPE_NOT_SUPPORTED_FMT(Exception):`

`pass`

&#x200B;

`@app.errorhandler(FILE_TYPE_NOT_SUPPORTED_FMT)`

`def custom_handler(errrors):`

`app.logger.error('Unhandled Exception: %s', (errrors))`

`return render_template('400.html'), 400`

&#x200B;

and the upload code is as follows:

&#x200B;

`@users.route("/oisdate_upload", methods=['GET', 'POST'])`

`@login_required`

`def doimport_ois_date():`

`msg=None`

`if request.method == 'POST':`

&#x200B;

`def OIS_date_init_func(row):`

`#`[`c.id`](https://c.id) `= row['id']`

`c = Ois_date(row['date'],row['on'],row['m1'],row['m2'],row['m3'],row['m6'],row['m9'],row['y1'],row['y2'],row['y3'],row['y4'],row['y5'],row['y7'],row['y10'])`

`return c`

&#x200B;

`request.save_book_to_database(`

`field_name='file', session=db.session,`

`tables=[Ois_date],`

`initializers=[OIS_date_init_func])`

`msg = "Successfully uploaded"`

`#return redirect(url_for('users.doimport_ois_date'), code=302)`

`if((Ois_date.query.order_by(Ois_date.date.desc()).first()) is not None):`

`date_query = Ois_date.query.order_by(Ois_date.date.desc()).first()`

`start_date = date_query.date`

`date_query1 = Ois_date.query.order_by(Ois_date.date.asc()).first()`

`end_date = date_query1.date`

&#x200B;

`return render_template('OISdate_upload.html',msg=msg, start_date=start_date,end_date=end_date)`



I am unable to figure out how to correctly capture the error and handle it, any feedback would be appreciated.

/r/flask
https://redd.it/9zfa4s
Jinja variable not showing passed through rendertemplate()

I have the following flask route:

@dashblueprint.route('/uploadblogimage', methods='POST')
@loginrequired
def uploadblogimage():
img = request.files.get('uploadBlogImage')
data =
img.stream.read()

md5
name = hashlib.md5(data).hexdigest()
filename = f'{md5name}.{img.mimetype.split("/")[-1]}'

blob
serviceclient = connecttoblob()
blob
client = blobserviceclient.getblobclient(container='blog-images-dev', blob=filename)
blobclient.uploadblob(data)

token = getcreatesastoken(currentuser.id, 'blog-images-dev')
accessurl = f'{blobclient.url}?{token.sastoken}'

print(access
url)

#return redirect(urlfor('blogging.editor'))
return rendertemplate("blogging/editor.html", updatedurl=accessurl)

&#x200B;

And in my html file:

<div class="modal fade" id="imageModal" tabindex="-1" role="dialog" aria-labelledby="imageModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">


/r/flask
https://redd.it/rfjrag