#web-development
2 messages ยท Page 110 of 1
hello all
i'getting my hand on Django queries
and i am supposed to have 80ish entries for a model
this model have a link in the format following DATE_XXX@YYY
if i do
e_tor = e.filter(boxscore_link__icontains='XXX')
it will only filter those with the format @XXX and not the ones with XXX@YYY why ?
because i want to get all objects where DATE year = 2019 and XXX is present in field
Can anyone help me understand what the problem here is when launching my Flask app using Gunicorn and Docker: https://paste.pythondiscord.com/itutagitoy.sql
This works just fine when running it locally on my system
@cold socket it can't do your import .. my guess is maybe in your dockerfile you're not installing your reqs?
you could perhaps bash into your container to see if everything is where you expect it to be but it seems like though it can see app it can't see Stores
ah, interesting
and Im importing it in another file called checker.py
and theyre in the same directory
hello all
i'getting my hand on Django queries
and i am supposed to have 80ish entries for a model
this model have a link in the format following DATE_XXX@YYY
if i do
e_tor = e.filter(boxscore_link__icontains='XXX')
it will only filter those with the format @XXX and not the ones with XXX@YYY why ?
because i want to get all objects where DATE year = 2019 and XXX is present in field
@quick schooner are you sure your filtering is correct ? because i tried on my machine, filter still able to find with icontains="XXX" and found example data with "XXX@2019"
oh ok glad you figured it out
yeah debug always help ๐
if i show you my models file would you be able to tell me waht to improve ? because i'm really struggling rn on how to model efficiently my models to make simple queries
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
i have many queries i want to make
but a good start would be the following
find all Linescores fitlering by Season year and Team abbreviation
i am wondering if i really need to have so much sub classes to my main Event class
because my Event is linked to a Boxscore which is linked to a Linescore
yeah let me read over and see
dw thanks a lot
a suggestion when you have troubles figuring out models it's easier to see with a UML diagram of tables
here how to generate it for django https://simpleit.rocks/python/django/generate-uml-class-diagrams-from-django-models/
nice !
its a mess lol
i made a Linescore as a sub of boxscor just to organise better (think it is ) from just having Linescore linked to Event just as betpp class
so i want to get all linescores of a team Events from a certain year how would i do that please ?
one of the issue i see is i cant filter my Events by team since i dissociated home and visitor Team in event
@quick schooner from the UML you can see that Linescore FK to Team and FK to Event
yes
@quick schooner for starter if you want to filter by year you can use __year on filter with DateTime or Date data https://docs.djangoproject.com/en/3.1/ref/models/querysets/#year
so i should filter Event there since it s the only class with a date right ?
yes filter by Event.date
i see 2 path you can choose:
- Linescore -> Boxscore(boxscore_id) - > Event(event_id).date
- Linescore -> Team(visitor_team) ->Event(visitor_team but the FK relation is reversed)
so i suggest query by the first method
ok
because event and Team has opposite FK relation so it's hard to do query on
filter(Linescore__Boxscore__Event_date__year=YYYY)
reverse i mean if you look at the UML
ok
boxscore contain fk of event
but team don't contain fk of event
but it reverse: event has fk of team
but i could shortcircuit it and fk linescore to event no ?
yeah you can
ok
i don't know basketball so i'm not too familiar with it's leauge system ๐
haha its ok dw ^
but yeah have Linescore FK with event is easier
thats what i thought yes
you can have Linescore.event_id
in the real life i think it's the same score usually connected to event leauge
well in my logic
u have event
event has a boxscore wich will score all infor relatives to scores like linescore with quarter scores and playerstats also in boxscore
but it is overflow yes
so o k i load all events
possibly, but database is not my main field, you can ask about designing database in #databases ๐
i can only help with framework stuffs like query,... ๐
i have loaded all games from 2019 now with date__year ='2019'
nice
now how can i filter with teams ?
because my issue is
the fk to Team
is showing home or visitor team only
so i an only filter by home or visitor and not by simple Team
like if i have PHI@TOR
here visitor is Phila and home is Toronto
with my model i can only model from home or visitor team right
but if i want to get all games wether Toronto is at home or visitor how can i do that ?
yes Event is the class for game
@quick schooner use OR or IN statement in your query
let me check IN
is this an AND ?
e_tor_2019 = e_2019.filter(visitor_team__abbreviation='TOR' AND home_team__abbreviation='TOR')
i tried this
@quick schooner
OR statement https://stackoverflow.com/a/739799/11225821
you looking if TOR with OR right ?
or is in 1 of those
and required both need to be TOR(which is not possible)
eithe one or other so its a or u are right
^^
nice
i tried to mix the three queries
where e is the list of events
but i still have other years events
what is wrong here ?
(visitor team = 'tor' OR home_team = 'tor') AND date__year=2019 @quick schooner
is this easier to see ?
the AND gives me syntax error
so it should be
e.filter((Q(visitor_team__abbreviation='TOR',) | Q(home_team__abbreviation='TOR')), date__year='2019')
django ORM don't have AND syntax
and is , in query
okkk
got it
works great
i cannot thank you enough for sharing you knowledge with me in a sympathic and efficient and patient way ๐
glad to help
and now
from this list of eents
if i want to access the data in the linescore ?
you have list of events
and your linescore have fk to events
so the logic should be linescore has event IN events
so this is where the __in query come in
but __in only work with a list
ok
and you need a list of event id
ok
to get id list of query you use .values_list('id', flat=True)
well linescore has fk to boxcore which has fk to event in the current state
@quick schooner oh ok so you have to do
Linescore.objects.filter(boxscore_id__event_id__id__in=a)
ok i got Related Field gort invalid lookup
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
i edited the query above a few times so i guess you copy the wrong thing
Linescore.objects.filter(boxscore_id__event_id__id__in=a)
Hey i am trying to deploy my flask web app in heroku but it is saying application error
This is my error
at=error code=H14 desc="No web processes running" method=GET path="/" host=simply-con.herokuapp.com request_id=996bdf6d-5a93-48b0-bc5a-b95383427023 fwd="49.207.138.206" dyno= connect= service= status=503 bytes= protocol=https
And here is my code https://github.com/Prasanna-Natarajan-3595/Trash
Can anyone help me what is wrong pls.
@quick schooner yes is the list of events you got from the one before that
oh it is a list ok
in checks the list ok
gets me an empty queryset unfortunately
Out[305]: <QuerySet [107088, 107102, 107119, 107128, 107141, 107163, 107178, 107197, 107207, 107223, 107241, 107245, 107263, 107277, 107305, 107328, 107341, 107352, 107367, 107381, '...(remaining elements truncated)...']>
In [306]: Linescore.objects.filter(boxscore_id__event_id__id__in=a)
Out[306]: <QuerySet []>
In [307]: b = Linescore.objects.filter(boxscore_id__event_id__id__in=a)
In [308]: b
Out[308]: <QuerySet []>
a haha no you haven't applied .values_list('id', flat=True) to a yet
i believe i did ๐ฎ
you flow should be like so
a = Events.objects.filter((Q(visitor_teamabbreviation='TOR',) | Q(home_teamabbreviation='TOR')), date__year='2019').values_list('id', flat=True)
b = Linescore.objects.filter(boxscore_id__event_id__id__in=a)
it's like this ?
are you sure that in your data b has any values ?
linescore that contain boxscore that contain event id year=2019 ?
In [316]: a
Out[316]: <QuerySet [107088, 107102, 107119, 107128, 107141, 107163, 107178, 107197, 107207, 107223, 107241, 107245, 107263, 107277, 107305, 107328, 107341, 107352, 107367, 107381, '...(remaining elements truncated)...']>
In [317]: b = Linescore.objects.filter(boxscore_id__event_id__id__in=a)
In [318]: b
Out[318]: <QuerySet []>
welll idk
maybe check your database
see if any linescore has event_id = one of those results from a
are you using mysql or postgres as your database?
postgres
can you access your postgres data with pgadmin ?
for query IN statement of postgres
SELECT *
FROM table
WHERE some_id = ANY(ARRAY[1, 2])
you copypaste the a list in array part
i tried with one id
select * from public.stats_event where id= '107088'
and it returns the row correctly
huh.
oh nvm it's table name
yes its table
like with two separate querysets
like do you need both a and b?
or what
or do you only need a because you want those IDs to query b
i m looking to acces Linescore stats from a query set of Event
you can see above he querying for linescore that contain event with year=2019 and has (home_team OR visitor_team = 'TOR')
so it should be 2 queries
queryset of event being games wher etor is visitor and home and year is 2019
a itself contain many filter logics so it need to be separate
i'm thinking his database might not has the data satisfied his query
possibly also
can you access django admin ?
you can search from there
generate admin of linescore
not sure how
oh then nvm
as in
my question is
do you need the queryset of Event or not?
like independent of the queryset of Linescore
i'm not sure tbh
you should post your logic
or do you just want the Linescore instances
that correspond to certain criteria over events?
okay, let me put it this way
i think i just want and need the Linescores
say you solve your problem with the above querysets a and b
do you need a for anything?
okay.
can you explain again
which linescores you need?
but i cant filter the linescores with my model
lets say i need
all line scores
of games of 2019 of the team TOR
okay
can you post your models
which fields would those be?
do you have like a DateTimeField that corresponds to the game date etc.
and which model is that in?
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
so this is my model.py
also an image of it
and the Linescore fieelds i'm intersted in Linecore
ok
got it
normally what you call your classes doesn't really matter apart from being a minor eyesore but I don't know how that would screw with Django's conventions
anyway
okay so
Linescore.objects.filter(Q(visitor_team__abbreviation='TOR') | Q(home_team__abbreviation='TOR'), boxscore__event__date__year=2019)
incidentally
your Boxscore related_name for the event PK is weird
related_name is what the other side calls you
so like
Boxscore.event -> the Event relating to boxscore
it is confusing mee also i just set it up so that i didnt havee 'clashes' from django
you missed the OR statement
@gaunt marlin wups yeah, fixed
basic principle of naming in python usually
class: CamelCase
variable, function: use _ for separation
it is confusing mee also i just set it up so that i didnt havee 'clashes' from django
@quick schooner you probably have clashes for another reason
in any case, good naming is very important
that related_name is basically asking...
what do you want to call the Boxscore models that are related to an Event?
and right now you have event.event
because you set your related_name to 'event'.
oh my GOD you called your related field event_id?
thats bad yes
just call it event
in your Boxscore model
yeah, you need to fix that or the query I gave you won't work
alternatively you can change the last filter to boxscore__event_id__date__year=2019, which is...pretty weird.
also in Django don't name field with _id because django will auto add _id at the end of column name
for example:
user_id = ForeignKeyField, django will auto set in database column name = user_id_id
well since myy model was already confusing me
yes i put event_id in boxscore to remberber it was the foreignkey towardds the even id haha
ok i didnt know that nice
could you provid a better models.py architecture i could use ?
i feel that this is way more omplicated how i did it than how it is supposed to be done with django logic
it's not actually related to Django but your database design
you can ask in #databases
ok cool doing it rn
hey guys i have a question
{
"data1": {
some data
}
}
i want to append data2 to this file in the exact same way as data1 is
You can add using obj["data2"] = data2
"data2" would be the key, data2 is the variable storing the stuff after :
Im working though CS50 Web Development. Just to be sure i understand the layout (typing it out without googling helps me commit to memory) My website is bascially an app. Within that app, i have to define the webpages in urls.py and views.py which assigns a url path to each html file and renders the webpage based on which html file is called (respectively). These python files allow for coding in the html file as well as dynamiclly updating paths right?
urls.py maps a url to a python function in your views.py
The functions in views.py renders the template htmls
Also yay to cs50 web
HTML and CSS lecture were easy. Did that in like a day. I have to break up lecture 3 into multiple days as to not overwhelm myself and actually take in the info. Thanks for the response.
Hi hoping to get some advice.
Is there any good python web framework, that can create a web server while at the same time be able to send via web sockets every few minutes?
Django or Flask
also note that you'll need a separate library to handle websockets
neither of them do out of the box
.
does anyone know why my main.css file in my static folder not loading ?(flask)
I used url_for(), and i have it imported too, idk why it isnt working
like it didnt take full affect..
Good day! I need help or tip how to upload info from file to Django app db.
I need to upload info from gist file(Myfile.CSV) to my Django app database. Can anybody give me suggestion how to do it more correctly? I have gist file which is located on github. It's a csv file wich containes 3 columns(number, name, colour) and several rows. So I need to upload(save) to existing Django project info from this file and after it change names of columns to different one.
https://stackoverflow.com/questions/64675291/how-to-upload-gistcsv-file-to-django-app-database
nevermind i figured it out, my static folder was inside my templates one
Can someone tell me this?
I'm deploying my flask application on aws ec2 engine.
I created a default vm and ssh'ed into it.
Firstly I disabled all incoming traffic
Then I allowed ssh on port 22 and http on port 80.
I downloaded my code from github.
Downloaded all packages required.
And ran the flask app with debug ttrue for development testing.
The app ran successfully there's no error, but on visiting the public ip the page isn't loading neither the debug is showing the get request made.
@tame kelp What does your code for that look like?
i figured it out
my static folder was inside my templates one
so basically my route wasnt correct
@devout coral yeah in generally. Rubber duck debugging is works ;)
good morning
How to make API POST request in js?
ajax
@stable kite https://www.w3schools.com/xml/ajax_intro.asp
here is a good resource
How do I verify?
can you show me some code?
@stable kite u need to set allowed hosts in settings.py
U need a library called django cors I think
Search it up and read the docs on that then you can allow incoming requests from allowed hosts
@stable kite u need to set allowed hosts in settings.py
@native tide i have done that
U need a library called django cors I think
@native tide i will try it
Uhhh what auth method are u using
Yeah to use allowed hosts you need the library
Corsheaders
i am using drf
And then set it in installed apps
Yeah but you need corsheaders to set allowed hosts
does anyone know how i would go about showing the 'print' commands from my script to show up on my html home page when the user presses send? This is my flask app:
from flask import Flask, render_template, request
from My_script import resend_data
app = Flask(__name__)
@app.route('/')
def main():
return render_template ("home.html")
@app.route('/process', methods=['POST'])
def process():
# Retrieve the HTTP POST request parameter value from 'request.form' dictionary
_username = request.form.get('username') # get(attr) returns None if attr is not present
_password = request.form.get('password')
_UID = request.form.get('UID')
# Validate and send response
resp = resend_data(_username, _password, _UID)
#subprocess.call(["python","myscript.py"], shell=True)
return render_template("some_page.html", response=resp)
#def response():
# return render_template ("out.html")
if __name__ == '__main__':
app.run(debug=True)
you can't use the print() function in an html. It's python
@digital hinge What I usually do is render the same html template but in different view and flash message. Do you only want to let user know login done OK?
@proper owl I have a form that the values _username, _password and _UID are being entered. When they click "submit" it processes the script. The Flask terminal shows the PRINT objects but id like to show them on the html page (Ajax maybe?)
send them to the view yeah.
to do it simple you can pass something to render_template("some_page.html", response=resp,uid = _uid, username = _username)
and in html template acces it by {{username}} {{uid}}
it depends on problem complexity xd
i want it to show on the home.html. The some_page i have is actually the 'done result'": ```html
<html>
<head>
<title>Some</title>
</head>
<body>
The response was:
<p>{{ response.reason }}</p>
<h2>Download a file</h2>
<p>
<a href="{{ url_for('.download_file') }}">Download</a>
</p>
</body>
</html>
ok
I deleted one script with flask and I dont remeber when this script was turn on or not
Closes thing i could find to something similar to what im trying to do would be here: https://stackoverflow.com/questions/54689392/flask-display-flash-messages-constantly but im not successful yet
so I have another script with flask .. and when I turn on this I see in localadress old resoult
do you understand me?
@hybrid patio maybe try to refresh your browser by Ctrl + F5?
i had same problem at the beggining with css style not updating
Hey guys, I'm trying to build a simple Chat application using Django. Found an official Django tutorial online - https://channels.readthedocs.io/en/stable/tutorial/
When I completed part 2, I'm facing an issue. My issue is as below. :
When 1st browser joins a room it works just fine. But the moment a new browser session joins the same room, the first session does not get the messages and 2 messages are sent to the latest browser session.
If a third browser session joins the room, 1st and 2nd sessions don't get the messages and the third session gets all the 3 messages.
I followed every step meticulously but not able to fix the issue.
Can anyone help me, please?
from flask import Flask
app = Flask(__name__)
app.route("/")
def simple_text():
return "Hello everyone"
if __name__ == "__main__":
app.run()
why show me text Hello in my browers
maybe cookes?
๐
So im wondering if there is simple way to put every print command from a script on the webpage 'home.html' instead of the console of the server?
webpage script
ill assume this means javascript
use console.log in the script it will print to the client console
@digital hinge still have problem?
Yes, just wanting to show the output of my ython script on my html page when they hit the send button
from flask import Flask, render_template, request
from My_script import resend_data
app = Flask(__name__)
@app.route('/')
def main():
return render_template ("home.html")
@app.route('/process', methods=['POST'])
def process():
# Retrieve the HTTP POST request parameter value from 'request.form' dictionary
_username = request.form.get('username') # get(attr) returns None if attr is not present
_password = request.form.get('password')
_UID = request.form.get('UID')
# Validate and send response
resp = resend_data(_username, _password, _UID)
#subprocess.call(["python","myscript.py"], shell=True)
return render_template("some_page.html", response=resp)
#def response():
# return render_template ("out.html")
if __name__ == '__main__':
app.run(debug=True)
ok is My_script module your own script?
the home.html has a form that gets a couple of vlues and passes these value to y python script. The server console shows me the print values but i would like them to show on the html page as well
yes
ok any error?
the resend_data is the function from My_script that launches. No errors runs beutifully, just no process bar or anything that tells the user its working
so i was hoping i could display the print log after 'send' has been press on the 'home.html' form
what it does maybe your resend_data method is wrong?
what the mehod does? maybe itll help more
Everything is working. Im just trying to show the script is processing on the client side. So I have a server with Flask, app.py (flask app), that launches the My_script function when the home.html form is filled out and 'send' is pressed. on the Flask run terminal i can see all the objects its 'printing' but i want to show this log as a stream on the html page
your resend_data has parameters but im not sure where the problem is because i think the flask server is working good
maybe theres something wrong with your own module
and im seeing your some_page template. i cant see any method views named download_file
some_page is the page that appears after the script has completed
url_for is usually used for a method name
i dont think there gotta be a dot before it
download_files downloads the zip file i create with the My_script.
@app.route('/download')
def download_file():
#path = "html2pdf.pdf"
#path = "info.xlsx"
path = f"{_UID}.zip"
#path = "sample.txt"
return send_file(path, as_attachment=True)
so theres a dot in here url_for('.download_file')
you placed it before your methodview name
everything works, just want to make this here in "home.html" so show the output of the My_script ```html
<form action="process" method="post">
<input type="text" id = "UID" name = "UID" placeholder="Enter URLโ">
<input type="text" id="username" name = "username" placeholder="Usernameโ">
<input type="password" id="password" name="password">
<button class="ui-component__password-field__show-hide" type="button" onclick="text()" id="button">Show</button>
<input type="submit" id = "btnSubmit" value="SEND">
</form>
<script>
<p>{{ output }}</p>
my source for that download function was from here: https://www.roytuts.com/how-to-download-file-using-python-flask/ but it works ๐
i want it to show on the home.html. The some_page i have is actually the 'done result'": ```html
<html>
<head>
<title>Some</title>
</head>
<body>
The response was:
<p>{{ response.reason }}</p><h2>Download a file</h2>
<p>
<a href="{{ url_for('.download_file') }}">Download</a>
</p>
</body>
</html>
there is a dot(.) before your {{ url_for('.download_file') }}
remove it
Okay
U need a library called django cors I think
@native tide thanks it worked
django and Flask?
django and Flask?
@digital hinge ??
Sorry, thought that was the response to my question about Viewing real-time console on a web page with Flask python
@nimble epoch Any idea how i can View real-time console on a web page with Flask python for the home.html when this is pressed: value="SEND
usually javascript used for real-time webpages but im not sure that i got your right?
so the flask console is the python output. Thats what im after
what type of service are you trying to make?
@app.route('/button/')
def button_clicked():
print 'Hello world!' #output in the console
return redirect('/') #output in the webpage
@digital hinge I wouldn't go about writing to a client console at all in that case. I would have an alert in the form of a popup show after pressing a button. Here is a resource for that specific action : https://www.w3schools.com/js/js_popup.asp
@cold haven What about a process bar then?
@nimble epoch that is only showing a print, ot the output from the script My_script.py
I would make a request for a resource on the server by using an ajax post, and then returning it, and then you can put it wherever you want in the view.
Maybe you would want it in a popup box.
@digital hinge you have create two flask app?
This sounds more like a job for Django.
@cold haven no difference
ofc it's different
you want to create just a download button right?
no My_script downloads files, its the wait time i want to show the python console output on the home.html page
so you gotta return it
If i can implement this, that would work : https://discordapp.com/channels/267624335836053506/366673702533988363/773513383890124810
you gotta use redirect using flask
you want the client download the file then get redirected to the other page?
the files download when they press the 'send' button and it can take up to 5 min
you want to avoid sending redirects from the client and use a router on the server-side.
need like a process bar or to show the server console output for the print commands so the user can see the files are downlaoding
so...
I think what @digital hinge want is to display the logs created by his script WHILE it's running. The solution you just linked seems like a good idea but it's a bit hacky and not optimized. A solution could be to use websocket, but I've never used Flask, I don't know how it can be handled.
you want to create a download bar for what exactly? requests are almost instantaneous except when downloading GBs of info. @digital hinge
yeah not sure but i think hes right theres extension called flask_socketio i think thisll help
i dont know exactly how it works or does it work for you but...
@nimble epoch something like this: https://github.com/miguelgrinberg/Flask-SocketIO/tree/master/example
Socket.IO integration for Flask applications. Contribute to miguelgrinberg/Flask-SocketIO development by creating an account on GitHub.
yep
and theres a tutorial in youtube...
I introduce Flask-SocketIO in this video by creating a simple chat app. Lookout of for other SocketIO videos where I create more complicated apps.
To download the cheat sheet, go here: https://prettyprinted.com/flaskcheatsheet
Join my free course on the basics of Flask-SQLAl...
You first need to connect your front (JS) to a websocket Flask view that emits an event whenever a log is created (that's the hard part), when the JS gets an event it displays it in the html page.
is javasciprt necessary?
maybe jQuery is better.
that javascript too
or React
hate javascript
Yeah I think it's necessary, you need to make your page dynamic
Websocket work with an emitter (Flask) and a receiver (JS)
oh you mean with RESTful API
Flask vs Django for chat app
no difference
What about something like this: ```py
@app.route('/yield')
def index():
def inner():
proc = subprocess.Popen(
['dmesg'], #call something with a lot of output so we can see it
shell=True,
stdout=subprocess.PIPE
)
for line in iter(proc.stdout.readline,''):
time.sleep(1) # Don't need this just shows the text streaming
yield line.rstrip() + '<br/>\n'
return flask.Response(inner(), mimetype='text/html') # text/html is required for most browsers to show th$
oh sorry i dont use subprocess
how else are you going to send requests to the server w/o js is the question, if only you use it for REST I think.
you need json objects
@digital hinge try it yourself see it works or not
HTTP is not asynchronous, you call it, it gives you an answer right away, so that don't work I think
back in the day of PHP you would serve a static html from the server and that's it. You would use php forms.
The link you gave earlier is maybe simpler, you call a view that gives every log you had so far every X seconds, and place the response in your html body
you can send a form in htmI believe, you use SOAP
The link you gave earlier is maybe simpler, you call a view that gives every log you had so far every X seconds, and place the response in your html body
so the page reloads every second am i right?
@nimble epoch ```py
from flask import Flask, render_template, send_file, request
import time
from My_script import resend_data
import subprocess
app = Flask(name)
@app.route('/yield')
def index():
def inner():
proc = subprocess.Popen(
['dmesg'], #call something with a lot of output so we can see it
shell=True,
stdout=subprocess.PIPE
)
for line in iter(proc.stdout.readline,''):
time.sleep(1) # Don't need this just shows the text streaming
yield line.rstrip() + '<br/>\n'
return flask.Response(inner(), mimetype='text/html') # text/html is required for most browsers to show th$
@app.route('/')
def main():
output = execute('./script')
return render_template ("home.html",output=index)
_UID = None #Global decleration
@app.route('/process', methods=['POST'])
def process():
# Retrieve the HTTP POST request parameter value from 'request.form' dictionary
_username = request.form.get('username') # get(attr) returns None if attr is not present
_password = request.form.get('password')
global _UID #Global Value across functions
_UID = request.form.get('UID')
# Validate and send response
resp = resend_data(_username, _password, _UID)
#classes = resend_data(_UID)
#subprocess.call(["python","myscript.py"], shell=True)
return render_template("some_page.html", uid=_UID, response=resp)
#def response():
return render_template ("out.html")
@app.route('/download')
def download_file():
#path = "html2pdf.pdf"
#path = "info.xlsx"
path = f"{_UID}.zip"
#path = "sample.txt"
return send_file(path, as_attachment=True)
#source: https://www.roytuts.com/how-to-download-file-using-python-flask/
app.run(debug=True)
No need to reload if you use JS and ajax
I could give you the JS script if you're not confortable with JS
return render_template ("home.html",output=index)
^
IndentationError: unindent does not match any outer indentation level
so final answer is YOU SHOULD USE JAVASCRIPT
Yeah if you want a dynamic page JS is unavoidable ๐
maybe you would be better off using typescript and fetch
@cold haven Typescript needs compilation, it seems a bit heavy, plain JS is enough
typescript is like the updated version of JQuery.
@digital hinge i think i found a new problem in your app in '/' route
i'm used to using high level abstractions in coding so that's what I would go with in any case. No need to reinvent the wheel for smaller tasks even. Especially if you have lots of sample code available that you can copy/past into different projects.
the output variable youve set in the render_template is set to something called index
are you going to make a docker container for your server @digital hinge ?
I have a good resource for setting that up if you want.
No plans for that yet, its just a locally ran server qtm
Would it be possible to implement this? I not sure how it would go for multipule users tho?
from flask import Response, escape
from yourapp import app
from subprocess import Popen, PIPE, STDOUT
SENTINEL = '------------SPLIT----------HERE---------'
VALID_ACTIONS = ('what', 'ever')
def logview(logdata):
"""Render the template used for viewing logs."""
# Probably a lot of other parameters here; this is simplified
return render_template('logview.html', logdata=logdata)
def stream(first, generator, last):
"""Preprocess output prior to streaming."""
yield first
for line in generator:
yield escape(line.decode('utf-8')) # Don't let subproc break our HTML
yield last
@app.route('/subprocess/<action>', methods=['POST'])
def perform_action(action):
"""Call subprocess and stream output directly to clients."""
if action not in VALID_ACTIONS:
abort(400)
first, _, last = logview(SENTINEL).partition(SENTINEL)
path = '/path/to/your/script.py'
proc = Popen((path,), stdout=PIPE, stderr=STDOUT)
generator = stream(first, iter(proc.stdout.readline, b''), last)
return Response(generator, mimetype='text/html')
@app.route('/subprocess/<action>', methods=['GET'])
def show_log(action):
"""Show one full log."""
if action not in VALID_ACTIONS:
abort(400)
path = '/path/to/your/logfile'
with open(path, encoding='utf-8') as data:
return logview(logdata=data.read())
ive made a log file in My_script to log the output and save it as logfile.txt
#########
#Logging#
#########
class multifile(object):
def __init__(self, files):
self._files = files
def __getattr__(self, attr, *args):
return self._wrap(attr, *args)
def _wrap(self, attr, *args):
def g(*a, **kw):
for f in self._files:
res = getattr(f, attr, *args)(*a, **kw)
return res
return g
# for a tee-like behavior, use like this:
#sys.stdout = multifile([ sys.stdout, open('myfile.txt', 'w') ])
class Log(object):
def __init__(self, path_log, mode="w", encoding="utf-8"):
h = open(path_log, mode, encoding=encoding)
sys.stdout = multifile([ sys.stdout, h ])
sys.stderr = multifile([ sys.stderr, h ])
def __enter__(self):
""" Necessary if called by with (or with... as) """
return self # only necessary if "as"
def __exit__(self, type, value, tb):
""" Necessary if call by with """
pass
def __del__(self):
if sys is not None:
# restoring
sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__
log = Log("logfile.txt")
def stream(first, generator, last):
"""Preprocess output prior to streaming."""
yield first
for line in generator:
yield escape(line.decode('utf-8')) # Don't let subproc break our HTML
yield last
not sure it realy work
HTTP is not asynchronous, you call it, it gives you an answer right away, so that don't work I think
as Patiptop said
hmm
@digital hinge why dont you just use javascript?
its ok with frontend and of course backend too.
@digital hinge If you want my honest opinion. I would store logs inside of a DB, and Django can do that.
Django looks like it starting to be the better choice but ive just started with Flask... i wont give up with it just yet as ill have to redo it all
@digital hinge If you want my honest opinion. I would store logs inside of a DB, and Django can do that.
@cold haven he wants a real time website
Even just a progress bar so they know its actually doing something
Django looks like it starting to be the better choice but ive just started with Flask... i wont give up with it just yet as ill have to redo it all
@digital hinge sorry but you cant get what you want in flask ๐ and even django
@cold haven he wants a real time website
@nimble epoch you can use firebase if you want it realtime
@nimble epoch you can use firebase if you want it realtime
@stable kite really? using flask?
@stable kite so you mean real time chat or something like that without js?
@nimble epoch no i mean if you want realtime db than you can use firebase for anything
Here's what I'd make and then I need to get to work @digital hinge:
Flask :
- have a 'script' view that calls your script just like you did. Instead of printing the log in the console, write it in a log file (save it everytime you write something). Save this file with a name related to the user (could be an autogenerated name in JS that you put in a hidden field in your form).
- have a 'log' view that takes the famous autogenerated name in parameter, and read the JS file named like that, and returns the content.
Front (JS) :
When you submit the form, add a timeout (https://www.w3schools.com/jsref/met_win_settimeout.asp) that calls your log view using ajax (so the window don't reload). And display the answer of your request in a div in your html page. That'd be a 20 lines script at most, if you want I can write it for you.
you can use firebase if you want it realtime
@stable kite, firebase or not, you need JS to make the web page dynamic.
It can't be achieved using Python only
you can use firebase if you want it realtime
@stable kite, firebase or not, you need JS to make the web page dynamic.
@balmy stag thats for sure
But yeah you're right Firebase is a great idea
you can use firebase if you want it realtime
@stable kite, firebase or not, you need JS to make the web page dynamic.
the answer got clear
i found something but not sure its Pusher, right?
@balmy stag Thats good idea. The log view from the Flask ap tho?
Yep !
havent got that working yet. running to a ```py
return codecs.lookup(encoding).name == "ascii"
TypeError: lookup() argument must be str, not function
Hey @digital hinge!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
โข If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
โข If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
trying to utilise this one https://paste.pythondiscord.com/usenuferoj.py
Starting to think a progress bar with the popup message is a better idea for now...
yep wish you luck
until i find the time to learn firebase and update on JS skillset
I'm getting invested in your problem ๐, I could try to build something in a few hours and show you my ideas in a few hours (need to work right now)
I am interested @balmy stag
ill experiment with a progress bar for now while the function loads
may be simple
๐
if i know how to add this to my function in the Flask app this may be a solution: ```py
@app.route('/yield')
def index():
def inner():
for x in range(100):
time.sleep(1)
yield '%s<br/>\n' % x
env = Environment(loader=FileSystemLoader('templates'))
tmpl = env.get_template('result.html')
return flask.Response(tmpl.generate(result=inner()))
So this question is more a web question than a python question, but maybe you guys have an answer to it. Anyways, so this script running on my python flask server runs the function updateLiveData() much more frequent than once a second, more like every 200ms or so, why is this?
window.addEventListener('load', function()
{
var xhr = null;
getXmlHttpRequestObject = function()
{
if(!xhr)
{
// Create a new XMLHttpRequest object
xhr = new XMLHttpRequest();
}
return xhr;
};
updateLiveData = function()
{
var now = new Date();
// Date string is appended as a query with live data
// for not to use the cached version
var url = "{{ url_for('static', filename='log.txt') }}" + "?" + now.getTime();
xhr = getXmlHttpRequestObject();
xhr.onreadystatechange = evenHandler;
// asynchronous requests
xhr.open("GET", url, true);
// Send the request over the network
xhr.send(null);
};
updateLiveData();
function evenHandler()
{
// Check response is ready or not
if(xhr.readyState == 4 && xhr.status == 200)
{
dataDiv = document.getElementById('log');
// Set current data text
dataDiv.innerHTML = xhr.responseText;
// Update the live data every 1 sec
setTimeout(updateLiveData(), 1000);
}
}
});
</script>```
@upbeat imp this run because you have used setTimeout()
Yes, but not every second, its much faster. Like every 100ms or 200ms
@upbeat imp because 1000=1sec
But mine runs faster
no it should not run faster
Well it does, like 3-4 request every second
Changing the value inside setTimeout() does nothing to the delay, even a value of 200000 is same speed
@upbeat imp just get all functions out of eventlistner ()
i think you should first sent the request &then you should wait for response
You have example?
You have example?
@upbeat imp check this out
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
@upbeat imp are you simply trying to add some sleep to your code? Sorry. I was not following the conversation in its entirety.
Use vue and django together!
@upbeat imp are you simply trying to add some sleep to your code? Sorry. I was not following the conversation in its entirety.
@devout coral Hmm yeah sort of
updateLiveData runs to fast
setTimeout does nothing it seems
Well, it does call the function i guess, but not with a timeout
Well, I think it does call with a timeout I think it is calling itself...
Have you tried user setInterval() and taking it out of the function?
Have set interval set to 1 second and set it to your function.
I will try
It only does the GET request once if i put setInterval outside the eventHandler
Which makes sense, since there is no loop
Well, no setInterval is suppose to call the function every time on a set interval.
As opposed to setTineout which only calls it once
Did you mean outside the window.addEventListener function?
After this JS session, i will never complain about doing work in C again ๐ฅฒ ๐
Yes
hmm
No it only runs it once
I don't know how scope works in JS, but the setInterval is maybe outside the scope for the function its calling?
Let me see what you did.
Put the set interval inside of the onload event like where the function call is.
Like this? Same results, only runs once
Does js have a "dumb" delay? That does not require any functions call as parameter?
well fuck me
lol
uhm
So i have djangorestframework installed in my folder and it is also in the Pipfile but when i add 'rest_framework' in my SETTINGS of settings.py i get the error saying 'No module called rest_framework' found
So this worked
setTimeout(function(){
updateLiveData()
}, 1000);
How does that differ from this?
Set Timeout is used to add some delay in code
you need a function in it
it wont work without function
nope.. the function didnt have the {} at the end
you need to do updateLiveData = function(){}
I have to work on a complex project (complex from my level). How would i start ? like how do i plan what goes where and the database structure and stuff. i have a lot of time
It is a defined function further up in my code
ah well i got no idea then sorry
I have to work on a complex project (complex from my level). How would i start ? like how do i plan what goes where and the database structure and stuff. i have a lot of time
@near bison watch some tutorials and try to understand stuff before you move on to other stuff.. that shud do it ๐
that is up to you and what you are more experienced with and more comfortable with and this is a not a question to be asked in here
u can ask it in #python-discussion
So i have djangorestframework installed in my folder and it is also in the Pipfile but when i add
'rest_framework'in my SETTINGS of settings.py i get the error saying 'No module called rest_framework' found
do you use Docker or venv?
hi i'm back
you can't just use venv
you need both docker and venv I believe.
they both have their uses.
How are big projects actually planned by professionals?
You could use venv, but it's easier to create a docker container for making a cfg backup, and connecting your service to a DB.
After using venv
@upbeat imp try this
https://pastebin.com/uuSnPcLe
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
I wouldnt compare Docker to a Venv
I believe there are additional steps that you must take if you don't want to use docker.
Or use them the same
Venv's are useful for just organising multiple projects keeping dependancies seperate
Docker covers alot more than Venvs do
yeah, it basically just builds a local virtual environment.
How are big projects actually planned by professionals?
@near bison wdym?
No one should deploy their stuff by just using a standard python venv and a basic shell script
and if you do that you really aught to rethink
I agree.
@stable kite Like before you actually go into the programming part. you have to make a map of what goes where . right?
docker is what's used outside of a virtual env.
you need to set up environmental variables
@near bison right
As a perfect example -> One of my Servers went down unexpectantly and came back up 20 minutes later, Docker auto starts and sets up everything automatically without me touching anything
@near bison right
@stable kite How is that actually done in production?
In a virtual environment, you have to run a cmd to start the server, where docker would set up your DB and your service on a Server in the same manner by running a script.
is it true docker requires a lot of ram for db?
one my friend said
@near bison I think they have some idea & just start it & then think how to implement the part
docker is simply a script that runs in the OS.
the DB will use the same amount of Ram as it would normally At least it wont use any noticeable amount more
Docker is alot more than a script
alot more
@near bison I think they have some idea & just start it & then think how to implement the part
@stable kite LOL. really ?
ok sure
yeah it's a working linux image
people just start coding when they make a website ?
you could easily say that it is a script in a general sense, would you like to add something that it is? ๐
you need have a plan right?
Process manager
Server Daemon
Executable
Container manager
would probably all go before i use the word 'script' for docker lol
So i have djangorestframework installed in my folder and it is also in the Pipfile but when i add
'rest_framework'in my SETTINGS of settings.py i get the error saying 'No module called rest_framework' found
@near bison depends what it is
@faint umbra do you use docker?
no
@near bison yes
Large companies usually have seperate teams of Designers, developers etc...
or you could shorten it to a microservice.
@faint umbra try using venv, it always works as for me
whatever you think is faster.
that covers it all that you mentioned
Another reason i like docker -> No BS of command line linux python confusion
how can i use venv?
@faint umbra python3 -m venv <name_of_env>
and do source /venv/bin/activate to activate venv
then its "./venv/scripts/activate.bat"
ah ok ty
yeah
I need to build a website for a business. it needs like the basic information and stuff. the additional features needed are
- Inventory Management - They will update their inventory and clients can know how much they can order
- List of all their products
- Clients should be able to order products and pay online if they want . which can be sometime large amounts
- App should be available in multiple languages
- Clients can inform business about their requirements
๐ณ
THis is the project basicall
I don't know how i would plan this. how the db should look and how i would host it
i was hoping to get some help here
Did you get a job for a real business?
@faint umbra what shell do you use?
@faint umbra what shell do you use?
@covert pulsar powershell
@quick cargo
@near bison ok
How do i move ? what stack would i choose ?
@faint umbra try using some other path, but there this script should be
how would i plan it and how the db should look like and the tests
ehh sounds like something Django would fit reasonably into if it doesnt need to be massively performant per proc
multiple languages is hard no matter what you do but can just be different html files or what ever
django lacks performance?
Django slowwwwwwwwwwwwwwwwwwwwwwwwwwwwww
damn
I am new to Django, but have heard great things about it. I think stacks are moving more towards python in the future as well.
what would be a faster alternative ?
but it has everything in the box
For payment Stripe is a pretty good api or Paypal but that depends
do you actually need that performance though
probably not for small to mid sized apps
i don't know how much difference it makes
this is a small app right?
or a medium one?
B2C probably
pretty standard E-Commerce setup from what ive gathered
yeah, I don't know how they would update info in a database though when they get it. I think you need a database administrator for that sort of thing anyways.
if you're learning i can garentee you'll mess up
even if you're not learning you'll probably mess up at some point
django has an inbuild admin panel @cold haven
also inbuild templates
doesn't it fall somewhere in-between data warehousing?
i was hoping to get help from you guys through out
I think it would
I think the default django admin panel would work for me
stripe is supposed to be fairly easy to use for payments api wise
Django would probably be a good fit for you
what is Django admin panel? a preset template?
i haven't done all these stuff. but i have a lot of time to get this done
@cold haven arent you learning Django rn?
yes
Have you never came across the admin panel before?
to answer your question, no. I have seen it in other frameworks and CMS
what is Django admin panel? a preset template?
@cold haven Yes kinda, you can view , edit and add new entries to the db
kind of like phpmyadmin?
to make it work in different languages will i have to redo the templates in those languages ?
diffrent programming languages?
nope
did you read my question really quick?
website content languange
anyone know of phpmyadmin and if it's similar to that of Django Admin panel?
like english, french etc
sorta but not quite
its not as complete
idek how you havent came across that
cuz the ORM practically forces you to when you setup a project with the super user
anyone know of phpmyadmin and if it's similar to that of Django Admin panel?
@cold haven Compare to phpmyadmin django admin panel has a lot of {your_name} involved
anyways, I still think it falls under category of DB admin
or data warehousing of sorts
i don't think a normal manager can operate it that doesn't have knowledge in that field.
they could easily manage it
EASILY
the admin page is dead easy to use and very hard to get wrong without deliberately doing it wrong
I said if they don't have any knowledge in computers at all, and I'm talking at the microsoft excel level.
so it has a user-friendly UI
something that you can plug values into easily without knowing what a row or a column is
?
yeah that's nice
You have Users + Groups extra if you are a superuser
db listing etc...
and you can set it to add blobs or img
you can do alot with it
just a bit awkward to customise the style but most people dont care about that
how do i make the website in different languages (people language)? do i need to have a different template for each language?
A company would probably want their own software because it is unlicensed.
probably the easiest method
i refuse todo multi language stuff after the hell of previous usage with it
and how can i add a chat feature to it?
you want to make it look really good for a company, and especially if it is customized for a specific company.
you want it to look good.
- if you don't mind can you tell me a bit about the hosting part ? do i need to use aws (or some other clound plat)?
otherwise you're probably gonna overthink stuff while learning a system thats probably gonna be new to you
you dont need to use aws no
I have used aws before.
Django is a WSGI framework
it's nice
so will run on any WSGI webserver e.g. Gunicorn which can run on any VPS etc...
so ?
@near bison you can use pythonanywhere,heroku
Free hosts are very limiting though to add to that
what is downside in using aws ?
Err cost
Serverless can cost a shit ton if you fuck up your scaling
You definitely want to set it up on a cloud service, that way you don't have to worry about implementing the security yourself. You can just use Encryption as a service.
I am a complete beginner and I want to be a pro Django and Flash coder.
How and where to start?
Serverless's advantage is that you pay for what you use rather than a normal vps or Dedi that you pay monthly
do you think heroku will work for me ? for the current senario ?
You definitely want to set it up on a cloud service, that way you don't have to worry about implementing the security yourself. You can just use Encryption as a service.
@cold haven you mean ssl ?
yes
however, if you setup stuff up wrong or use more than you expect you can quite easily spend more than you would on a monthly thing
anyone?
You should know how to setup SSL anyway
that is a massive thing, dont rely on someone else doing it for you
@sly echo the Django tutorial
i can just watch a tutorial for the ssl stuff right ?
its not hard
Cloud has just about everything. You can set up a devops pipeline, backups, security, and DNS reporting.
I see.
Can you send me a link to the tutorial?
would heroku work for me
you need a SSL key and cert set from somewhere (Cloud flare do it for free) and then give gunicorn the SSL cert and key paths
err probably not
you are going to want to have a backup which is probably important for any organization.
you can but its a pretty bad idea
In this Python Django Tutorial, we will be learning how to get started using the Django framework. We will install the necessary packages and get a basic application running in our browser. Let's get started...
The code for this series can be found at:
https://github.com/Core...
what would be the right choice for me
it depends if you are running linux or windows.
A useful application for a dictionary is to remember, or cache,
previously obtained results so that they can be retrieved from the cache
when they are requested a new. Write a program so that the user can
repeatedly enter file names. If the user enters the same filename
more than once, look up the answer from a dictionary instead of
counting the words again.
you may want to go with azure if it's windows
@quick cargo could you help me with this?
A useful application for a dictionary is to remember, or cache,
previously obtained results so that they can be retrieved from the cache
when they are requested a new. Write a program so that the user can
repeatedly enter file names. If the user enters the same filename
more than once, look up the answer from a dictionary instead of
counting the words again.
@sly echo a set would work too
uh can someone help with a small prob?
wsforms.validators doesnt have Email validation built in?
use regex
just install it
or install it yh
pip install email_validator ?
pip install wtforms[email] should do it @tame kelp
alr
@near bison
could you write the program for me so I can look and understand it better?
with a dictionary or a set ?
need to instantiate it
I am weak with both.
can you do in the dictionary first?
@near bison
-> () call it
oh
oh yeah mb
k works ๐
also, you were saying i can use regex, but how do i apply my own conditions to my fields?
cache = dict()
while True:
filename = input("Enter a filename")
if filename in cache:
print("That was already entered")
else:
cache[filename] = 'Seen' # OR something else
print("That wasn't found in the cache")
``` @sly echo set would have been a better way
I see.
Can you show with set?
cache = set()
while True:
filename = input("Enter a filename")
if filename in cache:
print("That was already entered")
else:
cache.add(filename)
print("That wasn't found in the cache")
Thanks man
@quick cargo Do you guys follow a test first approach ?
wdym by that
probably means unit tests
oh then yes test the shit outa it
you use a framework for it? or just manual
though i admit im pretty bad using unit test itself
if i do tests i normally test individual things making a file that houses the test
@near bison
Thanks a lot.
i have a file that auto runs the tests then when i update stuff
Just one more help
function that takes in a string, removes the duplicating letters from the list and returns the new string. The first occurrence of the letter should not be removed.
what do you test though...
Is it done with .split?
well recently when its been with my framework Everything
The URL compiler that turns the placeholder strings into regex runs though every single possible combination of patterns with the pre made converters and and random set of filler strings
@near bison
@sly echo you can do that with a for loop...
a='aboo'
def removeDupWithoutOrder(a):
return "".join(set(a))
print (removeDupWithoutOrder(list(a)))
I cannot go ahead of it
I am really bad at it.
I feel so sad.
I want to become a pro python coder and I cant even solve such questions.
@sly echo sets are unordered, so while that's a good idea, it won't always give you the correct result.
And strings are iterable, so you can iterate through each character in the string with a for loop, ie:
for char in a:
string = "aaabbbccccd"
seen = set()
newString = ""
for letter in string:
if letter not in seen:
seen.add(letter)
newString += letter
print(newString)
This would work , right ?
I am trying to only display my searched results post search. How exactly would I achieve this?
q
Can someone help me with JavaScript and Jinja2? When I add Jinja inside a script tag, it throws a lot of errors but runs fine
Hey guys, I am new to django, just completed the polling application from the django documentation. Can you suggest where should start from?
q
@whole sierra huh , it should be client_info right? that's what you are looping over
if q
Can someone help me with JavaScript and Jinja2? When I add Jinja inside a script tag, it throws a lot of errors but runs fine
@nova shadow That's because they are not valid js syntaax
doesnt work :/
Yeah, but is there anyway to hide those errors?
doesnt work :/
@whole sierra tryif client_info
or should I just leave it?
Yeah, but is there anyway to hide those errors?
@nova shadow idk, there should be a vscode specific way to not show some errors, i am sure though, i don't even know even this is how you should achieve what you want, i haven't seen jinja templates editing js
alright thank you
Hello, is any differences between flask_security and flask_login. im using flask_login should i change it to flask_security?
string = "aaabbbccccd" seen = set() newString = "" for letter in string: if letter not in seen: seen.add(letter) newString += letter print(newString)This would work , right ?
@near bison not working
What part ?
function that takes in a string, removes the duplicating letters from the list and returns the new string. The first occurrence of the letter should not be removed.
Just wrap this inside a function
if I take the input as "Khaan"
It should return [Khan]
first occurrence of the alphabet in a string should remain
and the result should be in list
return [string]
def RumDep():
string = "aaabbbccccd"
seen = set()
newString = ""
for letter in string:
if letter not in seen:
seen.add(letter)
newString += letter
print([newString])
@near bison
Take string as a param
And return the final thing
def RumDep(string):
seen = set()
newString = ""
for letter in string:
if letter not in seen:
seen.add(letter)
newString += letter
return [newString]
@sly echo
Damn, i am on my phone, it's hard to edit
works now
thanks
I'm working on a portable browser experience using pyppeteer/headless chrome. Wondering if anyone could point me towards a pattern example for implementing CSS.takeComputedStyleUpdates & CSS.trackComputedStyleUpdates from ChromeDevTools API.
Seems like it would be much more efficient way for me to get computed styles but I'm having trouble grokking it.
https://chromedevtools.github.io/devtools-protocol/tot/CSS/#method-takeComputedStyleUpdates
roles=EmployeeRoleMap.objects.filter(empId=emp).order_by("-startDate")[0]
how to access all roles field?
I am trying roles.values("id","name")
doesn't work
here is my forms .py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import Profile
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'email','password1', 'password2']
# USER UPDATE FORM!!
class UserUpdateForm(forms.ModelForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'email']
#PROFILE UPDATE FORM
class ProfileUpdateForm(forms.ModelForm):
Committees = (
('IT','IT'),
('Design','Design'),
('ER','ER'),
('Design','Design'),
('Marketing','Marketing'),
('Coaching','Coaching'),
('Media','Media'),
('Branding','Branding'),
)
committee = forms.ChoiceField(choices=Committees, required=False)
class Meta:
model = Profile
fields = ['bio', 'image', 'position' ,'committee', 'achievement','awards', 'experience']
and here is my models.py
from django.db import models
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(User, on_delete= models.CASCADE)
bio = models.TextField(max_length=300)
Committees = (
('IT','IT'),
('Design','Design'),
('ER','ER'),
('Design','Design'),
('Marketing','Marketing'),
('Coaching','Coaching'),
('Media','Media'),
('Branding','Branding'),
)
committee = models.CharField(choices=Committees, max_length=10, default='')
position_list = (
('Member', 'Member'),
('Head', 'Head'),
('Vice', 'Vice'),
('President', 'President'),
)
position = models.CharField(choices=position_list, max_length=10, default='Member')
awards = models.TextField(max_length=300, null= True)
experience = models.TextField(max_length=300, null=True)
achievement = models.TextField(max_length=300, null=True)
image = models.ImageField(default='default.jpg', upload_to='profile_pics')
def __str__(self):
return f'{self.user.username} Profile'
```
please help me fix this error
please i just didnt do anything i was taking a look at the website again and found this error showed up
idk what is the wrong
please i really need help in this
and here is the template as well
Hi, I would like to contribute to some open source projects, can you recommend any for first time Python contributors?
๐
with what
Does Gunicorn expect your Flask application to follow a specific file structure like the Factories or Blueprint structures?
no
it doesnt care about that
it only imports the specified target file and get the what ever the variable that contains Flask() instance
For some reason Gunicorn seems to error out on my imports
But when I run flask locally without Gunicorn the app runs fine
Hereโs the error I keep getting. If anyone has any insight into why this could be happening Iโd be very grateful https://paste.pythondiscord.com/itutagitoy.sql
I usually combine authentication with a "users" app. Not totally sure on best practice though.
@cold socket most likely because of the CWD you're running the app in
"app" is probably just a user folder that is registered in the settings.py.
@broken abyss there is a built in django login/registration / auth system
Anyone ever displayed previews for PDFs/JPG/etc on a django template? I'm serving the file as an HttpReponse but it keeps auto-downloading rather than rendering in the browser
@rain ledge try serving the content as image instead:
return HttpResponse(image_data, content_type="image")
i'm mostly focused on PDFs to start, this is asking me how to save/open it
but i'm hoping that i can get browsers to just open PDFs in a new tab @gaunt marlin
oh ok you want to open in new tab
@rain ledge
return HttpResponse(file_data, content_type="application/pdf")
def read_pdf(filepath):
pdf_temp_file = NamedTemporaryFile(delete=True)
in_memory_pdf = r.get(filepath, stream=True)
for block in in_memory_pdf.iter_content(1024 * 8):
if not block:
break
pdf_temp_file.write(block)
pdf_temp_file.flush()
temp_file = files.File(pdf_temp_file, name="zd.pdf")
return temp_file
def ticket_attachment(request):
filepath = request.GET.get("filepath", None)
content_type = request.GET.get("content_type", None)
if content_type == "application/pdf":
pdf = read_pdf(filepath)
response = HttpResponse(pdf, content_type=content_type)
return response
@gaunt marlin thoughts?
this still triggers an auto-download
@rain ledge that is on frontend part, to open new tab you would have an anchor link with target attribute
<a href="you_image_or_pdf_url" target="_blank">click here to open new tab</a>
you_image_or_pdf_url is url for your HttpResponse views
<a href="{% url 'view-
file'%}?filepath={{attachment.content_url}}&content_type={{attachment.content_type}}" target="_blank">{{ attachment.file_name }}</a>
@gaunt marlin feel like i'm going crazy on this one
hey
uhhh
i suck doode
idk why im getting this error
everything here
i can only make shitty websites with html and css
๐ฎ
@steady owl how are you attempting to run it?
@rain ledge your design on the url path is kinda wrong, here how i would do it:
urls.py:
path('image/<str:image_path>', views.my_image, name='api.my_image'),
def my_image(request, image_path):
# codes
image_data = open(image_path, "rb").read()
return HttpResponse(image_data, content_type="image")
and in your template:
<a href="{% url 'api.my_image' image_path=attachment.content_url %}" target="_blank">{{ attachment.file_name }}</a>
you can also implement like so with pdf file
@steady owl how are you attempting to run it?
@rain ledge through the terminal
what is the command you're typing
bruh...
it's a package
@gaunt marlin I passed them in as url parameters (?param1=param1&) because it's a full url to a third party website where i'm downloading stored files from. I'm downloading the file then serving it back.
i'm able to download the file, the problem i'm having is on the return, it auto-downloads rather than opened in the new-tab as expected
@rain ledge to confirm what causing it first, can you try adding a default image path in your code to see if it will download the image or open new tab?
because target="_blank" is how you open new tab
yeah, target="_blank" is in heavy use on the same template*
does it open new tab ?
just a working example for html
<a href="https://www.w3schools.com/howto/img_avatar.png" target="_blank">test</a>
yeah that opened
<a href="https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf" target="_blank">test</a>
so it's working
that PDF auto-downloaded, the image opened
OMFG is this seriously a browser default setting
maybe
ug now it works. @gaunt marlin what's your venmo i'll buy you a coffee
_blank also based on your browser settings
haha it's fine glad i can help though ๐
๐ thank you
Has anyone worked with python and Tor? I need to have a server that receives a small .txt or some bytes, but i dont know if i need ftp, tcp...? Im so lost. Maybe someone knows any hints
Please tag me if you answer, ty
hello people
this is my url:
how can I grab the /65909865 from the href being passed??
all i need to that number ๐
def home_view(request, pk)
Hi
How can I not be forced to write all extending code in every template?
atm i write this in every page
{% extends 'base.html' %}
{% load static %}
{% block content %}
i love this just to be default behavior of all template files, unless i type something else
find a solution for static
'builtins': [
'django.templatetags.static',
],