#web-development
2 messages · Page 136 of 1
@native tide fixed my problem what u need help for?
Can we talk privately so I could explain it to you throughly
yes ill do my best
i have a simple question which the different between get_object_or_404() and modlename.objects.all() i hope this make a sense
it doesnt cause get_object_or_404() is shortcut for modelname.objects.get()
oh! i think that was a shortcut
yes it is
class AddPackage(admin.ModelAdmin):
form = AddPackageForm
admin.site.register(Packages, AddPackage)
I have a form that I want to show within my admin dashboard. I'm just wondering how can I do something like if form.is_valid() here?
My form has ImageFields which I want to upload to an API before saving anything to my models. Should I just be using signals here? That was my thought, to use pre_save signals.
also saving your models in django admin does not send signals?
I think the validation should be at the model level
does it help ?
mhm, I tried pre_save but upon saving my models within the admin dashboard, but I'm not seeing any output. Brief look on SO and someone also said admin doesn't send signals (at least no pre_save - the usual ones).
looking at your post, they have this form:
from models import Product
from django import forms
class ProductForm(forms.ModelForm):
class Meta:
model = Product
exclude = [id, ]
def clean(self):
product_offer_price = self.cleaned_data.get('product_offer_price')
product_mrp = self.cleaned_data.get('product_mrp')
if product_offer_price > product_mrp:
raise forms.ValidationError("Product offer price cannot be greater than Product MRP.")
return self.cleaned_data
They rewrite clean, so could I just rewrite is_valid within my form?
oh iirc is_valid cleans the form first and if there are no validation errors it is therefore valid
so I can just extend clean within my form
that should work
bummer that signals isn't working though
Traceback (most recent call last):
File "/opt/anaconda3/lib/python3.7/site-packages/flask/cli.py", line 338, in __call__
self._flush_bg_loading_exception()
File "/opt/anaconda3/lib/python3.7/site-packages/flask/cli.py", line 326, in _flush_bg_loading_exception
reraise(*exc_info)
File "/opt/anaconda3/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/opt/anaconda3/lib/python3.7/site-packages/flask/cli.py", line 314, in _load_app
self._load_unlocked()
File "/opt/anaconda3/lib/python3.7/site-packages/flask/cli.py", line 330, in _load_unlocked
self._app = rv = self.loader()
File "/opt/anaconda3/lib/python3.7/site-packages/flask/cli.py", line 388, in load_app
app = locate_app(self, import_name, name)
File "/opt/anaconda3/lib/python3.7/site-packages/flask/cli.py", line 250, in locate_app
raise NoAppException('Could not import "{name}".'.format(name=module_name))
flask.cli.NoAppException: Could not import "development".
that's the error message
i don't get it i did FLASK_APP=app
FLASK_ENV=development
flask run
oh shoot i didn't do export FLASK_APP=app
i did it people i debugged my own code
whatever
from werkzeug.exceptions import abort
can someone explain what is abort?
what does that do???
Hey Everyone! Currently working on a project (ML-AI/WebDev) which involves music. We are building playlists that cover seven emotions("angry", "fear", "disgust", "happy", "sad", "surprised", "neutral"). To make the playlists more versatile, I am trying to get 5 or 6 songs from many different people. If you have the time, sending a song title and the emotion would be awesome!
Hello, I'm running flask and getting some 404's when my html is trying to pull in certain .css files.. I'm not sure why as the path is correct.
Heres my folder structure
├── project/
│ ├── config.py
│ ├── run.py
│ ├── env/
│ ├── app/
│ │ ├── init.py
│ │ ├── routes.py
│ │ ├── templates/
│ │ │ ├── prototype/
│ │ ├── index.html
│ │ ├── review/
│ │ ├── includes/
├── include-1614110632334.css
Here's the HTML in index.html
<link type="text/css" rel="stylesheet" href="./review/includes/include-1614110632334.css" />
dead channel lmao
code?
are you sure you haven't got any vpns or anything of that sort?
would that interfere?
also try to make the host "0.0.0.0"
I use a vpn because i live in dorms in school. so i just use replit for the flask coding
?
when you run it it should open a browser
because replits are hosted on the repl servers
take a screenshot of the last line
The last line is line 16
put app.run(host='0.0.0.0', port=8080) at the last line
Ok
@autumn yarrow it's blank look at the website name tho
are you sure index.html exists?
pls i don't even understand this goddamn flask tutorial
Lol
wasting my time rn
It's private
sure
Anyone know a good place to learn flask?
Hello, I am implementing a multi profile user to an existing project. It is for a website that places adverts for selling houses or offices. There is a User model and a UserProfile. We want to have different EstateCompanies where we can assign Users to this EstateCompany with a user that can be a 'normal' user and a 'manager' of the EstateCompany. That said, they also need to get different roles for example a normal user can only see his own adverts and a manager can see all adverts from all users that are assigned to that EstateCompany.. How to approach this?
Using Django
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
i wouldn't recommend this one as much tho i would recommend the one in "!resources"
this one is encouraging you to copy paste gigantic chunks of code
so no not good
Thanks man
yeah no problem
hi does anybody know how to connect python and JS so i want to make a key system in python and my friend is making a chrome extention (In JavaScript) is it possible to connect both?
i'd be down
since images are saved in django's ImageField in a binary format, can I base64 encode it (to use for stuff like imgur APIs)?
like @toxic flame said, have a api in python then use something like fetch(); in js
axios > fetch
never used it ¯_(ツ)_/¯
yea ajax, axios, plain js
oh man, ive done some serious work on my site today. built a brand new header, and menu, and search page. its been fun, not
i cant imagine why anyone would use flask over django
flask is way easier to learn
im a django/react person. if anyone has those questions
Flask is easy but i prefer django
yes django is better in terms of scalability
there are many built in features
and it is a framework apart from being a lib
guys, does facebook use react router?
Django FTW
The chances are high
how to make a dashborad for my bot
any flask-sqlalchemy users here? I have a function where i make quite a few changes then try to commit the transaction in the end. but now i want to commit the progress of the function in the middle so that the user can read the progress in the client.. how do i separate these two transactions?
how to put <body> in the middle of both width and height
Hey everyone. I'm trying use cloudinary and got weird situation.
In my model i specified two option ```python
picture_preview = models.ImageField(upload_to="uploads/home/services/serice-previews/", blank=True, null=True)
picture_preview = CloudinaryField('image', folder = "media/uploads/home/services/serices-preview/", null=True, blank=True)
When i'm using Django imageField I'm getting image url like ```"https://cloudinary.com/my_image"``` - without format extension.
In second scenario when i was trying use CloudinaryField i'm getting url like
```http://cloudinary.com/my_image.jpg``` with extension, but without https.
Have anyone meet this problem?
how to include a bot in my website
Selenium question: How can i wait for an element being located using explicit waits and run a script before every check?
element = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.ID, "myDynamicElement"))
)
Make a function containing your script and the selenium call.
thats my wait_for_element function:
def wait_for_element(driver: webdriver.Chrome, By_Mode, element_name, time=5):
try:
return WebDriverWait(driver, time).until(
EC.presence_of_element_located((By_Mode, element_name))
)
except:
print("element not found bruh")
driver.close()
and i want that it clicks a button (a refresh button on the page) and checks if the element is now there
i know that i can just use a while loop but there has to be a fancier way
have html code in one line, I want it to be a few lines and the tags should be in one line each how can i do this in python
ask your question then
I need help on everything, I can't do anything
don't expect yourself to learn everything at once, start with the small things!
what are you stuck on?
This good advice. This field has grown so incredibly complex in the last 20 (even less, 5?) years. I am sure it must be daunting to get into. Start with what you know, and be ready to fail often.
Hello, I writing a custom token auth as it involves two users and was wondering the correct way to go about it.
A user with a token can authenticate as other users. How should I handle this as part of the request?
The user with the token is a bot user that the actual user (the one that is being authenticated as) has sent a request to
Personally, I learned a lot from freecodecamp.org when it comes to front-end and back-end development. I went in with only the most basic HTML knowledge but I don’t even think you need that. Since using that site, I’ve been practicing with building a functioning website for my father-in-law and I’ve referenced to myfreecodecamp multiple times for help.
the way I have dealt with that in the past is using either a header or if you are using jwt, embedding it in the payload
and then doing the auth check in middleware
anyone know how to return, multiple querries at the same time in django/rest framework. i want to do a count on the search results, plus pass the first three results
I usually just return a response as a dictionary and return .values() of my query
return Response(data={"count": myCount
"query": myQuery.objects.filter().values()}, status=status.200...)
but it has to be serialized through rest framework to work, thats what im trying to figure out
that would work, the data is returned as JSON, .values() returns a dict.
You could also implement that into your own serializer
yea, but how. serializers have to be tied to fields or methods. i tried to do the serializers.serializerMethodField to count, but cant get it to work. because the initial is only 3, it only counts 3 in the in response and not a total of all
# serializer
class SearchProfileSerializer(serializers.ModelSerializer):
class Meta:
model = Profile
fields = ('id', 'username', 'profilePic', 'description')
#api
class SearchProfileApi(viewsets.ModelViewSet):
permission_classes = [
permissions.IsAuthenticated
]
serializer_class = SearchProfileSerializer
def get_queryset(self):
queryset = Profile.objects.all()
search = self.request.query_params.get('search', default=None)
initial = self.request.query_params.get('initial', default=None)
if search is not None:
queryset = queryset.filter(username__icontains=search)
queryLen = queryset.count() #want to pass this
print(queryLen) #this displays correctly
if initial is not None:
queryset = queryset[0:3]
return queryset
if i do the count in the serializer it would be
result_count = serializers.SerializerMethodField()
fields = ('id', 'username', 'profilePic', 'description', 'result_count')
def get_result_count(self, obj):
return obj.user_set.count()
so what's not working here? I'm not seeing it
you could also just give your model a property which returns the queryLen and append it to the data within your response.
I think you just need to return a dict of:
{"queryset": queryset, "count": queryLen}
and you should be sorted, apologies that I have nothing better to say, I'm not familiar with class based views 🥴
your fine, class based views are nice though. can do it all in one class get, post, delete without any duplicate code
i have a dumb question
can you keep HTML and CSS in the same file?
or do you have to save the CSS stuff as .css
you can have inline CSS
e.g. style=...
otherwise you add it as a stylesheet, and the .css is a separate file
yeah i think the tutorial i was following did it as the second option
i have an idea
if i mix both of the tutorials i will get a working flask thing w a login page
then i can add in the sqllite3 that i still have to learn (again)
its better to be in separate files.
<head>
<style type="text/css">
body {
background-color: #FFFFFF;
}
</style>
</head>
<!-- but this method is better //-->
<link rel="stylesheet" href="stylesheet.css" />
``` the first is document only, the second can be used by all
great i'll just do the second option then
i kind of forgot HTML/CSS from middle school but i think w3schools is a good source
you can also just add css inline as well <div style="color: #000000">Hello, World</div>
ok
<!DOCTYPE html>
<html>
<head>
<title>Login Form</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<h2>Login Page</h2><br>
<div class="login">
<form id="login" method="get" action="login.php">
<label><b>User Name
</b>
</label>
<input type="text" name="Uname" id="Uname" placeholder="Username">
<br><br>
<label><b>Password
</b>
</label>
<input type="Password" name="Pass" id="Pass" placeholder="Password">
<br><br>
<input type="button" name="log" id="log" value="Log In Here">
<br><br>
<input type="checkbox" id="check">
<span>Remember me</span>
<br><br>
Forgot <a href="#">Password</a>
</form>
</div>
</body>
</html>
what does div mean again?
it's a container
be careful with inline though. its the last to be called. it goes
1 .class //called first
2 #id // called second
3 and inline // called last.
``` so 3 will override 1, ect
<div></div> is a block container meaning its width=100% of its parent and you can apply padding and margins to it
<span></span> is an inline container meaning its width=fit-content and doesnt respect padding and margins
ok
i remember in college where they had us make a webapp w some data w bottle
it was a mess the TAs were holding people's hands to get them through the project
i build all my sites off of divs as do most people.
got it
i just got back into like 2 months ago though after a 13 year break from learning web programming in high school. i dont fully remember everything
uh yeah i have been coding inconsistently ever since i changed my major to business
i am taking it seriously again bc i don't think business will pay well enough
i think business degrees are pretty phony honestly by themselves. if you have zero knowledge of the field your using your business degree in, its not that helpful to have the degree anyways.
eh i don't think anyone deserves to get paid much to just stare at excel every day
coding is a much more valuable asset
this isn't the 90s they want people who can create things and solve problems not some random graphs on a spreadsheet
i mean a minor in business isnt a bad plan, but yea. Comp Sci major, with business minor. youll get a lot further then just having a business degree
but thats just my opinion, dont know if everyone would jump on that bandwagon
I've got a custom form within my admins.py which allows me to upload pictures, I then upload these pictures to the imgur API and save the URL within the object in a URLField. The issue is that I can't seem to find out how to also show the URLFields of my model as the ImageFields have the same field name...
class AddPackageForm(forms.ModelForm):
class Meta:
model = Packages
exclude = ['image_1', 'image_2', 'image_3']
image_fields = ['image_1', 'image_2', 'image_3']
image_1 = forms.ImageField(required=False)
image_2 = forms.ImageField(required=False)
image_3 = forms.ImageField(required=False)
def clean(self):
cleaned_data = super().clean()
images = {}
for key in cleaned_data.keys():
if key in self.image_fields and cleaned_data[key] is not None:
images[key] = cleaned_data[key]
imgur = ImgurAPI()
for key in images.keys():
# reads byte string from image
image = images[key].read()
uploaded = imgur.upload_image(file=image)
if uploaded['link'] is not None:
image_link = uploaded['link']
cleaned_data[key] = image_link
return cleaned_data
i dont know anything about that, i do uploads directly to my server instead of uploading elsewhere. wish i could help
Essentially my form field names are the same as my model names, but I don't know how else I can do this (to be able to show both the form fields and the model fields). The model fields are [image_1, image_2 etc.]
I think I just have the wrong train of thought
hmmm
Internal Server Error
The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.
uhhhh
internal server error?????
what are you running server side?
what does that mean
php? apache
python and flask
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return 'Hello, World!'
this is hello.py
oh look at the log for flask im assuming its similar to django and runs in command
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
this is app.py
<!DOCTYPE html>
<html>
<head>
<title>Login Form</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<h2>Login Page</h2><br>
<div class="login">
<form id="login" method="get" action="login.php">
<label><b>User Name
</b>
</label>
<input type="text" name="Uname" id="Uname" placeholder="Username">
<br><br>
<label><b>Password
</b>
</label>
<input type="Password" name="Pass" id="Pass" placeholder="Password">
<br><br>
<input type="button" name="log" id="log" value="Log In Here">
<br><br>
<input type="checkbox" id="check">
<span>Remember me</span>
<br><br>
Forgot <a href="#">Password</a>
</form>
</div>
</body>
</html>
and this is login.html
how many times are you initializing flask?
php doesnt run on flask
app = Flask(__name__)
and then import it to the other file
isnt error that you trying to render_template index.html while file named login.html
so from flask import app?
action="login.php" i dont understand this though. php isnt flask unless you cant even serve the index file
what about the export FLASK_ENV=development
It's just a form action
don't you need that too?
Yeah that too
ok good just checking
nope still didn't work
should i exit out of VSC and try again?
yea your running flask, why would your action be to php file in the flask server?
But that is not the error, That action only gets triggered when the form is submitted
You can remove the actions part
where is index.html placed? @spare iris
i know, but it will be an error is what im saying. he didnt say what his error was
index.html is placed in a folder called templates
Traceback (most recent call last):
File "/opt/anaconda3/lib/python3.7/site-packages/flask/app.py", line 2446, in wsgi_app
response = self.full_dispatch_request()
File "/opt/anaconda3/lib/python3.7/site-packages/flask/app.py", line 1951, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/opt/anaconda3/lib/python3.7/site-packages/flask/app.py", line 1820, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/opt/anaconda3/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/opt/anaconda3/lib/python3.7/site-packages/flask/app.py", line 1949, in full_dispatch_request
rv = self.dispatch_request()
File "/opt/anaconda3/lib/python3.7/site-packages/flask/app.py", line 1935, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/rahuldas/visual Studio worskpace/Web App Drawing 2/app.py", line 7, in index
return render_template('index.html')
File "/opt/anaconda3/lib/python3.7/site-packages/flask/templating.py", line 138, in render_template
ctx.app.jinja_env.get_or_select_template(template_name_or_list),
File "/opt/anaconda3/lib/python3.7/site-packages/jinja2/environment.py", line 869, in get_or_select_template
return self.get_template(template_name_or_list, parent, globals)
return self._load_template(name, self.make_globals(globals))
File "/opt/anaconda3/lib/python3.7/site-packages/jinja2/environment.py", line 804, in _load_template
template = self.loader.load(self, name, globals)
File "/opt/anaconda3/lib/python3.7/site-packages/jinja2/loaders.py", line 113, in load
source, filename, uptodate = self.get_source(environment, name)
File "/opt/anaconda3/lib/python3.7/site-packages/flask/templating.py", line 60, in get_source
return self._get_source_fast(environment, template)
File "/opt/anaconda3/lib/python3.7/site-packages/flask/templating.py", line 89, in _get_source_fast
raise TemplateNotFound(template)
idk what's going on
comment out your html in index.html and try printing something small
see if it works
also can you share a screenshot of your project directory
wow
i'm sorry i make noob moves
thank you
thanks guys
i promise i'll get better at this the more i do it
sorry for wasting your time
Hi, I am making a simple blog using django, how can I make the logged in user the author of that post using a function based view?
when you send an HTTP request using django, you can get the logged in user using request.user
i sorted the issue, just had to approach it differently
Thanks, but when a person is submitting it won't the author field still be an option?, how can I hide that field?
body
{
margin: 0;
padding: 0;
background-color:#6abadeba;
font-family: 'Arial';
}
.login{
width: 382px;
overflow: hidden;
margin: auto;
margin: 20 0 0 450px;
padding: 80px;
background: #23463f;
border-radius: 15px ;
}
h2{
text-align: center;
color: #277582;
padding: 20px;
}
label{
color: #08ffd1;
font-size: 17px;
}
#Uname{
width: 300px;
height: 30px;
border: none;
border-radius: 3px;
padding-left: 8px;
}
#Pass{
width: 300px;
height: 30px;
border: none;
border-radius: 3px;
padding-left: 8px;
}
#log{
width: 300px;
height: 30px;
border: none;
border-radius: 17px;
padding-left: 7px;
color: blue;
}
span{
color: white;
font-size: 17px;
}
a{
float: right;
background-color: grey;
}
hey so i wanna add this CSS to my login page
you don't need an author field, because you only want the author to be the logged in user. so theres no need to have a feild in your html for the author @eternal blade
is this within a css file? if so you have to reference it with the correct link
yeah i called it login.css but how do you reference it
Ok, thanks very much 
im not sure how it works for flask but i believe you can specify a static route which contains all your static files (css, js, etc) which you use in html
ok i'll do some research and get back to you
do you mind if i ping you when i figure it out?
yea sure no problem
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('login.html')
this is all i have for my routes
i don't really know what it means
Setting Up Flask
Flask [http://flask.pocoo.org/] is a great choice for building web applications
in a modular way using Python. Unlike Django and other analogues like Ruby on
Rails, Flask is a micro-framework. This means it includes only what is necessary
to do core web development, leaving the bulk of choices beyond that minimal
subset to you....
ugh i'm confused
maybe tech w tim can save me
so basically, you specify some sort of URL that static files are going to be packed in. this can be anything, such as "/css"
so when you use <link rel="stylesheet" href="...">, the href will be the path you specify
app = Flask(__name__,
static_url_path='',
static_folder='web/static',
template_folder='web/templates')```
OMG I DID IT
YA BOY DID IT
if __name__ == "__main__":
app.run(debug=True)
i was missing this in my app.py
and then i made a folder called static and put login.css underneath it
tech w tim is really good
if it wasn't for him i wouldn't know to create a folder called static in the first place
You dont necesarily need the if name = main, well atleast i dont
ok then it was probably putting the file under static
either way tech w tim is a g
i read somewhere that flask does it automatically tho
But the app.run(debug=True) does make it debug
hm
anyways i'm just happy i did something productive today
me to my internship when i finish this portfolio project
yea same here im like 16 but i just do this stuff for fun
yea now i just facepalm whenever ppl think they are a hacker when they inspect element lmao
~~html is a programming language ~~
oh come on we all went through that phase
my teacher deadass said HTML is a great programming language
that just shows you how bad the education actually is
Html is so hard
Someone told me html is too hard
And he said its enough to hack nasa
And my response was:
|| REEEEEEEEEE ||
Ha, you think yours bad? Mines doesn't even teach computation
computation like 1+2?
Yea you dont need the __name__ == "__main__" to run the flask app
Hey, has anyone setup AWS S3 in django in windows? ```python
AWS_ACCES_KEY_ID = ''
AWS_SECRET_ACCES_KEY = ''
AWS_STORAGE_BUCKET_NAME = '************'
AWS_S3_HOST = "s3.eu-west-3.amazonaws.com"
AWS_S3_REGION_NAME="eu-west-3"
AWS_S3_FILE_OVERWRITE = False
AWS_DEFAULT_ACL = "public-read"
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
In linux this works just fine, but in windows i get error botocore.exceptions.NoCredentialsError: Unable to locate credentials
not even
hey i need some help randomizing a background?
<script>
setInterval(()=>{
let images = ["image-1.jpg, image-2.png"]
document.querySelector(".home").style.backgroundImage = `url({{ url_for('static', filename='/thankyou/${images[Math.floor(Math.random() * images.length)]}') }})`
},2000)
</script>
i need some help with this
used flask
if you have only two images i would try to change html class of element
imma add more images
and in .css file have different bg image for each class
Hello. Need some info here
I am a noob learning flask. Which database should I use?
whichever suits u better bro
I am thing of postgre or sqlite3
sqlite is less complex
if you dont want to dive into client/server architecture of postgre you can use sqlite
Alright 😎
if you have not worked with databases a lot before, then sqlite3 should be good enough for testing/learning flask
Aight thanks
Mongo is the simplest
And you can use mongo atlas if you dont wanna setup a local instance
sqlite is just a .db file
I think he wants to focus on learning flask instead of investing time on database setup, here sqlite3 is the easiest to setup compared to mongo, postgres
Ik mongo sqllite as well as postgre. I was only having problem choosing one
Thanks anyways ended up using sqllite3
yea sqlite is also built in when using django so it makes preparing your database so much faster
ok i'm here @manic frost
what is from . import db
from flask import Blueprint
from . import db
main = Blueprint('main', __name__)
@main.route('/')
def index():
return 'Index'
@main.route('/profile')
def profile():
return 'Profile'
it's from here
it just says from .
i have never seen that
oh, I meant I would explain the whole request-response model
I'm not very familiar with flask-login
For those who have already replied to me please disregard but does anyone in here know a lot about selenium?
i think i celebrated a bit too early
A very simple overview is
You receive a request from the client
You direct the request to the proper route
If required you query the database
You construct a response and send it back
are you talking to me?
do you know what from . import db means?
what is .
maybe i should find a better tutoriall
That line means import the db file from the current directory
yeah i am gonna search for a better tutorial this is not cash money
Anyway http is a big subject, the specification is found here https://tools.ietf.org/html/rfc7231
The tutorial is fine
It assumes some familiarity with python tho which is fair
i do know python
Ok maybe some more familiarity then

well i need to do the project anyways so
i have been coding (inconsistently) for 2 years
you'd think by now i would be able to follow a tutorial lmao
But are you following the tutorial or are you just typing in the code they use
trying to follow the tutorial
If you have any specific questions you can use the help channels anyway
i mean #web-development is here to answer my questions too
there is a good chance that people in help channels don't know what i'm talking about and can't help me
not everyone has seen flask
@spare iris
Basically, when you open a website (let's stick to static websites), this is what happens.
- The browser sends a request to a server. It's nothing fancy -- just a small text message formatted in a particular way.
- The server responds with a similar message containing the webpage source (in HTML).
If you install curl and run curl -v https://docs.python.org/3/, if you ignore all the garbage it sends along the way, you will see this request text:
GET /3/ HTTP/2
Host: docs.python.org
User-Agent: curl/7.58.0
Accept: */*
This is the message it sends to the server. It has 4 several important parts:
HTTP/2is the name and version of the protocol, not very important for understanding./3/is the "path" of the URL -- it's the part of the URL after the hostGETis the "HTTP verb" -- it's one of GET, POST, DELETE and a few others. They have some differences, but for now they just bear different meaning, i.e. they allow you to perform different actions on one path- After the first line you'll see a list of headers -- it's a list of key-value pairs with some metadata. For example,
User-Agenttells what kind of program the client is using. - After these headers, you have optional "request body" -- everything before was just the address and the post stamp, but the body is the letter. Here there's nothing in the body.
You can also try https://jsonplaceholder.typicode.com/:
curl -v -X POST --header "Content-Type: application/json" "https://jsonplaceholder.typicode.com/posts" --data '{"title":"foo","body":"bar","userId":1}'
this sends this request:
POST /posts HTTP/2
Host: jsonplaceholder.typicode.com
User-Agent: curl/7.58.0
Accept: */*
Content-Type: application/json
Content-Length: 39
{"title":"foo","body":"bar","userId":1}
Then the server responds with:
HTTP/2 201
date: Wed, 24 Feb 2021 20:50:45 GMT
content-type: application/json; charset=utf-8
content-length: 65
... (some garbage like cookies and such)
{
"title": "foo",
"body": "bar",
"userId": 1,
"id": 101
}
The 201 is a status code -- it tells you the status of the response, i.e. whether it succeeded, how exactly it succeeded or why it failed https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
If I use uvicorn as a WSGI server, would it still be fast as opposed to it being used as an ASGI server?
@manic frost do you know django? im trying to solve a problem
You can use uvicorn as a WSGI server
ok cool
No, never used it
dang... i need to return the count of search results, but i want to slice the array to the a preview size and i cant seem to figure out how to do it
Hm?
Wdym
I know async won't work, but I don't need it for my use case
Im making my own framework
I need a server for it to run by default
So I though uvicorn by default would work
Its WSGI
I don't understand
Uvicorn is based on uvloop which is just another implemention of the asyncio loop
Why would you want to create a sync framework based on uvloop?
skrrt skrrt
Lol
I am confused
Well, I made a web framework, it runs by default on a cherrypy webserver, but you can use any WSGI server with it, I wanted a different default web server for it to run, so I decided to use uvicorn, since its fast and can handle lots of requests really well
And the webservers WSGI
did not understand a word but go off
Lol
The way uvicorn is able to handle so many requests that good is because it is based on uvloop
You wouldn't be using it for its intended purpose if its not deployed with an async module
like asgi or hypercorn
I mean, if it works i'm fine with it
Kinda bad practice but sure
Basically what you are doing can be summed up to this:
import asyncio
async def count_to_10():
for i in range(9):
print(i + 1)
asyncio.run(count_to_10())
It works but it doesnt look right
np
You might want to look how fastapi is implemented
It supports both sync and async
and its based on starlette which is based on uvicorn and uvloop
i dont have a clue what either of you are talking about. i still dont understand the point of async
Its an alternative syntax to threads
Not at all @noble spoke
no i understand what async does
async func a () {
await this;
}
async func b () {
await that;
}
``` so it calls a, and runs the code, while it waits for this it calls b, and does that. then goes back to this and gets the response, and finishes the the function call then finishes b. but your still waiting, just for 2 things at the same time.
so on the 6th line this guy writes that
i think that's his path
how do i figure out the equivalent for my computer?
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] ="login.db"
app.config["SECRET_KEY"] = "thisissecret"
db = SQLAlchemy(app)
right now it's just this
You need to create a database, I suggest you use sqlite
so it gets automatically generated in your project's directory
but unless your running multiple requests that take a bunch of time, it doesnt really help that much in terms of processing speeds. just running async on everything isnt that benificial
idk how to use sqllite3 for logins
Async has specific use cases and it is mostly for networking
i tried following tutorials but i don't understand what's going on
CPU bound stuff is generally not for python because of its GIL (Global interpreter lock) basically making it unable to run multiple processes at the same time, that can be considered both good and bad at the same time but I won't get into it now because it could be hours of typing haha
yea, because requests takes time. you get stuck in a queue and get answered when you get answered.
Kind of
There are many things async can do and it is definitely where the web frameworks are heading in the future
i mean beasically, without a full course of networking and dbs.
Hey, do anyone know what if difference between?
CLOUDINARY_STORAGE = {} and CLOUDINARY = {} ?
(django)
seems to be all is working the same in one difference with CLOUDINARY_STORAGE = {} ignoring configuration parameters like secure = 'true'. Cant find any information in google
No idea, ive never used django 😮
my site is fully async, but i dont actually have to program for async. i use react and axios. its all promise based. but my site still doesnt run full async like others try to program their sites
also not a clue, i use django. but ive never seen either of that
react and axios are frontend technologies
Your site doesn't have to be written in async for that
react and axios are both async though. theres not a single page refresh, its all done async in the background
React is not async
React is a frontend framework for building interfaces
How you interact with your API is your choice
fetch api is async for example
But in javascript async is syntactic sugar for promises
react/redux/axios is considered async. everything is based off promises. js async isnt true async like python async, but it follows the same concept at least from what ive been told
Alright, I am not going to get into this argument
🔥Edureka Python Master's Course: https://www.edureka.co/masters-program/python-developer-training
This Edureka video on the "Python Login System Part - 1" (Part 2 - https://youtu.be/SUC1aTu092w ) will help you in understanding how we can make a login system using Flask in Python along with hands-on.
Python Tutorial Playlist: https://goo.gl/WsBp...
random indian guy saves the day???
hopefully
no joke i am actually understanding basic flask syntax now
i should learn django why did i choose flask
react has async qualities, but it isn't really async unless you make it to be
axios = async = best request library
and redux is a pain in the arse 😄
static files generally refers to javascript / css files. for frameworks like django/flask the setup for static files excludes that of html files, so I would say it's not considered static within that sense.
ok
just kinda new to this so
only web stuff I ever did was w bottle
bottle is just a worse version of flask
Why do you need axios if there's fetch? https://caniuse.com/?search=fetch
axios seems a bit like leftpad or is-number
i have no clue, I think it's because I learnt axios first
both are really really similar
axios is really simple to use I can say that
and is-number is extremely useful 🤓 🤓 🤓
maybe even thanos.js
Well, fetch's interface is pretty much just one function, and it's a built-in.
I guess you can make your own little wrapper if you want something more specific and convenient, but not a large dependency.
One thing I hate about axios is that non-2XX responses are thrown as exceptions.
Does uvicorn loop its server?
did you figure it out?
can i have HTML and CSS in the same file or does it have to be different
Yes
to which question
All
Np
hey i have a question
@ keyframes show-navbar-dropdown {
0% {
transition: visibility .25s, opacity .25s, transform .25s;
transform: translate(0, 10px) perspective(200px) rotateX(-2deg);
opacity: 0;
}
100% {
transform: translate(0, 0);
opacity: 1;
}
}
why is this giving me an error
i don't get what's wrong
!pastebin
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
@ keyframes needs to be @keyframes, I think @spare iris
omg that fixed it you're the best thanks
do you need git to use heroku
idk what heroku is
dude
is this seriously it for all the doc
ERROR: Command errored out with exit status 1:
command: /Users/rahuldas/opt/anaconda3/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/8z/bx5my93n79gbdhds9zw6wy9h0000gn/T/pip-install-afvp475v/mysqlclient/setup.py'"'"'; __file__='"'"'/private/var/folders/8z/bx5my93n79gbdhds9zw6wy9h0000gn/T/pip-install-afvp475v/mysqlclient/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /private/var/folders/8z/bx5my93n79gbdhds9zw6wy9h0000gn/T/pip-install-afvp475v/mysqlclient/pip-egg-info
cwd: /private/var/folders/8z/bx5my93n79gbdhds9zw6wy9h0000gn/T/pip-install-afvp475v/mysqlclient/
Complete output (15 lines):
/bin/sh: mysql_config: command not found
/bin/sh: mariadb_config: command not found
/bin/sh: mysql_config: command not found
mysql_config --version
mariadb_config --version
mysql_config --libs
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/private/var/folders/8z/bx5my93n79gbdhds9zw6wy9h0000gn/T/pip-install-afvp475v/mysqlclient/setup.py", line 15, in <module>
metadata, options = get_config()
File "/private/var/folders/8z/bx5my93n79gbdhds9zw6wy9h0000gn/T/pip-install-afvp475v/mysqlclient/setup_posix.py", line 70, in get_config
libs = mysql_config("libs")
File "/private/var/folders/8z/bx5my93n79gbdhds9zw6wy9h0000gn/T/pip-install-afvp475v/mysqlclient/setup_posix.py", line 31, in mysql_config
raise OSError("{} not found".format(_mysql_config_path))
OSError: mysql_config not found
----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.
why did this happen when i did pip install flask-mysqldb
anyone ever use websockets aka channels in django?
@spare iris do you have MySQL installed locally?
no 
sorry it's been a long day
pip install mysql doesn't work either
MySQL isn't installed through pip, it's installed as a totally separate standalone app
you might do better starting with SQLite since it's included with Python
web developers is it a hard major
what type of jobs u get
how much is the salary
what is a good college
any tips
web dev isnt a major, comp sci is. and in the US devs make 80k+ a year starting. good money and if you get specialized can make a great living
Hi, does anyone know a good tutorial in django rest framework?
80k starting is a bit of an overstatement. It greatly depends on location.
if your not making 80k you should move companies. starting pay for network admins is 125k+ in Tulsa, Oklahoma and you dont even need a comp sci degree to do it. i wont work for less then 80k just about anywhere regardless of the job
You're lucky if you can make $30 an hour in Florida as a senior
like i said, id look around. comp sci degrees definitely require you to be mobile
theres white hat hackers making 200k+ a year. no sense in taking 60k as a senior web dev anywhere
I need to gtfo Florida : /
i mean maybe i live in a dream world, but i definitely wouldnt do what i know how to do for 60k, ill drive a semi truck for a lot more then 60k before i sit at a desk and type.
anyone ever seen this error?
ImportError: cannot import name 'PostNotificationSerializer' from partially initialized module 'web.serializers' (most likely due to a circular import)
This'd be the place to ask some Django questions, yeah? Didn't see any other more-specific channels.
yea, do you have a question?
Yeah, more about deployment of a pre-packaged Django app, looking for opinions on something. Lemme type it all out, gimme a sec.
So, I'm trying to deploy an already-developed Django app. Source is unobfuscated, so it's no mystery on what they're using in the app. The vendor for the app doesn't have great built-in ways to load data into the environment at deployment time, so I'm trying to use some Django built-ins to do it.
By "data," this would be "things you'd normally configure in-app that I don't want to make a human configure in each of our environments" - think like custom categories in this app, user roles for django_prbac, a few other things.
Optimal requirements are that this initial data can be loaded/modified idempotently, is easily versioned (i.e. I can deploy it through my CI/CD pipeline), and easy to parse by human beings
Look into seeding data on django
Found this on the docs: https://docs.djangoproject.com/en/3.1/howto/initial-data/
I figure I have a few options:
- Fixtures: literally designed for loading initial data into an environment, so there's that - but, if they change their data model, those fixtures might not work any longer. Plus, they use ints as their pk, and making it not collide with an existing record while remaining idempotent seems hard without a source code change (can't).
- Migrations: can easily be versioned, and can have it depend on a migration point in their package. Use
RunPythonto have it generate records, modify them if need be. I can then say what max version number of migration gets deployed in the stage. I don't quite know how I'd need to number these, though. - Admin command: most flexible, but also requires the most overhead. Also difficult to say exactly what version gets deployed, tracking those versions would be a bit difficult.
@placid vigil I looked at fixtures, and I'd really want to use them, but:
- can't call out to external libraries (think of if I wanted to resolve a secret value for a superuser password or something)
- I can't get them to run idempotently, if I declare an int pk, I have to hope that they didn't use that value somewhere else. They have UUIDs, but that's not their pk for the model
@wicked elbow for the first year is 60k good or nah
Hello i have a flask API. it takes a request to do some web scraping functions. 30 - 60 seconds per request. How should i handle 30 request concurrently
i mean up to you, but i wouldnt work as a dev for 60k but thats just me
What is the best practice for my problem
@wicked elbow if you have any ideas here, more than willing to hear them
you have a circular import
(sorry...but that’s really it)
I need to work elsewhere 😔
does web-dev / fullstack dev pay similar to other parts of the field, like ML? ( i don't know what to compare it to)
Hi how can I get all defined routes in django
i think i debug mode when you try to acces unknown route it gives you list of known routes
Hey , I am new to Django and recently trying to learn about making custom fields. I need to know how can I detect an invalid character in input string using RegExValidator
Hi, I am making a blog using django, my problem is when I upload an image with high dimensions it displays very big in the post, is there a way that I can make the image look smaller?. Thank you.
Hello, how can I know if the user has already entered his name in the database with flask and sqlite3.
A simple query for the username?
select username
from user_table
where username = the_username_youre_looking_for
``` maybe?
make your own regexvalidator which returns a validation error (with the invalid characters as the message)
it's my function but not working i already test it```py
def session_actu(data):
connexion = sqlite3.connect("Bdd/user2.db")
curseur = connexion.cursor()
requete = curseur.execute("SELECT * FROM t_user WHERE prenom = ?",(data,))
nom = requete.fetchall()
if nom == data:
return "deja enregistrer"
else:
curseur.execute("INSERT INTO t_user (prenom) values(?)",(data,))
connexion.commit()
Thanks
i didnt have a circular im port though. at least my serializers werent circular. i do have an issue, just gave up last night and went to bed
huh
then why did you get that error
still not fully sure, but im doing my stacked serializers wrong. which is whats causing the problem anyways
i also changed my header, you didnt like on my page. its new and fancy now
def session_actu(data):
connexion = sqlite3.connect("Bdd/user2.db")
curseur = connexion.cursor()
curseur.execute("SELECT * FROM t_user WHERE pseudo = ?",(data,))
resultat = curseur.fetchall() # premier resultat trouvé (c'est une liste normalement)
print(resultat)
if resultat:
return "deja enregistrer"
else:
curseur.execute("INSERT INTO t_user (pseudo) values(?)",(data,))
connexion.commit()
``` i resolve this thanks
class NotificationSerializer(serializers.ModelSerializer):
owner = serializers.SlugRelatedField(
many=False,
read_only=True,
slug_field='username'
)
initiated = serializers.SlugRelatedField(
many=False,
read_only=True,
slug_field='username'
)
comment = CommentsNotificationSerializer()
comment_likes = CommentLikesNotificationSerializer()
reply = ReplyNotificationSerializer()
likes = serializers.SlugRelatedField(
many=False,
read_only=True,
slug_field='post'
)
class Meta:
model = Notifications
fields = ('id', 'owner', 'initiated', 'comment', 'comment_likes', 'reply', 'likes', 'more_info', 'timestamp')
``` using nested serializers didnt work corrcectly, but i need multiple pieces of data from the foreign key, so i made a serializer for it with the fields. but thats what caused the circular import, so i scaled it back a tiny bit, but now im getting
TypeError: Object of type Posts is not JSON serializable
you probably
had serialisers referring to each other
I've had that problem before
the problem is all the foreign keys in each of the databases. creates one giant circle between posts and notifications. i get it but still
i followed the trace all the way back and couldnt find anything wrong.
my biggest problem is ive become to much a JS writer, my python brain dont wanna work any more
@vestal hound new header just for you. its in two parts, you can get the idea from the picture
it's 2021 btw
lmao shhh i dont wanna change it
that header was actually a lot of fun to make minus the lining up of the borders
hi, I have a question. Is it possible to open an website inside of a python program, something like iframe in html ? i want this mostly because I don't want to waste resources on opening a full browser like chrome or something 🙂
you mean like in a gui? or as a headless browser
gui
lining up of the borders?
they're not flex?
they are both flex, but for some odd reason they arent exactly the same size using the exact same code, rows vs columns. the row is centered amongst all the elements, so i had to add padding to fit it perfectly
ya, im sure there is. pyqt has web browser functionality
a ok
thx 🙂
no worries, theres headless browsers as well inside python
🥴
sounds kinda brittle
nah, they are both position fixed. even works correctly in mobile browsers.
im positive it has to do with the top being centered.
so instead of - _ -- i had to use align-items center for them to line up. the overlay is
so it doesnt center on the header. just had to position it to make up for the center
hi, i dont't know if this is the right channel, i'm trying to login into my discord account only using requests and json modules... when i send login requests with my data it returns only the token and few user settings but it doesn't return id or username as expected...sorry for my bad english
ok, I just got it working
🙂
but thx 🙂
Hey Pls I want some Help
app = Flask(__name__)
class User:
def__init__(self,id,username,password)
self.id = id
self.username = username
self.password = password
why is this all apparently wrong
it's all being underlined in red
this happened ever since i installed flutter
goddamnit i never should have installed that damn language
Hi, I am using django and I am trying to load a template in a class based view but django is searching in the wrong folder \templates\base\video_form.html but the file is in \templates\video_form.html how can I make django search in the correct folder?. thanks
Nvm fixed it
i fixed it thanks
afaik you don't need self when defining them in the user?
oh
yeah your indentation
np man
app = Flask(__name__)
class User:
def__init__(self, id, username, password):
self.id = id
self.username = username
self.password = password
def __init__
Hey Pls can Anyone help me
dont ask to ask. just post your question
never to be heard from again
Wy
lmao he dmed me instead
blocks him
lol
i should write code that blocks people when they DM me off the server
eh that sounds stupid bc you can shut off people from DMing you
i mean some of the friends i made off this server DM me all the time so they would get blocked too
whatever it was just an idea
How do I hide a field in a function based view, I am using django
whats your function look like? i dont know function based views. but im assuming theres similarities
hello, i'm using flask (which uses jinja2 template engine), how come i can't import a module within a block statement? ie.
{% import time %}{{ time.time() }}
this is the exception i get
or is it simply a security feature to not allow jinja access to import modules
guys how would i create a feed where people can post stuff
idk how to do it w HTML and CSS
starting to find stuff
its a very long process... not just as simple as some html and css
damn dude i'm not gonna finish this project any time soon am I
http://www.safespace.fyi:8000/ you mean something like this?
i'm gonna google some stuff and do some research
yea, ive been working on it 12 hours a day almost every day for 2 months now.
what have i signed myself up for
sometimes i dont actually work on it, just look at it and take breaks, but its not a simple project by any means. its a ton of code
i will watch some youtube tutorials
omg i looked it up and i can't find anything
how did facebook and instagram do it
you wont find anything, but still like todo lists. its pretty irrelevant unless you know how to change stuff to what you need it for
they hired a bunch of devs to work on it. the original facebook was incredibly simple. and even then had more the just zuckerberg building it. he actually stole source code from others to make it. ever seen the movie about it. the social network or whatever its called
uhhhh dude i have been "stealing" source code for this project for days
so i guess pick an easier project
can you think of anything?
you can do anything honestly as a portfolio project. but theres a reason everyone doesnt have their own social network platform
even in the simplest form, it looks good, but cant keep up with even reddit because it goes one step further and implements web sockets. to keep chats/feed up to date with likes ect
would i still get interviews and possible internships??
does it really matter what your profile project is?
just code what you want. youll get hired if they want you. its not fully based off of what youve done. almost every programmer has done the same portfolio projects
jobs look better in your portfolio, not projects.
well i'm still in college
Guys how would you make field for date of birth in flask ??
use sqlalchemy and you can find it in its documents
What s the difference between sqlachemy and migration
its not even the same
that you want to compareem
if you want to know about migration i got it schema migration refers to the management of incremental, reversible changes and version control to relational database schemas.
while sqlalchemy is a orm
hi everyone i have a question, any of you know an amazon API that allows me to login and add items to wish list ?
Amazon doesn't expose APIs for internal stuff like that sadly.
how can i get this with beautifulsoup, cant use findChildren bc its in a <a>
tbh i cant find anything that says i cant
im not doing anything big, its for a personal project
hey there
I have a basic flask app with this main functionality:
- someone can register on the register page and get redirected to the user area page.
- OR the user can login if he has an account there.
now the problem is I dont want my user area page can be accessed by typing the url in the url bar.
but only from the login or register page through redirection.
Any help?
@barren topaz you need session management... the flask docs have an example of an auth wrapper that's pretty simple
You just apply it to the route and it creates a condition
In fact I dont wanna use any sort of authentication from flask modules. I have a very simple html form and I wanna do all the stuff by myself.
I can provide my code if that can help.
Either way, you need to create a session. the type of session depends on what your needs are. Its just a signed cookie anyways and it uses the session obeject.
I'm sorry pal, Im quite a newbie in flask. Can I send you the code?
Cuz I have implemented the session thing based on the doc. but I dunno what further steps I should take.
This is my code, in the user_area function I was trying to put a condition not to let anyone access the page via GET but it seems that was dumb thing.
All of this stuff is covered in the tutorial, everything your asking about is covered in the docs. I know because I just spent about a week reading it over. https://flask.palletsprojects.com/en/1.1.x/tutorial/
@barren topaz if you're interested in all the details, bottle is a micro framework and gives you more fine tuned control. or you can just use weurkzueg which is really getting into the weeds a and is what flask uses anyways.
Sorry if it felt like I ignored that part.
I gotta check it out.
No problem bro, its ok.
Hi, this is my code to create a form ```py
def video_upload_view(request):
form_class = VideoUploadForm
form = VideoUploadForm(request.POST)
if request.method == 'POST':
if form.is_valid():
request.user = form.creator
form.save()
return reverse(home_page)
return render(request, "video_upload.html", {"form": form })
@pliant bane
Try this
for link in soup.find_all('img'):
print(link.get('src'))
ok will do
^^^ thanks
this is my code: ```py
@app.route("/dashboard")
async def dashboard():
bot_guilds = await ipc_client.request("get_guild_count")
guild_ids = await ipc_client.request("get_guild_ids")
user_guilds = await discord.fetch_guilds()
user = await discord.fetch_user()
same_guilds = []
for guild in user_guilds:
if guild.id in guild_ids:
same_guilds.append(guild)
return await render_template("dashboard.html", guild_count=bot_guilds, matching=same_guilds)
this is my HTML: ```html
<!DOCTYPE html>
<html>
<head>
<title>Dashboard</title>
</head>
<body>
<h1>Hewlett Dashboard</h1>
<h2> The Bot is in: {{guild_count}} servers </h2>
<h3> Common guilds </h3>
<ul>
{% for guild in matching %}
<li>{{ guild.name }}</li>
{% endfor %}
</ul>
</body>
</html>
but, this is my output:
how do I make the output into this or similar
Is your matching list empty?
I avoid bootstrap like the plague, i use react component libraries
I like chakraui a lot
I do
im not the best at css, but I do use my own
I would but im garbage
same
I never realised how bad i am until now, trying to build an online portfolio
I mean, you could just stick to a website-builder
same, I tried yesterday but decided to use flask as well
flask or html isnt the hard part
I spent 30 min trying to center 2 buttons
ikr
thats why you oculd use a website builder
no
if your project is suited for that
I refuse
im making a discord bot dashboard
oh
so I kinda have to use code
me too
I decided to take another step to make a dashboark
same, but for free
nice
after I did that for a while
you did them for free?
yeah
why
my status was "DM me for a free discord bot"
oh
I cant accept money
hint hint
no payment required
I made a bunch of money 3D modelling at one point
but then python happened
and I am not as good anymore
tkinter?
(the first thing I did after learning python)
PyQt5
ah
Tkinter sucks
i agree
its so frustrating
I gave up with it after a few projects
I didn't want to do guis
I have several questions
why have you been playing Qt designer for 2+ days
oh
for two days
normally I do
oh nvm
doesn't it ruin its lifespan
what?
leaving it on 24/7
HP Spectre X360 2016
^^^ Thanks :-)
how do I do the following? http://stackoverflow.com/questions/66377727/how-do-i-group-results-based-on-categories/66378257
could just throw it on heroku
hey guys
i'm pretty new to python and i have been trying to grab my database and display the results in a table
i know that wont work what i posted, but i don't really know how to display all the data in a html table
it's a school asignment
so i have to stick with this
yeah
yeah i switched it
i know how to get it to display in the console
my issue is getting it to display on a webpage in a table
yeah
to obtain the info and store it in the database
yes
oh yeah
yeah
would i put it here?
tbh i've never heard of jinja2 until now since this course is an introduction to python
i thought my php would transfer over, which it did in some parts
do you know how to do it without jinja2? i really don't wanna get into jinja2 or flask
How do I link a url which has multiple parameters?. Thanks
Could you elaborate?
Trying to loop things into my html table ```
for row in data:
id = row['user_id']
title = row['Title']
lname = row['LastName']
fname = row['FirstName']
streetname = row['Street']
city = row['City']
province = row['Province']
postalcode = row['PostalCode']
country = row['Country']
phonenum = row['PhoneNum']
email = row['Email']
print()
response = ("<html><head><style>table, th, td{border: 1px solid black;}</style></head>"f"<table><tr><th>ID</th><th>Title</th><th>First Name</th><th>Last Name</th><th>Street Name</th><th>City</th><th>Province</th><th>Postal Code</th><th>Country</th><th>Phone Number</th><th>Email</th></tr><td>{row['user_id']}</td><td>{row['Title']}</td><td>{row['FirstName']}</td><td>{row['LastName']}</td><td>{row['Street']}</td><td>{row['City']}</td><td>{row['Province']}</td><td>{row['PostalCode']}</td><td>{row['Country']}</td><td>{row['PhoneNum']}</td><td>{row['Email']}</td></tr></table></html>")
the print() works {'user_id': 39, 'Title': 'Mr', 'FirstName': 'wqe', 'LastName': 'wqe', 'Street': 'wqe', 'City': 'weq', 'Province': 'weq', 'PostalCode': 'weq', 'Country': 'Canada', 'PhoneNum': 'wqe', 'Email': 'wqe'} {'user_id': 40, 'Title': 'Mr', 'FirstName': 'wqe', 'LastName': 'wqe', 'Street': 'wqe', 'City': 'weq', 'Province': 'weq', 'PostalCode': 'weq', 'Country': 'Canada', 'PhoneNum': 'wqe', 'Email': 'wqe'} {'user_id': 41, 'Title': 'Mr', 'FirstName': 'wqe', 'LastName': 'wqe', 'Street': 'wqe', 'City': 'weq', 'Province': 'weq', 'PostalCode': 'weq', 'Country': 'Canada', 'PhoneNum': 'wqe', 'Email': 'wqe'} {'user_id': 42, 'Title': 'Mr', 'FirstName': 'wqe', 'LastName': 'wqe', 'Street': 'wqe', 'City': 'weq', 'Province': 'weq', 'PostalCode': 'weq', 'Country': 'Canada', 'PhoneNum': 'wqe', 'Email': 'wqe'} {'user_id': 48, 'Title': 'Mr', 'FirstName': 'a', 'LastName': 'b', 'Street': 'c', 'City': 'd', 'Province': 'e', 'PostalCode': 'f', 'Country': 'Canada', 'PhoneNum': 'g', 'Email': 'h'} {'user_id': 49, 'Title': 'Mr', 'FirstName': 'a', 'LastName': 'b', 'Street': 'c', 'City': 'd', 'Province': 'e', 'PostalCode': 'f', 'Country': 'Canada', 'PhoneNum': 'g', 'Email': 'h'} {'user_id': 50, 'Title': 'Mr', 'FirstName': 'a', 'LastName': 'b', 'Street': 'c', 'City': 'd', 'Province': 'e', 'PostalCode': 'f', 'Country': 'Canada', 'PhoneNum': 'g', 'Email': 'h'} {'user_id': 51, 'Title': 'Mr', 'FirstName': 'a', 'LastName': 'b', 'Street': 'c', 'City': 'd', 'Province': 'e', 'PostalCode': 'f', 'Country': 'Canada', 'PhoneNum': 'g', 'Email': 'h'} {'user_id': 52, 'Title': 'Mr', 'FirstName': 'a', 'LastName': 'b', 'Street': 'c', 'City': 'd', 'Province': 'e', 'PostalCode': 'f', 'Country': 'Canada', 'PhoneNum': 'g', 'Email': 'h'} {'user_id': 53, 'Title': 'Mr', 'FirstName': 'a', 'LastName': 'b', 'Street': 'c', 'City': 'd', 'Province': 'e', 'PostalCode': 'f', 'Country': 'Canada', 'PhoneNum': 'g', 'Email': 'h'}
but on the webpage it only shows my latest entry
and not all the entries
and yes, i have to do it through html like this with python
I don’t want to use a framework. I prefer just to use HTML through python
any reason for that
Because it’s an introductory course and I don’t want to get too deep with python
🥴
well, up to you
@vestal hound notifications, what do you think? yay or nay? gonna add the post thumbnail as well i think, but basically the set up
needs more padding
contrast seems a bit low
I am working locally, and to start a celery worker, I have to run this in terminal:
celery -A your_application.celery worker
Does anyone know how I can get this to run automatically when I run my app?
When hosting is on Heroku, I'll use a Procfile. But I'm unsure how to run it when developing locally
yea, maybe a bit, just not trying to make to much white space though
why is django's request.user returning AnonymousUser when I just successfully login() my user and I have the sessionId stored as a cookie?
are you passing the token with your request?
yeah
contrast is the bigger thing
i spaced the references out some from the first sentence telling what happend. trying to decide if i should add a tiny bit more padding to the side though
that’s important I think
right now there’s no distinction between the different elements
something more like that. dont mind the testing comments. i talk to myself haha
havent decided if i like the trays or not that slide in from the side of the screen, but it doesnt look bad and you can click anywhere to exit it other then in the tray
uhh, trying to access the sessionid cookie with Cookies.get('sessionid') and it's just undefined. I do the same with any other cookie that I have and it works...
id say just make sure your matching your cookies. i havent messed with cookies in forever. im using local storage to save the token at the moment on a short timer from the server. i pull it from local storage on initialization and save it in my redux store in react so i dont have to mess with local storage again. so im not much help there
Can I have a url for static files and media files, I am using django. Thank you
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('base.urls'))
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)``` Is it possible to have a url pattern for static files in addition to this?.
hey
so basiclly im making an app
and im displaying an image and i want the image to be centered on the screen
but it doesnt
its at teh top
here is my code
import { StatusBar } from 'expo-status-bar';
import { GestureHandler } from 'expo';
import React from 'react';
import { StyleSheet, Text, View, Dimensions, Image, Animated } from 'react-native';
const screen_height = Dimensions.get("window").height
const screen_width = Dimensions.get("window").width
const Movies = [
{id: "1", name: "Venom", uri: require("../movie-suggestion/assets/movie-poster/Venom-Movie-Poster.jpg")},
{id: "2", name: "American Sniper", uri: require("../movie-suggestion/assets/movie-poster/AmericanSniper-Movie-Poster.jpg")}
]
export default function App() {
return (
// <View style={styles.container}>
// <Text>Open up App.js to sart working on your app!</Text>
// <StatusBar style="auto" />
// </View>
<View style={{ flex:1 }}>
<View style={ height=60 }>
<Text>Venom</Text>
</View>
<View style={{ flex:1 }}>
<Animated.View style={{height:screen_height-120, width:screen_width, padding:10}}>
<Image style={{ flex:1, height:null, width:null, resizeMode: "cover", borderRadius:30}} source={Movies[1].uri} />
</Animated.View>
</View>
<View style={ height=60 }>
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
and a screen shot
of what is happining
and a screen
import flask
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return "Hello! This is a website where you can find many things about python (for begginers)"
@app.route("/<name>")
def user(name):
return f"Hello {name}!"
if __name__ == "__main__":
app.run()```
i have already download flask
error:
```py
Unable to import 'flask'pylint(import-error)```
some help
i am new to web development
and:
guys???
@silver wagon Please don't try to ping @everyone or @here. Your message has been removed. If you believe this was a mistake, please let staff know!
ok
Try executing
python app.py
Where app.py is something like this:
from __init__ import *
if __name__ == "__main__":
app.run(host="0.0.0.0", port=80)
You probably has this file in the root folder of your application.
bruh
C:\Users\SpyD\Desktop\pybox\demoapp>app.py
Traceback (most recent call last):
File "C:\Users\SpyD\Desktop\pybox\demoapp\app.py", line 1, in <module>
from __init__ import *
ModuleNotFoundError: No module named '__init__'
Send the files in your application root folder
Is it more common to use plain Django web applications? Or using Django rest and a front end framework like React?
I've been digging into things and it feels like the latter is far more powerful since it let's you do more on the front end than basic stuff.
I actually use Django rest and React because I feel more comfortable but idk depends on the project i guess.
I feel kindve annoyed with how I have fought so hard with getting a half decent front end with Django when I could have just used react.
Are there downsides to using react over Django?
There may be performance differences but I don't think there is a notable downside.
you should use a frontend framework with django for sure, it makes auth less plug n' play tho :>(
I mean react is awesome and I am also kind of angry learning it so later.
Yeah, cors was a pain to get past
generally it doesn't matter much which system you use just depends on context
if you have something which relies alot on AJAX type systems like a chat app etc... then a front end framework like react or vue is easier to use and setup
but if it's static content there isnt much reason to use it over ss rendering unless you're planning to render the content on a edge server
Ya I think that's the biggest issue I had with pure Django
Do you guys know any worth looking django additional libraries?
Django tenants was interesting to me. Also CMS like mezzanine
mezzanine is awsome.
I have a question with selenium. Why is it not placing the value and it keeps repeating the error of finding an element if I am no longer on that page
hi is their a way to render a webpage every 2 seconds using flask so i can change the variable constantly i want to make a clock
the environment variable is named FLASK_APP not flask_app
Hello,
Is there anyone who uses a chromebook for web development? I saw that google video about how to web developing on chrome OS:
https://youtu.be/3CWUAisN-vo
And now im considering buying a chromebook cuz they are cheaper and i have some questions:
From your experience what are the things that you didn't like about web developing on chrome OS?
What are the things to look for when buying one?
And any other thing about it will be really appreciated
This talk demonstrates how in a few clicks you can get a full web development environment up and running on Chrome OS, including how to do cross-browser testing!
Presented by: Emilie Roberts
#ChromeDevSummit All Sessions → https://goo.gle/CDS19
Subscribe to Google Chrome Developers → https://goo.gle/ChromeDevs
Event photos → https://goo.gle...
js is the way here
Oh did i cut someone frkm speaking?
how much cheaper are they anyway
@noble spoke like 200 and something
Chrome books are a no
But there are cheaper
you can get a cheap laptop for that price
i got a lenovo for £200
that’s a laptop company right?
My budget is 100$
why 100$
youre not gonna get anything functional for that
that’s a laptop company right?
@spare iris well i am a self taught not employed yet
I mean same
lol
Acer is a laptop company yes
Nothing wrong w being self learnt tho
everyone has to do some degree of self learning in CS
if all you do is rely on the help of others you’ll never really make progress
youre not gonna get anything functional for that
@noble spoke
On google video they downloaded VScode and other IDE's and like... Everything will run fine
acer makes more than just laptops tho
Hang on I’m gonna google some good quality laptops in your budget
youre gonna struggle with compatibility issues
at the end of the day if thats all you can afford its better than nothing
if all you do is rely on the help of others you’ll never really make progress
@spare iris oh i thought you were asking if i will be using it for work
Hang on I’m gonna google some good quality laptops in your budget
@spare iris ok i appreciate that
Here check this out
Ok
How old are you?
Im 20
makes sense why you can’t use your parents money anymore
yeah I’m hoping my Mac that my dad bought for me lasts for a while
makes sense why you can’t use your parents money anymore
@spare iris yeah
yeah I’m hoping my Mac that my dad bought for me lasts for a while
@spare iris lol
@scenic dove I’m probably gonna get OTd but it’s like those people who don’t even have a job that use their parent’s money to date people
it just feels wrong
i spent 400 on my laptop lol
i made with it my old buisness
aint got no golden spoon feeding me
good stuff
@scenic dove I’m probably gonna get OTd but it’s like those people who don’t even have a job that use their parent’s money to date people
@spare iris what is an OTD :P
aint got no golden spoon feeding me
@toxic flame 👏👏
@scenic dove !ot