#web-development
2 messages · Page 142 of 1
the database will be separate
unless you use an in-memory database
or local storage
which you should not do
why not
Like sqlite?
If you’re scared of losing your data because of the platform, I wouldn’t risk using the platform
but you really should avoid sqlite for anything other than really small projects or testing
If i switch to postgress the current users will have to reregister right?
you can perform a data migration
more or less
every IaaS/SaaS platform
does this.
servers are fungible.
What is a "days migration"
you can’t write to the local filesystem on AWS either
if your fear is that you will lose data like that
then I would say you are approaching the problem from the wrong direction.
your database should not run where your app does.
There are only about 5 users if I migrate to postgress and they'll probably register again but it will be a new experience for me trying to migrate to a new db without breaking stuff
like I said
you can run a data migration
is not difficult with a bit of preparation
and you have little data
Ok, I've never done it before tho...
-> fewer edge cases
great time to learn
So should I also have static/media files separately?
I've never deployed anything before, I'm new to that
Ok thanks I'll try doing that 👍
no
they’re static
i.e. don’t change
if by media you mean user uploaded stuff
then yes separate
okay maybe to give you some context
the reason you should separate app and data is
that makes your app stateless
you can run as many copies of your app as you want
if one goes down, just restart it
you lose nothing unrecoverable
imagine if you want to serve 10 different copies
and each has its own database on its local filesystem
how are you going to sync each of them?
imagine you connect to one but your user data is somewhere else
where will all that logic to switch you to a different server go?
if your apps are stateless
the user will never be exposed to this kind of detail
Sorry, give me a moment to catch up
So, if I have a media separately how can connect to it?
So I should use a service like this to store files?
https://www.youtube.com/watch?v=inQyZ7zFMHM
In this video I will go over Hosting dajngo static files with amazon web services (AWS) S3 buckets. We will first set up our S3 bucket and then configure our django app to pull and upload these files to our bucket.
Source code & Live Demo: https://dennis-sourcecode.herokuapp.com/36/
Hello everybody
I need help with Django-Restframework
I've been searching on google but I couldn't find something useful, could anyone help?
what is it
I am using it, I can probably help if it is basic. Do tell.
im doing a login but i get an error
@app.route("/login")
def login():
code = request.args.get("code")
red = request.args.get('red')
if code is None:
if session.get("token"):
user = Oauth.get_user_json(session.get('token'))
return f"already logged in as {user.get('username')}#{user.get('discriminator')}"
return redirect(f"{Oauth.discord_login_url}")
else:
try:
at = Oauth.get_access_token(code=code)
except:
return "Invalid Code"
print("Session")
session["token"] = at
if red is not None:
redy = red.replace("$", "/")
print("Accessed - ", redy)
return redirect(url_for(red))
else:
return "Successfully logged in"
@app.route("/<guildid>/announcements")
def announcements_page(guildid):
print(guildid)
if session.get("token"):
return "Valid Session"
else:
return redirect(url_for(f"/login?red=${guildid}$announcements"))
login
and error is
@ocean dirge The url you are calling is then redirecting to the login url right? Have you tried calling the login url directly?
if i pass a value into the discord login url will it come back again?
i need to pass the redirect url around a good bit
i got it fixed
is this good code?
@app.route("/login")
def login():
code = request.args.get("code")
red = session.get("redirect")
if code is None:
if session.get("token"):
user = Oauth.get_user_json(session.get('token'))
return f"already logged in as {user.get('username')}#{user.get('discriminator')}"
return redirect(f"{Oauth.discord_login_url}&")
else:
try:
at = Oauth.get_access_token(code=code)
except:
return "Invalid Code"
print(at)
session["token"] = at
if red is not None:
return redirect(f"http://127.0.0.1:5000/{red}")
else:
return "Successfully logged in"
guys, it always returns 1, in a form with flask
gender = SelectField('Sesso', validators=[DataRequired(message="Inserisci il sesso del tuo personaggio."), ], choices=[('M','Maschio'),('F','Femmina')])
def generategender(self, gender):
if gender == 'M':
return 0
else:
return 1
does anybody know how come?
idk why my website taking too time to load ?(using django)
after uploding videos website work one time.BUT when i reload it,it only load. why this is happening?
Hey, everyone! i'm an intern in a college lab for air quality and they are starting to implement a webapp that runs a executable program (in rust if I'm not wrong) in the server (like, the user uploads the necessary files to the web page, the webpage redirects it to the server where it will run the program and give back the results). But the thing is that the user needs to keep that page open all the time. Is there a way that we could program it to do it like: the user uploads and submits the files and leave the page, then once the program finishes the server sends the result to the users email?
the best way to do this is to have the process running independently of the web request, with something like subprocess. then you could either send to an email (would have to code that too, maybe a small python script that calls the program, gets results and dispatches a email) or actually write results to a database together with the username/id. if you do it based on user id the user could just reopen the page to check the results at a later time.
thanks!! any tips on what to look for to start learning about those subprocesses? (using django)
not sure, i would start by googling something like "long running processes in django"
@misty gate have you tried Huey or Celery? It can be used to run asyncronus tasks. You can write your django views as required and then write a function for asyncronus task.
They have examples there so it won't be hard.
I came across Celery on my searches, but it seemed rather complicated hahaha but I'll look further into it!! Also thanks for sharing this Huey, I'll also take a peek at that one
Celery might be overboard, but huey is definetly light weight, useful and simple.
Hi, I have a question. Someone know how I can send a file to user since Flask?
They give me parameters and I have to give them a file
@tender goblet serving file in frontend or sending email?
You mean like they give you info on a form and you give back a file with "results" on that?
thank you!
awesome, could you give some more info about the project?
frameworks you are using, which language is the backend written on
I am working with Flask, what I have to do is receive some parameters through form-data. With those parameters that they give me I have to create a .kml file and return it
But I don't know how return the file
I wanna set up a kahoot bot but the game pin wount type on the website
hi guys so i ran into this error
I know its not related to python but it's react and i need some help ;-;
Site works fine, i just dont like this error ;-;
Hey Thanks for replying to my msg. I am passing a list for modifiers, I get an error shouting at me that
MODIFIER IS EXPECTED TO BE A dict but got a str
Hey guys this problem is the reason i am unable to sleep, If any one have something to help, I would really appreciate that. 😦
#web-development message
Can someone explain how I can send Jinja variable to a Javascript function in an external filesheet, whilst using base templates?
<button onclick="logUsername('{{user.username}}')>Click Me</button>
This sends {{user.username}} to the javascript function, and not the Jinja value
It only happens with my child template, which inherits from a base template
(PHP, MySQL) Is there anything that im doing wrong? (im getting syntax error)
So I'm going to use this
https://getbootstrap.com/docs/4.0/components/modal/#scrolling-long-content
But I'd like to see a way to either have a black overlay over the background or blur the background when it pops up. Preferably blur. Does anyone know a way to do that?
Can anyone help me with web parsing?
how would I make a menu for a phone in one media quarry not display for another media quarry for the desktop/tablet
in css
never mind figured it out
I have a question - I want to ask if it can be programmed that when I enter a web address on the discord, such as www.example.com, a predetermined embed will appear.
Do you own the website? If so, Discord respects OpenGraph tags for its unfurls.
This is probably a good starting point: https://medium.com/slack-developer-blog/everything-you-ever-wanted-to-know-about-unfurling-but-were-afraid-to-ask-or-how-to-make-your-e64b4bb9254
ty! : D
so im trying to learn flask as of now and i was hopping if someone could help me understand how i can use teh main python file (such as idk app.py) how i can use it and what i can insert there
ping me if someone can help
class CreateCharacterForm(FlaskForm):
telephone = SelectField('Telefono', validators=[DataRequired(message="choose whether your character will have a phone"), ], choices=[('1','yes'),('0','no')])
def generatenumber(self):
if self.telephone == 1:
while True:
rn = random.randint(100000, 999999)
char_same_num = Char.query.filter_by(telephone=rn).first()
if char_same_num is None:
break
return rn
else:
return None
guys it always gives NULL, why?
@cloud path You should be comparing self.telephone.data. Also I think the value will be coerced into a string (I might be wrong here!) so check the type of the data so you're comparing the same types (1 != '1')
@heady iris what are you specifically interested in knowing about the main python file for Flask?
I think you can pass in a function (in this case int) as a coerce keyword argument for the SelectField. That way you don't have to do the manual int casting and catching of errors. So you'd have SelectField(...., ..., ..., coerce=int)
Also according to the docs, if there's no specific reason for DataRequired, use InputRequired as the required validator.
I'm not quite sure how to debug when using Flask and Dash/Plotly. For instance I have the following callback:
@app.callback(
Output('right-lower', 'children'),
[Input('station-dd', 'value'),
Input('all-graph', 'selectedData')],
[State('right-lower', 'children')])
def display_selected_data(dd_selection, graph_selection, children):
...
c = children
...
if children is None:
figure = None
else:
figure = None
So I'm trying to get the figure from the children and I have breakpoints at the ellipses but when i trigger the callback the breakpoints dont break and I cant see the variables so I dont know how to extract what i need.
Is there any way to view html code generated after Javascript has run and added content?
I'm trying to port wikimedia pages to github docs/wiki and wondering if there is any easy solution anyone is aware of.
@floral fulcrum I believe the request-html library can capture text rendered by JavaScript to a variable that can be output/parsed/manipulated as you see fit...
i want to knwo what i use that file for
meaning what is this files purpose and how can i use it
@receiver(signal=signals.post_save, sender=Event)
def create_event(sender, instance, created, **kwargs):
if created:
for fighter in Fighter.objects.filter(retired=False):
instance.registered.add(fighter)```
I'm trying to add to add Fighter object to Event object's registered ManyToMany once its created
but when i check, they havent been added
Any ideas?
So I'm having trouble with sqlite3 while learning django... Every time I run py manage.py dbshell I get "CommandError: you appear not to have the 'sqlite3' program installed or on your path." I both have sqlite3 installed and added to my user variables and system variables! Since it wasn't working with the sqlite3 directory in path I even went as far as adding the actual .exe file paths to my env variables... At this point I'm completely lost, any help would be GREATLY appreciated!
Pls
@heady iris Typically that file will contain the code to tie everything together into a Flask app. It might contain things like the database connector, routes, and additional middleware you want to include in your app. When you call flask run, the package will read this file and run your application.
Have you tried spinning up a hello world with Flask?
@app.route()
def hello_world():
return 'hello world'
yes i have
👍
@outer apex but how can ik if i need to put something in teh app.py when creating soemthing?
It depends on how you want to structure your app. Let's say you have a simple app with two routes, index and about. If there's no complicated procedures for these routes, makes sense to have two functions in the main file. But let's say you had a few set of routes, you probably don't want to put all the functions into the main file. Instead you'd pull these sets of routes into their own packages and then in your main file, import these packages. Flask already has a pattern called blueprints that does this.
It's a bit difficult to answer that question without much context since the context really defines how you would choose to structure and organise the files, right
lets say i wnat to make a sign in page
i woudl need to make a route for it
i woudl also have an html file lets name it signin.html
there i woudl display everything so that i can input my username and pass
the reason i ask this question is to understand how will i be able to check if the user had entered somthing specific so taht he/she will be redirected to another page
and also where will i check that
so thats why i asked what i can use teh main pyhton file
well basically you do this
@app.route()
def login():
if user=user and password=password:
return NextPage
return LoginPage
``` in the simplest terms
i dont know flask, so dont ask me specifics. just the same concept for every language

ipc_client = ipc.Client(secret_key="HELLO")
@app.route("/<guildid>/settings")
async def announcements_page(guildid):
user = await discord.fetch_user()
if user:
session["redirect"] = None
guild_count = await ipc_client.request(f"get_guild_count")
return f"Valid Session, accessing for {user.name}#{user.discriminator}, bot is in {guild_count} guilds"
else:
session["redirect"] = f"{guildid}/settings"
return redirect(url_for("login"))
website side
async def run():
description = "Mattress, the backbone of any server"
credientals = CREDIENTALS
db = await asyncpg.create_pool(**credientals)
await INIT(f"Successfully connected to {credientals['database']} database")
await db.execute("CREATE TABLE IF NOT EXISTS guilds(guildid BIGINT PRIMARY KEY, prefix TEXT)")
await db.execute("CREATE TABLE IF NOT EXISTS users(userid BIGINT PRIMARY KEY, announcements BOOLEAN)")
await db.execute("CREATE TABLE IF NOT EXISTS members(userid BIGINT REFERENCES users(userid), guildid BIGINT REFERENCES guilds(guildid), announcements BOOLEAN, PRIMARY KEY(userid, guildid))")
async def get_prefix(client, message):
if message.guild.id not in prefixes:
pr = await db.fetchrow("SELECT prefix FROM prefixes WHERE guildid = $1", message.guild.id)
print(f"[PREFIX] - cached prefix '{pr[0]}'")
prefixes[message.guild.id] = pr[0]
return pr[0]
else:
return prefixes[message.guild.id]
client = Client(description=description, db=db, intents=intents, prefix=get_prefix)
@client.ipc.route()
async def get_guild_count(data):
return len(client.guilds)
try:
await client.ipc.start()
except Exception as e:
print(e)
pass
await client.start(TOKEN)
class Client(commands.Bot):
def __init__(self, **kwargs):
super().__init__(
description=kwargs.pop("description"),
intents=kwargs.pop("intents"),
command_prefix=kwargs.pop("prefix"),
case_insensitive=True
)
self.ipc = ipc.Server(self, secret_key="HELLO")
async def on_ready(self):
await INIT(f"{self.user} is online")
async def on_ipc_ready(self):
await INIT("IPC is Online")
async def on_ipc_error(self, endpoint, error):
await ERR(f"{endpoint} raised {error}")
loop = asyncio.get_event_loop()
loop.run_until_complete(run())
idk what teh context is but when i get soemthing liek that i usualy check the last line cuz thats where teh problem is
i have all relevant code here
is localhost:20000 a valid location?
i never refer to localhost:20000 anywhere
flask site is on 127.0.0.1:5000
is there a config for port?
should i change ipc port to 5002
thats what your error is. meaning something is pointing to that location. find what is pointing there and youll solve your problem. i have no idea, dont know flask. and dont know discord.py. also no idea on connections between the 2. but thats your error.
its apparently an error with the get_guild_count line
your connections have to match. thats true for anything. for instance a db server runs on a specific port, or redis runs on a specific port. if the port isnt active, then itll refuse the connection.
not not necessarily. redis for example is port 6379, postgres is port 5432. if i havent started the servers, the ports will refuse a connection. make sure everything is running and running on the correct ports
bump
Thanks I'll check it out
So I'm going to use this
https://getbootstrap.com/docs/4.0/components/modal/#scrolling-long-content
But I'd like to see a way to either have a black overlay over the background or blur the background when it pops up. Preferably blur. Does anyone know a way to do that?
you can make your background colors transparent using rgba() or you have a background div that has an opacity of less then 1
cant really blur that i know of, maybe make and image thats partially transparent. like every so many pixels to use as a background that way its hard to tell whats behind it
its not really the actual background color I'm looking to change, but to createa a layer/blur over everything behind the popup
same thing...
@floral fulcrum I forgot to mention selenium too... If the JavaScript that renders the html that you're trying to capture requires any interactions with the page in order to render then you'll want to look into selenium because it can automate page interactions to get the JavaScript you're looking for to render...
something like that?
because thats exactly how you do it
yea
tho I would prefer a blur, a partially transparent color would have to do too ig
theres is no blur, but you cant make it be less transparent so its harder to see
well, there is css body { filter: blur(2px); } for what I know, but idk how to do that only when the popup is active and not blur the popup itself
Ended up with a reversed effect 
should be able to do it with something like:
<div style="height: 100%; width: 100%; background: rgba(255,255,255, .3), position: relative">
<div style="position: absolute; left: 50%; top:50%; transform: translateX(-50%) translateY(-50%); background-color: #FFFFFF">
Whatever here
</div>
</div>
use the blur in the first div if you want it there
may have to do it seperately, or like this
<div style="position: relative; height: 100%; width: 100%;">
<div style="height: 100%; width: 100%; background: rgba(255,255,255, .3), position: relative">
blur here
</div>
<div style="position: absolute; left: 50%; top:50%; transform: translateX(-50%) translateY(-50%); background-color: #FFFFFF">
Whatever here
</div>
</div>
have a feeling its like opacity. and youll have to do the bottom method to achieve it
Hey guys, little desperate to figure this out for a Client. Their web host doesn't have Python Apps or App management enabled in cPanel and don't offer SSH. Though they claim to offer python. Is there a way for me to run an app (Django) utilizing PERL or something else?
do they have "normal" cgi support?
I can't remember how "normal" cgi works, but you might be able to set the interpreter to python
regardless this seems like a security vuln if you're forced to put everything under doc root
I tried testing a file in public_html/cgi-bin and got a 500
yea idk how well this would work
I'm about to tell them to find a better host or move over to me
django expects wsgi i think, it supposedly also works with asgi but idk what that is
that means you have the connections run as different threads served from the same interpreter i think
normal cgi spawns a new interpreter each time
barely anyone uses normal cgi anymore, it's mostly fastcgi, wsgi, or some other thing where the request is forwarded to a backend service
Even that's getting a bit over my head at this point lol
yea it's pretty hard to do in a sane manner
I should just be able to pull the repo, and run it through Python App (cloud linux) or through the application manager (neither of which they have)
with a venv
are they migrating the app or is it fresh?
it's fresh
also, make sure you aren't using django's integrated server, it's not production ready. I've found uwsgi is simple enough to setup, but there are many ways to securely connect django to the client
Yeah, it's still in development, so I'll set that up when it's ready
ah
I just wanted to get it tested on the existing server for my sanity
but at this point it's safe to say that he's gonna have to move
Yeah, but in recent years, it's no problem to get basic python support, even with a little setup
are you sure there's even a python 3 interpreter on there?
Lol NOPE
can't even get into SSH to test it
for all I know it's probably only 2.7
all the client got from the host was Python support is already enabled on all of our servers. If you're having trouble using Python, please provide us with steps that can be taken to replicate the problem.
when I asked them to request the cpanel applications to be enabled
I feel like if you're running a django app you should probably shell out the additional like $4/month to get a proper VPS
probably
this is probably running shared between like 10 different users
anyway, I had a question about django I thought I might try to ask here
Thanks for the help, if I know anything I'll stick around
np
I've historically used flask + jinja + some db driver for my projects, but I've been looking at trying django for my next project, altho idk if it's the right fit
actually I think I've figured it out after trying to explain it lol
django would prolly be best for this
it seemed kind of overwhelming at first compared to the minimalism of flask
how do i get a client's ip when hosting a django site off of repl.it
every attempt ive made has led to a wrong ip
ive tried using the flask module itself and https://api64.ipify.org?format=json
it may be sent through a proxy
there might be an X-Forwarded-For header I think
tried that
hmm
@tulip relic I haven't used Flask, what are you trying to accomplish?
@sly trail are you trying to get the IP from the request, or your provider?
I wanted to essentially make a site where users can search youtube videos, choose to archive them, and then replay them later. It'd also keep metadata and stuff. The hard part is that the downloading process could easily fail, and it might be complicated to jeep track of
with replit tho
I know how to do each step, but I fear that I could get into situations with half-downloaded files and such
altho django makes it easy to manage the db
#my_app.view
def MyView(request):
...foobar
ip = request.META.get('REMOTE_ADDR')
...foobar
@hollow scaffold the problem is Stocker's server never observes the client directly
AttributeError: 'Request' object has no attribute 'META'
there's no way to tell without making the client specifically mention it in the request somehow
rip
also, there are some cases where the client doesn't have its own public IP
almost seams like you would need another server just to act as the proxy and make the requests from your actual site
and get the IP's there
^
the ips keep changing lol
depending on how i choose to get them
remot_addr gives a private ip i believe
json api gives one, x-forwarded-for gives another one, etc
This is the landing page of my fully working website ignore the song and video quality bcoz I forget to stop and customise them
im trying to do something to check for alts (discord py)
@tulip relic yeah, I wonder if there is a library that might handle the downloads for you that you can implement into your project
nice
Thanks @sly trail
it'd leave a file on disk and may or may not leave invalid metadata
i think i found a way tho
np
ye
Thanks dude but it's only the landing I have made the full website
And after sometime I will upload whole website
@tulip relic btw so basically i cant get the client's ip if im hosting the flask page off of replit right?
p much
alr
my goal is to create something like altdentifier in a way where it detects alts, but idk how to do that securely
okay
its what powers the login with google, login with facebook, etc
ic
how would i do it?
also what would OpenID be used for
it's possible for multiple legitimate users to share the same IP and for a single user to have multiple IPs. It's way more useful, if you're trying to use it for alt detection to use OpenID
OpenID basically makes it so a user can identify using third party accounts
it's harder to create multiple google accounts than it is to get more than one IP
hey guys, was trying to deploy to heroku and it was successful but then i ran into this problem
Traceback (most recent call last):
File "/app/.heroku/python/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/app/.heroku/python/lib/python3.7/site-packages/django/core/handlers/base.py", line 204, in _get_response
response = response.render()
File "/app/.heroku/python/lib/python3.7/site-packages/django/template/response.py", line 105, in render
self.content = self.rendered_content
File "/app/.heroku/python/lib/python3.7/site-packages/django/template/response.py", line 81, in rendered_content
template = self.resolve_template(self.template_name)
File "/app/.heroku/python/lib/python3.7/site-packages/django/template/response.py", line 63, in resolve_template
return select_template(template, using=self.using)
File "/app/.heroku/python/lib/python3.7/site-packages/django/template/loader.py", line 47, in select_template
raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain)
Exception Type: TemplateDoesNotExist at /login/
Exception Value: todo/userCreation/login.html
this is the view that is causing the error
path('login/', auth_views.LoginView.as_view(template_name='todo/userCreation/login.html'), name='login'),```
if you turn your router off for a minute and turn it back in it is likely you'll get a completely different IP
oh damn
that doesnt seem true
it looks like altdentifier makes you use a discord account with a linked e.g. steam account that matches what you login to altdentifier with
unless you have your ip set to dynamic it wont change everytime
residential ISPs don't offer static by default
servers should have static ips
you connect those accounts to altdentifier after logging into it with discord
yea his server does, but he was concerned about the client
yeah'
generally, IPs shouldn't be used at anything higher than the network level, because that is really their only intended purpose
what do you mean?
it's kind of like keeping track of someone via their home address
people move, and they can have roommates
it stays the same for a while but it doesn't have to
ah
it's better to come up with another way to keep track of that person, like a name (altho people can change their name in the real world, I can't think of a better example)
yo does anyone have some insight into my issu
lemme see
looks like your templates aren't in the right folder
or they are rename d
oh i c
@tulip relic ty for the help
np
oh btw
wait are you sure that file exists where you think it does
even tho using their ip isnt always reliable, i think altdentifier does that as well when gcaptcha is the only option
templates/todo/userCreation/login.html
well i think it uses it in addition
maybe
yeah
it's really easy to get a new IP (I can do it in about 6 seconds), so you cant rely on that alone
i think discord's bans are ip based in some cases
I am trying to web scrape https://finance.yahoo.com/trending-tickers with urllib and bs4, but this page is completely rendered my javascript, so when I try to open the page with urlopen and print the page content, I get a bunch of Javascript in my console. Does anyone know a workaround this so that I can get the HTML content of the page after the Javascript has been rendered? thanks!
they're always ip bans btw
or at least im pretty sure they're supposed to be
selenium
yea maybe selenium
kinda slow but idk what else
there's not an easy way to do it bc pretty sure they sell an api for it
makes sense
will it get the html content after the javascript has been rendered?
ok thanksman
i gtg, i might be able to help tomorrow though
alr cya
o/
thanks man i appreciate it!
you can look at both, and no problem
this will probably help more than those
you can play around with the sleep values to find the lowest sleep value you can do
np
bro can somone help me #help-popcorn
ok
I am trying to create a login API in django where User can login using email and password can anyone help me out please i am completely new to API
you will have to start off by creating a custom user model https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html#abstractbaseuser
lets hear what you think of the redesign? theres so many lines of code to make something so seemingly simple look like that. random meme pulled from reddit/random filler text. no offense intended
okay
how can i also check that user which is logged in is an admin or not
If u have created a custom user model,add fields like is_staff and _is_admin, you can check if the logged in user is admin by checking user.is_admin field
Django's User model already has such fields that you can use, just extend the user model.
it is generally not recommended to extend the user model but the AbstractUser model instead
@versed python yeah that's what I mean
!paste
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.
im getting an error on importing flask that is:
ImportError: cannot import name 'Flask' from partially initialized module 'flask' (most likely due to a circular import)
any help is appreciated
https://paste.pythondiscord.com/befixamoga.kotlin
can someone check my code i am getting an error
Error:
TypeError at /api/v1/login
'str' object is not callable
is there anyone that can help me with some javascript, because i am using Ducument.getelementbyid but it is not working for me?
how to create a new page using Django and configure the HTML and CSS files in the website while running the website or server?
Like the wiki fandom
when you try to access a restricted page, django usually redirects to the login page. The first is the path for this redirect page.
The second one is basically a reference to path where the login page (it is not related redirect url in any way), and it is often equal to the redirect url
Thank you😶
hey,
I'm starting to work on a web app, and I want to use a js framework(like react or vue) along with python as backend - how can i easily do it? is there ant python framework that can help me build a dynamic web app?
Flask or django which one is better?
Bro i love that font, can I have it? Uwu
sure its called quicksand
Hi Robben589, this is a very controversial question. There is no "better" it all depends on what suites you better.
React and most frameworks usually parses data from a REST api, which you can do with django using the Django-Rest-Framework.
For authentication, I suggest JWT, alot of people dislikes it by its need for refreshing but I personally read the entire documentation and I was able to change the expiry date.
if you change the expiry token of jwt to a large time, you might as well use token auth
I'm 2 lazy to learn another auth library
I've been using express and experimenting with other backend libraries ( strapi, express, nuxt )
use django-rest-knox. it stores the tokens encrypted. jwt is plain text so anyone with access to the db can log in as that user. also jwt is one per user, and knox is 1 per device
knox is basically the same as jwt i believe in terms of use
jwt is useful because it has a small expiry time. If you increase to a large time, all benefits of jwt are gone. at that point you might as well use auth token method which is much easier to integrate
that being said, have you been able to integrate nuxt with jwt?
nope hahaha
I'm working with sockets.io atm
socket-io with express
Since strapi is just a plain old headless fms
Cms
strapi very useful for quick n easy fast apis
man drop downs with frameworks are so much easier to make then doing it in plain old JS. i remember building multi-tier drop down menus using onMouseOver/onMouseOut in JS 13 years ago and it was a nightmare. but boy was it a masterpiece when it was done
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return "Hi, dit is mijn eerste website!<h1>Hi<h1>"
if __name__ == "__main__ ":
app.run()``` it doesn't say anything
does someone know whats wrong?
and yes i did download flask
Check out the website's dashboard I m working on
i fixed it!
if name == "main ":was this the issue?
ahh, easy to miss
Yup
Anyone here experienced with Flask SQLAlchemy? Having a bit of trouble wrapping my head around Many-to-Many relationships 😒
in react i have an <h1></h1> and everywhere i go in routing it's still giving me the same tag why?
you probably included it in the default layout
Yeah tell what is the problem bro
@quiet ridge I managed to sort it, somehow. I don't really understand how the code is working since I've pieced bits together that I've found online but I'm trying to figure it out. Thank you though!
can you elaborate?
@void wagon
okay
thank u for your response
Error
File "./src/server/main.py", line 6, in <module>
app = Flask(
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/flask/app.py", line 601, in __init__
self.add_url_rule(
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/flask/app.py", line 98, in wrapper_func
return f(self, *args, **kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/flask/app.py", line 1275, in add_url_rule
rule = self.url_rule_class(rule, methods=methods, **options)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/werkzeug/routing.py", line 666, in __init__
raise ValueError("urls must start with a leading slash")
ValueError: urls must start with a leading slash
At first, I thought it was my @app.route(s) but all URL(s) there starts with a leading slash (/)
I don't understand why it throws the error
I'll get my code
main.py
from flask import Flask, request, render_template, send_from_directory
from os import path
from colorama import Fore, Style
from random import randint
app = Flask(
__name__,
template_folder='../public/pages',
static_url_path='../public/cdn'
)
@app.route('/')
def home():
return render_template('index.html')
@app.route("/style/<path:path>")
def send_css(path):
return send_from_directory('style', path)
@app.route('/monitor')
def monitor():
return '{"status":{"code":200,"message":"OK"}}'
if __name__ == '__main__':
print(f'{Fore.GREEN}[Python]{Style.RESET_ALL}: Running Webserver')
app.run(
debug=False,
host='0.0.0.0',
port=randint(2000, 9000)
)
line 6 is the app variable ```py
app = Flask(..., ..., ...)
html:
<div class = "spinner"></div>```
css:
.spinner:before {
content: "";
box-sizing: border-box;
position: absolute;
top: 50%;
left: 50%;
width: 60px;
height: 60px;
margin-top: -30px;
margin-left: -30px;
border-radius: 50%;
border-top: 2px solid coral;
border-right: 2px solid transparent;
animation: spinner 0.7s linear infinite;
}
@keyframes spinner {
to {
transform: rotate(360deg);
}
}```
Currently this loading circle is locked in the center of my screen, is there any way to move it to the top right of the screen?
@native tide top: 50%; and left: 50%; is probably what is keeping it in the center
I've just tested your code (but removed any additional modules such as random and colorama). I'm having no issues
That's wierd
Has the original Flask installation been messed with?
colorama and random is just additional modules
That's what I'd try. I'm by no means an expert, so maybe someone else can advise. But I see nothing wrong with your code, so I can't understand why it isn't working
same. the error make's no sense
i even searched S.O. for answers
didnt find one
so I've uninstalled and reinstalled flask
same thing
template_folder='../public/pages',
static_url_path='../public/cdn'
I think you need the absolute path
should i use sys.path.abspath?
anyone know of a good js discord?
there's TCD
they support almost any languages
:incoming_envelope: :ok_hand: applied mute to @scarlet patio until 2021-03-20 17:02 (9 minutes and 59 seconds) (reason: chars rule: sent 3134 characters in 5s).
!unmute 487761079389257742
:incoming_envelope: :ok_hand: pardoned infraction mute for @scarlet patio.
!paste
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.
use that
Oh. Id just type my question in separate messages
I have to „create a backend for RESTful API that should able to persist collections of GPS points (in JSON format), these collections are called traces” with example trace given:
[
{ "latitude": 32.9377784729004, "longitude": -117.230392456055 },
{ "latitude": 32.937801361084, "longitude": -117.230323791504 },
{ "latitude": 32.9378204345703, "longitude": -117.230278015137 }
]
As it is my first time doing something using Flask, i started from basics to expand it later.
Created database as stated:
id = db.Column(db.Integer, primary_key=True)
trace = db.Column(db.Integer, nullable=False)
latitude = db.Column(db.Float, nullable=False)
longitude = db.Column(db.Float, nullable=False)```
As I thought it would be a good idea to just insert data point by point and connect them into one trace with ‘trace’ number. It works fine for adding points one at time, but when it came to changing my code to let it take the whole trace (list of objects as stated above), I dont know how to do that. Is it possible to access objects from PUT request one by one and add them to separate rows? Or i should change my database structure to something different?
def put(self, point_id):
point_put_args.add_argument("trace")
point_put_args.add_argument("latitude")
point_put_args.add_argument("longitude")
args = point_put_args.parse_args()
point = PointModel(id=point_id, trace=1, latitude=args['latitude'], longitude=args['longitude'])
db.session.add(point)
db.session.commit()
return point, 201
my whole code https://paste.pythondiscord.com/acebehihag.py
I just got lost, not sure if my database idea is even a good one
anyone work with netlify I need some help
Hwlllo, how to get rid of useragent stylesheet?
its putting margins and i cant fill the background
hello django users, anyone tried ModelForms with async views ? it seems not working since it needs to get data from database to render the form
I use sync_to_async helpers when dealing with DjangoORM calls, but this one is at the template level ..
maybe the render() function should be wrapper with sync_to_async 🤔 I'll give it a try
oh it works
here is the solution:
def _sync_render(*args, **kwargs):
return render(*args, **kwargs)
async_render_wrapper = sync_to_async(_sync_render, thread_sensitive=True)
you will also need a wrapper for form validation
def _sync_validate_form(form_instance):
return form_instance.is_valid()
async_validate_form = sync_to_async(_sync_validate_form, thread_sensitive=True)
as far as I see, django is not yet ready for async python 😐
You can use something like a "CSS reset", which is basically a stylesheet that resets all the styles set by default by the browser.
You can also do ```css
- {
padding: 0;
margin: 0;
}``` if you want to just set the default margin and padding to 0 on everything.
or you can just set margin: 0 on body and html
ideal solution
Hi, I have a little issur. When I want to upload for the first time a video on a user account, it uploads on his account, but when i want to upload on an other, it gets the main user's name and uploads on the first person that has uploaded. Is there a way to change the user when uploaded because i use a form field ? Thanks Here are my codes
from django.conf import settings
from .validation_taille import validate_file_extension
from django.contrib.auth.models import User
# Create your models here.
class Videos(models.Model):
user=models.ForeignKey(User,on_delete=models.CASCADE,default=1)
caption=models.CharField(max_length=100)
Video=models.FileField(upload_to='video/',validators=[validate_file_extension])
def __str__(self):
return self.caption
def Profile(request):
all_Vid=Videos.objects.filter(user=request.user)
print(all_Vid)
if request.method=='POST':
form=Video_Form(data=request.POST,files=request.FILES)
if form.is_valid():
form.save()
else:
form=Video_Form()
return render(request,'Utilisateurs/Profile.html',{'form':form,'all':all_Vid})
def login(request):
if request.method == 'POST':
form = AuthenticationForm(data = request.POST)
if form.is_valid():
username = request.POST['username']
password = request.POST['password']
user = django_authenticate(username=username, password=password)
if user is not None and user.is_active:
django_login(request,user)
return redirect('MonProfile')
if user==None:
messages.error(request,"Le nom d'utilisateur ou le mot de passe n'est pas bon")
else:
form = AuthenticationForm()
return render(request,'Utilisateurs/Connexion.html',{'form':form})```
class Meta:
model=Videos
fields=('caption','Video')```
hello ive got a doubt
does anyone know how to fix: 'sqlite3.OperationalError: table "AboutMe_aboutme" already exists'
anyone know how to use fontawesome with html/css files only?
you have to #comment out the line of code where you made the table "AboutMe_aboutme"
because the table has already been made it cant be made again
i'm looking for a group of people who are new at django too and are welcome to learn together.
anyone?
Just add it?
do you know any html?
hello, not really a python question but a javascript one. I wanted to make a chrome extension that filled some forms automatically. Could I go about installing selenium in the extension resources, or are there other ways to do it?
It actually has little to do with Django. Anything non db related runs fine with async. But async db calls don't really do that much for you. Dbs have queue lines. That's just how they work. Even if Django was perfect with async it wouldn't actually do that much because a db isn't handling the async calls as async anyways
yeah but db calls are io so sure it will help
Just have a seperate url for response and install ajax on the site :3
ajax is really laggy though for some low end pc because it's sending alot of requests per min
there is also djangosocketio
i only heard of it but nevee used it
Had a look on its doc a few weeks ago
You'd get more out of Django async if you used Django as an api rather then using it for views. Don't really need async from what I can tell unless your using non help requests anyways
o_O wut?
yea, databases arent async. thats why you have to wrap db calls in database_sync_to_async wrapper.
they run in queue. not simultaneously
hey, having a little issue with my background....
this is what the background should look like
but once I added another part for text, which was too big to fit in the screen so it had to become scrollable, this happened
I'm using this css .cover-bg { background-size: 100%, 100%; background-position: center, right top; background-repeat: no-repeat, no-repeat; background-color: rgba(44, 48, 56, 1); }
<body class="cover-bg" style="background-image: linear-gradient(to top, rgba(44, 48, 56, 1) 20%, rgba(44, 48, 56, 0)), url('https://images.igdb.com/igdb/image/upload/t_screenshot_huge/sc8ecz.jpg');">```
how can I make it be like in the first ss again?
Can someone send me an up-to-date web development course please?
Hi, I need a second opinion in this:
I have the following schema:
type Subscription{
"Get all the posts from all following users of the user in context, if `UserID` is provided then only the posts from that specific user are passed, Range should be in this format: `0-10` `10-20` `20-30`"
getPosts(Range: String!, UserID: String): Post!
}
type Post{
ID: String!
Author: User
Title: String!
Published: String!
Visibility: String!
Disabled: Boolean!
Content: Content!
Reactions: [Reaction!]
Comments: [Comment!]
}
type Comment{
ID: String!
Author: User
Content: Content!
Disabled: Boolean!
Comments: [Comment!]
Reactions: [Reaction!]
}
So what happens here is that the client can subscribe to the getPosts event and basically retrieve the posts as they are loaded so there is no big server side buffer to hold more than 1 post at a time.
A post has a field called Comments which returns a list of Comment, comment has many fields and SubComments which are a list of Comment.
Should I retrieve all the comments and subcomments with each post or should I make another subscription for comments to be sent for each post when needed.
The latter is more work obviously so I am looking for a second opinion in this
You need to have some sort of limit on comments retrieved. For really large threads, it wouldn't be a good idea to retrieve all comments at once. You could limit it to a few sent with the initial thread request and then request more comments separately later in chunks.
In total or per level?
I am not using Python, I am using GoLang to resolve the subscription, the data is gathered through a gRPC stream from the posts microservice
No, it will only retrieve the first 10 comments and the first 10 comments of each comment
This is the resolver for context purposes
https://gist.github.com/sneakykiwi/983b5bd208d99802bb3095a483022ac2
If it's only 10 then I think it's okay to get them together with the post, as long as you're not returning 10 for each level of nesting cause that could quickly add up. You wouldn't want to have threads on their own without comments would you?
When you say threads you mean nested comments?
100 comments doesn't seem that bad of a number, its a fairly fast query to the db
I meant posts, sorry.
Ah okay
Well 100 is fine but if you don't have a hard limit then it could get infinitely large, or until the content length limit is reached or something.
Well again, the first 10 posts will be retrieved
You are able to range
so there is a 0-10 first 10 posts, 10-20 20-30 XX-XX
So, basically pagination?
Yes
But the thing is that they aren't first buffered and then sent together
Each post gets sent as soon as it gets found
So the memory footprint of a process like that is equal to loading one post from the db
But what about comments, are they paginated? I was concerned with infinite nesting of comments, not with many posts being returned.
Ah okay
The primary comment which sits under the post
And the comment of the primary comment
I am just trying to think rationally what would be best for scaling
What I can do is for each post that is found fire a new process instead of waiting for it to complete
So that as soon as it a post gets found it iterates to the next while still processing the previous one
The problem with that is that if a post has no comments there will be no loop and no structuring so it will finish faster and they get sent to the client directly so the order will be messed up
Because if a newer post takes more time to process than an older post the older post will get sent first
Yeah I see what you mean
I can implement a wait group but that would basically buffer the posts waiting in the memory which I dont want
And you don't want the client to have to fix the order
No i don't want to
Because that will also make the client buffer the posts
And it will look bad UX wise
Imagine having posts randomly appearing in ur feed
in random places
Well you have to display the post anyway so just display it right away and if you get an earlier post find the right spot and insert it. But you're right, it is worse ux. No buffering needed though
I will figure it out at last, thanks for discussing this with me
I haven't been able to wrap my head around it for a bit
I think for comments it's okay to send them with the post since you'll be requesting them anyway. Though there isn't much flexibility if the client doesnt want to show them all at once. Like, it probably won't show all 100 if it gets that many, but it will be forced to have them and therefore store them locally somewhere.
No, its not forced to have them, I am using GraphQL so the client chooses if it wants to get the comments or not
I mean it may want some and not all
oh you are right
I should make the comment subscription anyways then
I didnt think of that
And later request to load the rest if the user clicks show more
yea yea
Shit thanks haha
Like how Reddit works
i forgot that could be a case
Yea
Like I said at the start it may be fine to send a very small amount and have a means to request more in chunks but yeah you could make it fully subscribable
that's probably what i am going to do
Thanks a lot
You're welcome
Can someone please help me? project in flask```point_fields = {
'id': fields.Integer,
'trace': fields.Integer,
'latitude': fields.Float,
'longitude': fields.Float
}
@app.route('/', methods=['POST'])
@marshal_with(point_fields)
def Add():
point=list()
req_data=request.get_json()
count = len(req_data)
for i in range (count):
point.append(PointModel(id=i+1, trace=1, latitude=req_data[i]["latitude"], longitude=req_data[i]["longitude"]))
return point[0]how to make fields so I can return the whole point list like that:[{...],{...}, ... ,{...}]```
@scarlet patio you are returning only the first element of the list, you need to change return point[0] to return point
the point is, It wont work this way as im returning marshalled version of point. only one point
i probably should make another dic that would act as list of point_fields
not sure how it should look
Why are you returning them marshalled?
need an output to be in json as follow: [ {...}, {...}, ...., {...}]
like a list of objects
Yea if you just do: return {"data": point}
it will return it in that format
Or just point in that matter
They get marshalled internally
Another thing you can do is: return json.dumps(point) this will render the list as a json object, then once you receive it you can parse it as json in the frontend
But returning a list is a valid json object
Remove the@marshal_with(point_fields)
Let me just fix it up for u
give me a second
@app.route('/', methods=['POST'])
def Add():
point=list()
req_data=request.get_json()
count = len(req_data)
for i in range (count):
pointObject = PointModel(id=i+1, trace=1, latitude=req_data[i]["latitude"], longitude=req_data[i]["longitude"])
point.append({"id": pointObject.id, "trace": pointObject.trace, "latitude": pointObject.latitude, "longitude": pointObject.longitude})
return {"data": point}
Try this ^
@scarlet patio
gives an error :/
yes, works 🙂 thank you so much
np
what is below the below the navbar called?
like this https://www.tesla.com/
below the navbar
does it have a name?
I have a route with @ in the url. If I visit the route normal, then it works. However, when I send a redirect to that route, it replaces @ with %40. How can I resolve this ?
dumb question?
<div id="container" onClick={()=>doSomething()}>
<div id="child" onClick={()=>doSomethingElse()}></div>
</div>
``` when you click on child, does container get called?
in case anyone wondered, the answer is to also do event.stopPropagation(); in the callback
yes, events propagate through parents, seems like you answered it yourself though 😄
lmao no one answered fast enough. i move quick haha. i didnt know that was a thing. the child should honestly just overide the parent, but it is what it is
Me either, thanks for the information
Hello, what is the ideal way of doing a like/unlike post system? at the moment I have it set up to go to 0.0.0.0/like/postid but is it better to use forms instead?
with Flask*
What you mean?
you want not to show the id?
or you mean you use forms instead of a simple button?
For example
I believe he wants to have a live feature where he can send likes and stuff.
Here, Miguel uses an empty form to post to the server to follow/unfollow users, whereas the way I'm liking/unliking posts is by going to a URL, (0.0.0.0:5000/like/postid
I'm just wondering if there are any benefits over going with Miguel's way of doing this type of thing
The way on doing it is onclick post the data as a parameter, and have the server take it in as a parameter
Well if it's url without a secret key, its alot more vulnerable
isnt it better with buttons?
You have buttons, but how will you handle the request?
What will happen when you click the button?
i mean a link tag
You either: redirect to a certain link then return
Or
Post the data to the server
using a tag i mean
Essentially, you'll setup an API at and endpoint such as localhost:port/like/<post_id>/, when clicking a like / dislike button, it will make a request to that endpoint and update the post's likes within the database
Okay thank you people 🙂
This is what I'm currently doing, just wanted to make sure I'm using best practices
it's called html escaping, if you're using jinja2 templates I roughly recall you can use a html_safe filter to stop html escaping. That should help you find the answer 🙂
I can do it in Jinja. The problem is when I do a redirect from a route
return redirect(url_for('donate.donate', username=user.username))
Hi. Can someone recommend a good video tutorial of Django?
use .unescape() to stop revert escaped HTML.
Hi all — anybody able to advise on how best to implement maps?
I have a flask web app for customer management and bookings, and I would like to plot customer addresses on a map. It will be all address that have a booking on a given date.
I’ve only just started researching how to get it done, so any guidance from experience would be appreciated. Thanks
are you using JS? There's some good JS mapping libraries which would most likely simplify that a whole lot.
do you mean like:
return redirect(url_for('donate.donate', username=user.username)).unescape()
because that doesn't seem to work, and I don't see what it does. Is it not possible to unescape the whole route? because I have several redirects to this page
I don't use Flask, it's just guidance to help you find the answer yourself. So for flask-specific things for that, I couldn't help.
Thanks anyway, I will look into it more
Not using JS right now, but no reason why I can’t try and make it work with JS as long as I can pass addresses or coordinates from flask/database easily enough 👌🏻
using plain-JS, you could use:
or check pypi for some flask-related map packages
there's also Leaflet, if you don't want google maps.
Pertaining to Django:
I'm trying to work out why I'm hitting an error, I recall it was working yesterday and I don't think anything actually changed -
error:
Using the URLconf defined in barHubCore.urls, Django tried these URL patterns, in this order:
admin/
[name='homepage']
single/<slug:slug> [name='single']
^media/(?P<path>.*)$
The current path, single/first-post/, didn't match any of these.
slug = 'first-post'
code from views:
def single(request, slug):
data = Post.objects.get(slug=slug)
return render(request, "single.html", {"post":data})
also code from urls:
path('single/<slug:slug>', views.single, name="single"),
it should be path('single/<slug:str>'
you are taking slug as a string
@fair agate
still the same error returned
Using the URLconf defined in barHubCore.urls, Django tried these URL patterns, in this order:
admin/
[name='homepage']
single/<slug:str> [name='single']
^media/(?P<path>.*)$
The current path, single/second-post/, didn't match any of these.
all of the other endpoints/functions seem working, and I recall it worked yesterday and I don't think I changed anything so it is bizarre
I tried that too and it didn't work either 😦
Using the URLconf defined in barHubCore.urls, Django tried these URL patterns, in this order:
admin/
[name='homepage']
single/<str:slug> [name='single']
^media/(?P<path>.*)$
The current path, single/second-post/, didn't match any of these.
How can i make a custom domain when i have my own domain name. To be more specific -
i have one domain say - abc.com then how can i make something like - test.abc.com? Asking this for a friend, thank you for your answer
I use cloudflare to manage my domains and its pretty simple to do with cloudflare
Just add a A record of test.abc.com pointing to your host IP address in your Domain Provider, configure Ngingx to serve the different websites under the one domain.
Your looking to serve subdomains
Cheers bud
if you want to avoid this error in the future, set APPEND_SLASH=True in settings.py. It means that if Django can't match the URL to anything in urlpatterns, it'll setup a redirect with an appending slash (/)
how to make an image full screen?
guyss
so i am trying to do something with js
but i am facing issue
so i am trying to detect a resize event for an element, after it's resize i want to give it a margin depending on its size
but when i give it the margin, the resize event is called again, and the final value will be messed up
can you paste some code?
give it a height of 100% (of the viewport) and width of 100% (of the viewport)
https://ibb.co/MZ4rB5R https://dpaste.org/vUL4#L18,48,50,51,52 I m not getting those failed recepients please help
In Brython, I'm have a syntax error at the end of this line, but I don't seem to have the same issue in vanilla Python, and syntax checking sites don't seem to see one either. Any ideas what's going wrong?
note = browser.html.DIV(browser.html.SPAN(text,id=textId) for text,textId in {"Note Text 1":"noteText",":"Letter 1":"letter1","Letter 2":"letter2","Letter 3":"letter3","Note Text 2":"noteText"}.items(),id="noteDiv")
packages can work, but is there any problem with my code?
Not sure didn't check
The library checks if the smtp of the provided email address is valid
you cannot guarantee that an email is correct until you send the mail or Helo
ok then how will the email that send know it works? That's right, by checking if the smtp ip is real for that address
the email is a text file. Once the other end receives it, it sends back a response telling which email addresses it could find and which not. The other end parses the text file
the web server implements HTTP, the mail server IMAP, POP3, SMTP
hello
is anyone online ?
i just need to ask one thing
is it dangerous to install Django and Flask on the same machine ?
No, of course not
It’s not but just use a virtual environment?
Hi there. I'm finding that CherryPy seems to be reading static files as some encoding other than UTF8 because unicode chars in files are showing in the browser as garbled nonsense. Does anyone know if this can be fixed with a config setting or something? Thanks.
How do you render a template INSIDE of another template in Flask?
Passing a rendered template as a value into another doesn't seem to work
Like, I'm looking for:
render_template("main.html")
And from main.html,
<body>
{{ navigator }}
{{ content_from_specific_page }}
</body>
you probably want jinja's macros
or using template inheritance with extends
that second one might work. lemme try it
PERFECT, MATE!! That's EXACTLY what I'm looking for!!
Thanks!!

Hi, im not sure if this is the right place to ask but here i go anyway. I want to control some relays with my Raspi over a web-interface. The problem is that i dont know what i am even looking for to find tutorials online so if guys have any idea Ty
@swift igloo
https://duckduckgo.com/?t=lm&q=raspberry+pi+relays+python+web+interface&ia=web
https://tutagomes.medium.com/simple-home-automation-python-relay-module-c0e088e05a2b
What do you guys recommend learning first Flask or Django
is there someone who has used allauth python for google authentication in their django app?
Django is becoming more popular i've noticed
I also think it's a more contemporary in its design philosophy (sort of similar to popular js stacks- mern, mean etc)
in other news- does anyone know a good hosting service for django sites (similar to netlify or docusarus but for django)
would very much apprecaite it
(just tried digitalocean but they immediately locked my acccount (????))
you can launch on aws, although its not free and youll have to get your own address. but still not bad
awesome, i'll look into costs w/ aws- ty
heads up, if you create an instance dont create a django instance. just get a ubuntu instance and install all the stuff into linux
i quickly googled it & am planning to follow this guide: https://aws.amazon.com/getting-started/hands-on/deploy-python-application/
oh- rereading what u wrote it doesnt sound like complete jargon. hopefully it'll make more sense to me as i proceed through aws
so as this point i go- platform: linux, blueprint.... django (?)
click os only and use linux.
first month is free if youve never used it and 3.50/month after
can get a domain normally for 8-20$ a year. unless your looking for something super specific. but until you get a domain, just use the static ip your given
and you can run the dev server in the instance as well just an fyi, just have to open port 8000 in the firewall, and start the dev server on the local ip address
yeah i searched through for the domain over go daddy earlier, it's for a family website & lucky it's not a popular name
🤔
appreciate the support ! going to keep clikcing thro the aws
personally i think its the best option, just not completely free
also good excuse to start becoming familiar with AWS 😎
ill boot my server up just to give you an idea. if you want. ive had it down because im working on pushing into production
i've already built everything locally on my laptop
how would I push it onto the instance
you also dont need to use their database. from a linux instance, just install it yourself
or for a small website just use sqlite3
🤔 could i ftp transfer files
or perhaps... ssh
Amazon Lightsail is the easiest way to get started on AWS. We have a number of tutorials to help you on your cloud journey. In this tutorial, you will learn how to deploy a Django-based web application onto Lightsail. You can also follow along the written tutorial.
Learn more about Amazon Lightsail at https://amzn.to/2GfYysc
Subscribe:
More ...
oh 🤔
easiest way, upload to s2, set to public and then use wget to pull them
OHHH
and if use a dev server, you have to use screen to keep the dev server running
🤔
probably could throw it up to a git repo & pull it ?
wow i feel my braincells rubbing together
tyvm 😎
ya, since your already in AWS just upload to an S2 container its simple really. all my static files are being pulled from my s2 container
i;ve just never used (or head of) a s2 container
http://www.safespace.fyi:8000/login just to show you. thats my django backend based site hosted on aws.
to google 😎
although its way way out of date now
and im running django/rest framework/react from inside it
nicee
Welcome to another Django tutorial, here we take a look at deploying Django to AWS Lightsail. In addition we also go through the steps of uploading and download files with a SFTP manager and in Windows 10 take you through how to remotely SSH into the server.
00:00 Introduction
01:56 Get started in AWS
03:06 Create new instance
06:51 Feature tou...
😎 sort of following, can kind of do same thing w/ just ubuntu os (instead of django, little difference so far)
go it running off the instance ip- 4:30 am, think ima come back to it tomorro
nice
who builds their nav bars
<nav>
<ul>
<li>Nav 1</li>
<li>Nav 2</li>
</ul>
</nav>
VS
<div>
<div>Nav 1</div>
<div>Nav 2</div>
</div>
``` and why should you use the top version?
The former uses semantic elements, namely the nav. Not sure if using an unordered list really matters.
Semantic elements have better readability for both us and machines
So it could enable a browser to provide better accessibility features
For example, the reader view on Firefox
Using an unordered list probably helps that too now that I think about it
My Flask app is using an external API with one user only, and today I'm using Lock() on a bool variable "in_use" to serialize access to the API if many requests try to use it at once.. This works for multiple thread but not multiple processes.. Any idea how I could share that variable in multiple processes?
Anyone has worked on django here?
why?
what do you mean why?
why do you need to synchronise access?
each process has its own memory space
because only one request at a time can use the external API user
locks are for synchronising access across threads
...why?
that’s what I’m asking
I don’t understand the motivations behind that design
because we only paid for one API user
it's a CAD integration to an ERP system
i actually don't really know if it's a problem yet. maybe i can run just one process
I’m assuming
when you say multiple processes
each is running an instance of your server?
i.e. the processes are not spawned by Python
running the app on mod_wsgi in apache on a windows server
but i read somewhere now that maybe mod_wsgi on windows doesn't support multiple processes so it could work anyway. feels bad though to not be able to move it to linux or something just because of code design
use sqlite
to synchronise access
there’s defo a better way
but I haven’t really had to deal with this so I don’t know what it is offhand
hmm, true i kind of forgot about sqlite. i was thinking i could use my database but sqlite is probably waay faster. could use it to cache some requests too i guess
i'll look into it, thanks
guys how can I put the "cognome" besides "nome"? there are no <br> between the two ones
above the nome do a <div class="row"> <nome> <cognome> </div>
if it doesn't work u shld try a container
if it does work let me know 
thanks imma try!
okay let me know if it works
@cloud path use flexbox. You'll be able to get a grid-like layout with rows/columns in pure css.
i am not a css expert but looks like this shld be a good practice
i just gave you a quick and ready to use solution
using flex will make it look better
but it is a lot of code
yeah
@cloud path
https://css-tricks.com/snippets/css/a-guide-to-flexbox/#background
It's really simple, if you use bootstrap you can also leverage flexbox. It's a must!
Our comprehensive guide to CSS flexbox layout. This complete guide explains everything about flexbox, focusing on all the different possible properties for the parent element (the flex container) and the child elements (the flex items). It also includes history, demos, patterns, and a browser support chart.
np!
i'll try that
thanks guys!
is there to much going on now?
could someone help me with flexbox?
the css is great
theres definitely a lot going on css wise
im a full stack dev. i built the django/rest framework/channels backend as well
hey fellas some pretty basic questions w/ django
deployed my project via aws recently
but having a hard time routing to the assets (images, css, etc)
what is the ideal way to organise that within django ?
(it all runs fine when I deploy it locally)
are you deploying with debug=false?
yeah
django is put into production mode when you put debug=false and no longer serves static, youll have to install apache or nginx/gunicorn to serve your static
😎
a lot of people use apache to run django, and use nginx to serve static
and yes, you run both servers at the same time
no worries. you have it simple. i have to get nginx gunicorn/uvicorn up and running as well as a postgres server and regis. its gonna be a process for sure
do you guys have a fix for this problem when the image is not loading?
profile.html
maybe I missed typed something?
@native tide Can you type http://(your hostname)/media/profile_pics/solo_leveling.png in the browser?
and is DEBUG on?
how to know the host name?
😆 I am new here
it's this part of the url
right click on the image, copy image address, and paste here....your site is working fine but your avatar image is missing, probably the image does not exists or you point to the wrong path
is this the corey schafer tutorial ? 😏
went through it compulsively the other week- it's great, i think the problem is as described, maybe not directing the src to the image
||up & running, just started registration for domain, everything working, thanks heaps!||
also, i'd reccomend this resource for anyone trying to deploy django using aws: https://www.youtube.com/watch?v=ZpR1W-NWnp4
Learn how to deploy a Django website on Nginx with uWSGI as a web server gate interface. In this complete tutorial, we will use Ubuntu 20.04 and the latest version of Django and uWSGI. Nginx will communicate requests to the WSGI via a UNIX socket. Additionally, we will create a system service to launch the website at boot (and keep the service r...
Hi there. I'm finding that CherryPy seems to be reading static files from filesystem as some encoding other than UTF8 because unicode chars in HTML/JS files are showing in the browser as garbled nonsense. Does anyone know if this can be fixed with a config setting or something? Thanks.
Hi All,
I have a static website (really old) that displays every employees names/title/extension, (up to 100). Is there a way to modernize it?
Or does anyone know a good way to update it?
I have a question - can discord bot create a server? Thank you for your reply.
0
Discord bots cannot create servers; only user accounts can. While it is possible to create an account and use its token to make a selfbot, it is not reccomended as it is against the discord Tos.
And is there any way to automate server creation?
No
oh no
That's just common sense. Think about how many millions of bogus servers would be created every day if you could automate it.
That's true
hey guys is there like a shorter syntax to a child component props equal to the current states
like a component inside another component, in react,
HI guys, I m trying to do a ManyToMany Model field which contains a list of added users, but I want it to be empty on default. The problem is : it gets all the Users per default in my model. any suggestions ?
users = models.ManyToManyField(User,blank=True)
hey guys, my flask web app was working fine on a server of a friend of mine, then he moved the database to another server and i changed the datas but it gives now this error, and isn't working
Warning: (3719, "'utf8' is currently an alias for the character set UTF8MB3, but will be an alias for UTF8MB4 in a future release. Please consider using UTF8MB4 in order to be unambiguous.")
result = self._query(query)
tryusers = models.ManyToManyField(User, default=None)
this is the way to do what you want to
i dont get what page you are on now but if you registering new...(thing) hen thats true
in here it says who you wanna create it for you can leave it or choose someone
if it didnt work add it like users = models.ManyToManyField(User, blank=True, default=None)
and now you can just leave it
i dont get it. maybe i could help with more explanation
Hey, I am using flask
I wanted to know the best way to accept payments on my site....
pls help
PLS HELPPPP
See this everyone updated this user profile
it's best to be explicit about the props you pass to a react component. don't leave things to be implicit (this is why typescript is awesome :D)
anyone know why when i try to dp FlASK_BLOG=hello.py in the terminal it shows an error
even though i did exactly what the docs say
its so i can run the application but its saying| Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
- Debug mode: off
Usage: flask run [OPTIONS]
Hey, I am using flask
I wanted to know the best way to accept payments on my site....
pls help
it is empty by default. the admin form just allows you to select many users to apply to your row within the database. If you do not assign any users to that row, it is empty.
you can test this by using the django interactive shell python manage.py shell and checking the users field of a row.
@nicky si how could I do an empty list in which i can add many users ?
you already have that... as I have explained
make API requests to your payment processor's endpoints (use their docs), or find a wrapper for your payment processor on pypi, sometimes it makes it easier.
Sorry, I don't understand which docs or what is a payment processor......
payment processor = the company which processes your request, PayPal, Stripe, etc.
You integrate their payment processing by following their documentation, or the other option stated.
Yea, I tried stripe but there was some weird thing that you need to add the name, shipping address and intent for the customers, for international payments, but they code they wrote was a bit different from the one I had written already for non-international payments, and I didn't know how to implement it in there. So, I have been looking for an alternative.....
why doesn't it work? https://hatebin.com/pnfvicvdnv
i'm trying to make snapscroll but it doesn't work
it shouldn't be too hard, but I guess you could look for a stripe wrapper on pypi for flask which could simplify things
anyways, if anyone atm is learning React, I just wanted to say you should 100% learn typescript to go with it, it makes things so much more reliable.
of course you can, you can use selenium to create servers (provided you have the user accounts), send API requests to your server to then communicate to your bot for it to join.
if i have lots of javascript running in the background the browser would become slow?
generally, yep. if you have thread-blocking functions in your JS script, async could help make things "faster"
ah
so ill have to use async
cause i belive one of my functions, are thread blocking. looping over an array of objects
700 objects. i see
has anyone deployed a flask web application on heroku?
stuck in an error here
never deployed flask but django
maybe i can help
With this py file = open("templates/index_graph.html","w") file_to_add = open("templates/g_test.html", "r") file.write(file_to_add.read()) file.close() it rewrites content of index_graph.html with g_test.html. How to add it not rewrite whole file?
file = open("templates/index_graph.html","a")
a = append
w = write (writes over any existing content)
oh thanks!
i need to add values to html trought render_template, and add that html to another html with that values. how?
@native tide jinja2 template inheritance
No worries man. Glad to help
Anyone tried working on a live streaming mobile application? Can you share how you designed your infrastructure
hey guys, in flask, is using blueprint the same as going to django and creating a app?
It's not identical, but a lot of the patterns and purpose are the same.
Hi everyone
just getting started with django, reading the documentation, installing it
as far as I understood installation involves the process of just creating template files with default settings etc.
I wonder if it is possible to create a django project from zero without installing it from terminal
i thought it would help to better understand the structure of the project
@young ferry
Technically, it is...
but you don't wanna do that...
Well, If you have just started...
https://docs.djangoproject.com/en/3.1/intro/tutorial01/
try this ..(all 7 parts)
and then try making it by yourself...
What frameworks you guys can recommend for frontend? 🤔
Emm.... Django? 
Not for backend, i'm talking about frontend frameworks
React/Vue/Angular
React(btw out of these only Angular is a framework rest are libs)
also, It depends.
I was asking the same question once...
at that time a friend of mine who uses Vue recommend React because of its community support and available resources...
You can't go wrong with any one of these...
Isn't vue considered a framework though? 🤔
Yes in reality
That's one discussion of its own...
but i think so...
They're not really libs as they're considerably more opinionated in how they're setup etc but vue is more flexible in that regard
i dont get why people use statebased frontends
Overall I'd say go with Vue just nicer to work with
i mean its fine if you have static webpages, and its also good if you know json as your very first langauge, but if you have a python background, learning js is so hard
I don't really like vuex compared to angular services
bro react and redux over any other framework
It isn't hard
I don't want to write boilerplate code 😉
yes it is bruh what you on about, do you honestly think you can teach redux to someone who has a python background
Js isnt really hard, react babies you so nuch its pretty easy todo stuff
in the same time its takes to teach somone who knows js
Redux isn't hard but it's tedious to write all these actions and reducers compared to angular
your point doesn't really make any sense
or say mobx which i don't really like
redux is such a different approach to frontend that ive ever seen, it was such a curve ball when i first started to learn it
If you want a real doffrent approach just use Wasm for everything 🤣
damn that was funny bro
redux is easy, put simply its a global state manager. pull this data store the data in a specific spot. now every item that subscribes to that data has access to it.
Tbf I've written entire frontends in wasm, suprising amount of fun and nice to use a language other than JS at times 🤣
I just don't really see a point in using mobx when observables in angular are so much easier
i would say that a frontend framework is somthing you need to learn not somthing you want to learn if you realise how easy the rest are, but bing honest, after all the dogshit boilerplate, redux and react are pretty fun to code for, but that learning curve was jsut way too much for one attempt
I had problems with react since it give you too much freedom and needs 3rd party libraries
So it's hard to choose 😉
alot of people prefer frontend to backend especially in large systems