#web-development
2 messages Β· Page 118 of 1
yeah

How can I pass multiple objects to one class based view on Django?
is heroku fine for hosting?
the company seems legit. their services are useful. the deployment process is not easy
Pretty sure heroku are one of the easiest, no?
regarding deployment efforts you mean?
yes, the deployment process / time
Honestly just get a cheap vps
i agree, 5$ for a virtual server are 2 coffees
working with django channels to send data from backend to frontend and I went ahead and created this consumer
class AppConsumer(AsyncJsonWebsocketConsumer):
async def connect(self):
await self.accept()
async def create_app(self, AppObj):
# Deserialize AppObj into json
app_json = ApplicationSerializer(AppObj)
await self.send_json({'action': 'create', 'data': app_json})
How would I go about running the create_app method in another python script?
I thought about creating a reference when I instance AppConsumer in routing.py but that didnt seem to work either, any suggestions?
Feel free to @swift heron thanks!
tried doing the following
# From Routing.py
appConsumer = consumers.AppConsumer()
websocket_urlpatterns = [url('computer/', appConsumer.as_asgi())]
In python code
# Not async code
sync_to_async(appConsumer.create_app(new_app))
Did it without the sync_to_async function and did it with and I added a print to the create_app method which was never called. No errors in console so what else could I try?
Anyone familiar with django-content-editor? Following the docs but can't get the plugins to work for the life of me
Anyone know y I have to rerun the "runserver" for my website to update even tho it should just update when I save all my files?
why do you want to do that?
Trying to find correct way to send data to the frontend using channels is all thought this would be the correct way, is it not?
use the channel layer?
ahh I have heard about that, thought that was only for communicating between multiple instances of channels, it is also used to send data into a consumer?
I recall looking at channel layers a while back and didnt it also use something special called redis?
yes
the thing is
you have ONE consumer that's handling the websocket
you want to talk to that ONE consumer
not create a new one.
right so I thought the consumer was being created in the routing.py if so couldnt I just grab a reference of that consumer there?
anyhow thanks for your help ill take a look at channel layers and redis tommorow seems to be a bit more complicated when looking at it and involves more setup. Thanks for pointing me in the right direction
huh.
hm.
I'm p sure you're not meant to do that...?
but even then
note that in the routing
it's turned into an ASGI application
and you don't know what happens there
yeah, this was just my thinking as a way of possibly doing it. This was the only place I knew where a Consumer instance is created so I figured I would have to grab a reference there I didnt realize the correct way was through channel layers
yeah I just started with channels a week ago too
awesome
https://github.com/hhhrrrttt222111/fatigue-detector
Long duration of online classes has a bad effect on students both physically and mentally. So, we team 3xpl0its.axx is developing a website that detects fatigue and drowsiness in the students along with other features.
Technology being used is Flask for web and OpenCV, dlib and imutils for detection.
can u reccomend a good tutorial for jwt token auth?
FastAPI framework, high performance, easy to learn, fast to code, ready for production
seems to cover both cases.
ok thanks
Sure thing.
I am thinking about adding an error message into the wepage, what should I do, especially with this bootstrap
the html part
how do i add static css files in my html file in django???
you will want to add this to the top of your html
{% load static %}
This means it will scan your static directory in your App for all the js/css files you have and then from there you can load them in the usual way
<link rel="stylesheet" href="{% static 'name_of_file_in_static_dir.css' %}">
@vestal hound hey I wanted to ask you this since you were also working on channels and redis. when installing redis are you on windows? seems like there are alot of repo of people porting it that are all deprecated
so should we write this command?python manage.py collectstatic
you dont need to use that command in order to get this to work
oh
but its not working
i tried it
hmm I have never used that command before, is your static directory in the right location?
is in under file not under project or app
like for instance it should be like this
Oh this would be your App I believe, whatever directory that doesent contain settings.py
sure
wait
nope I do all my dev work on Ubuntu
I want to make a cross-browser extension (chrome, firefox and brae) with python
how can I do this?
idk anything about it
an extension that block yt recommendations
another one which blocks websites .......
when i change my ckeditor skin to kama it doesn't work like it is not being shown on the site, on the other hand when i use monno it works.
how can i set it to kama?
ohk
@thin dome what have you tried?
Does anyone understand celery, I'm trying to setup a task that runs once a day
Then expires on the 3rd day <- That's the part i want to do using celery, is there a built in way to handle this ?
guys i mad every thing but its not work
@native tide And to answer the question
There isn't one
You'll want some css
Or to just stick it as an attribute of the tag
@haughty turtle i have loaded static file in .html file i have and also added {%static ' '%} lines
I'm working on creating an API using DRF. I want to send json data from an external script to a django view using post requests.
django_view
elif request.method == 'POST':
json_data = json.loads(request.body)
code = json_data['code']
data = json_data['data']
external python script
import requests
import json
data = {'code':'101400', 'data':'101'}
payload = json.dumps(data)
headers = {'Content-type': 'application/json'}
r = requests.post("http://localhost:8000", data=payload, headers=headers)
The code works fine, but I want to know if I'm doing the pythonic or django way of doing things.
why aren't you using a serializer
@vestal hound I don't want to pass the data to a db, I was to extract data from a db using the data received in the json file
go on
@vestal hound that pretty much it, when I use request.body am I doing it the right way, or am I missing something
@thin dome how is your static folder set up?
show the whole view
okay so
I don't really get this
how does that fit into a POST?
the external python script sends a post req, in it I pass some json data, then I receive it on the other end in a django view. That's pretty much it. Side note, I'm not using the json to store it in a db, I'm just using it to access info already present in the db.
I was to know if I'm passing and receiving the data appropriately
@api_view(['GET', 'POST'])
def function_name(request):
if request.method == 'GET':
entries = Code.objects.all()
serializer = CodeSerializers(entries, many=True)
return Response(serializer.data)
elif request.method == 'POST':
json_data = json.loads(request.body)
code= json_data['code']
data= json_data['data']
CodeObj, created = ProductBasket.objects.get_or_create(
item = code,
data = data
)
I was to know if I'm passing and receiving the data appropriately
@api_view(['GET', 'POST']) def function_name(request): if request.method == 'GET': entries = Code.objects.all() serializer = CodeSerializers(entries, many=True) return Response(serializer.data) elif request.method == 'POST': json_data = json.loads(request.body) code= json_data['code'] data= json_data['data'] CodeObj, created = ProductBasket.objects.get_or_create( item = code, data = data )
@Dr.Crispy#5919 why are the models different?
you can use request.data, incidentally
Does serializing a queryset return it in JSON format?
I forgot to update the model names
no
serialization turns a model into a dict
the renderer is the component that then turns that into something that's sent in the response
e.g. JSONRenderer
feel like
this is weird structure...
your GET returns multiple objects
and your POST is a get_or_create...?
π₯΄
So once you have the serialized model, Response() would turn that dict into JSON by some means?
Oh I found the docs
So Response() renders content based on the renderer specified in settings.py
e.g. JSONRenderer as you said
can I show pic in js? or I need some other stuff ?
with flask how can i get the value of checkboxes when theyre updated without the person having to press a submit button
@copper lagoon sounds like a JS thing
Yes
Ty
if u want i can show u my views too
hey guys, anybody just getting started with django?
cursor.execute("INSERT INTO User (expire) VALUES (?) WHERE username = ?;", (time,username,))
can someone help me with what im attempting to do?
i am trying to find a user, then change the expiration date on the account
@copper lagoon you can use the onChange event listener for your option, so when it's selected, you can then run a JS function which sends a request to your API with data (then you can do as you wish with that data).
i cant fix it
@mystic wyvern what's the issue
the page can't load
look her
the name of view?
No... what is the error saying?
dudes is there a bootstrap class that centers the alert messages or i have to write my own?
The div or the text?
you'd have to do it yourself with CSS then (ifaik bootstrap don't have classes for that), but you could have a col div within a row div and then change the width of that col and I believe that is centered.
row justify-content-center
there you go
that will center any col divs within the row
that's essentially just flexbox but the bootstrap class version
it didnt worked
well i will look around and see what i find π
just good to know there is no bootstrap class for it π
it should work, can you show your html structure? Also are you using the bootstrap container?
i fixed it π
text-align: center;
this worked
i had it in the wrong place π
So you wanted to center the text, not the div?
<div class="alert-center">{% if messages %}
<ul class="alert alert-danger" role="alert">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
</div>
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
<ul class="alert alert-danger" role="alert">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
</div>
{% load static %}
also did u configured ur static directory in the settings.py ?
can you show static_url and staticfiles_dirs from settings.py @thin dome
yes
its ```STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
STATIC_ROOT = os.path.join(BASE_DIR,'assets')
i havnt changed anything in STATIC_URL
STATICFILES_DIRS = [
(os.path.join(BASE_DIR, 'static'))
]
think it takes tuple
so u have to wrap it with ()
π€£
can you copy the head section of ur page?
make sure u dont forget ({%load static %}) in your templets
can u show me your templets
ok
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<meta name="description" content="Test">
<link rel="stylesheet" type="text/css" href="{% static '/static/base.css' %}">
<link rel="stylesheet" type="text/css" href="{% static '/static/headers.css '%}">
<title>Home</title>
</head>
<body>
<div id='header-outer'>
<div id='header-inside'>
<h1>Home</h1>
<span id='nav'>
<a href="" class='current'>Home</a>
<a href="">About us</a>
</span>
</div>
</div>
<div id='after-header'>
<div id='after-header-inside'>
<h2>Hello!</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</div>
</div>
<footer>
<p>Copyright 2020 © Dante</p>
</footer>
</body>
</html>```
% static % refers to the static path, so you need to change your path I believe.
guys how can i align these input
do you mean getting the input-bar at the bottom?
yep
that's a simple google search
@thin dome asked before to show where you are storing your static files
The folders you created
@mystic wyvern if anything show the CSS snipet
i'm bad for frontend, ok guys, i will search on google
Show your CSS
Hi, how can i add the ability to log in with a microsoft or psn profile on my site? Iβm using Django
Are there api for do this? Or i canβt?
Look into Oath2 @clever hedge
This isn't Django but it is Python using Oath to login you could learn from it
@clever hedge
idk about this but i think if u want to log in with google you need to be verified or somethin
thanks
Is there any method for sending a verification email to new register user in flask
And if that is the case, is there any free web server that I can use to do it?
why are my templates and static css files being detected from another app
What do you mean? @modest scaffold
@topaz widget ```
app1/
templates/
base.html
app2/
templates/
base.html
this is my structure kind of
Flask? Django?
oh right sry django
views.py -> app2
def homePage(request):
return render(request, 'base.html')
it is rendering the base.html of app1 and not app2
Well, I don't know why you would have base.html in both apps. You shouldn't even have a templates folder unless you've created it within the app.
i have created the templates folder within the app
thats what my structure shows above
Well, typically when you invoke the render function, you also have to specify the app before the template name: (e.g. render(request, 'app1/base.html))
right
But your folder structure doesn't even look right
wdym
It should be: app1/templates/app1/base.html If you are looking at it from the top-level directory.
ohhhhh thats why people do it like that
i always just ignored that and just put the templates directly into the the templates folder
Or maybe rather:
app1/
templates/
app1/
base.html
app2/
templates/
app2/
whatever.html
ok well then whats the point of having templates in each app
you could just have one templates folder in the main "app"
But you also need appname/base.html in the render function.
app/
templates/
app1/
base.html
app2/
base.htlm
Just do it the conventional way and avoid problems.
well thx for the help π
@modest scaffold There isn't a "set" way to do it, it's whatever you prefer. Here are two examples:
https://learndjango.com/tutorials/template-structure
One where you specify the templates folder within each app, or where you specify the folder in the root project directory. I prefer the second option, but it's just preference at the end of the day. Imo the less folders (as long as you keep sense in the structure) the better
thanks nut
@mystic wyvern btw if you're still stuck how to move that input to the bottom and couldn't find it via google:
.div-container-of-your-input{
position: absolute;
bottom: 0 // this is the margin from the bottom of the parent
}```
class Calculator:
def __init__(self, a, b):
self.number1 = int(a)
self.number2 = int(b)
def seta(self):
a = self.number1
def setb(self):
b = self.number2
def add(self):
return self.number1+self.number2
def subtract(self):
return self.number1 - self.number2
def multiply(self):
return self.number1 * self.number2
def divide(self):
return self.number1 / self.number2
def main():
CalcObj = Calculator(1,2)
CalcObj.seta(a)
CalcObj.setb(b)
print(CalcObj.add())
print(CalcObj.subtract())
print(CalcObj.multiply())
print(CalcObj.divide())
main()
what am I doing wrong here?
CalcObj.seta(a)
NameError: name 'a' is not defined
someone help π¦
@native tide
@sly echo youre passing in a to seta() but a is undefined
CalcObj.seta(a) what is a?
a should be 1 it is a number
a and be are two random numbers
No need to ping me
b*
@sly echo you should learn how variable scope works
@sly echo in the scope of main() a is not defined
I see
I am very confused about the instance variables and class variables.
here main is a function and not a method, right?
and what can I do now to fix this
define a in main
This is not an academic work. I have started coding and learning it
honestly your whole class is a bit off
now this error
seta() takes 1 positional argument but 2 were given
b = self.number2``` this sets a new variable `b` to whatever `self.number2` is, and then immediately garbage collects `b` (I think)
it's doing nothing
class Calculator:
def __init__(self, a, b):
self.number1 = int(a)
self.number2 = int(b)
def add(self):
return self.number1+self.number2
def subtract(self):
return self.number1 - self.number2
def multiply(self):
return self.number1 * self.number2
def divide(self):
return self.number1 / self.number2
def main():
CalcObj = Calculator(1,2)
a=1
b=2
CalcObj.seta(a)
CalcObj.setb(b)
print(CalcObj.add())
print(CalcObj.subtract())
print(CalcObj.multiply())
print(CalcObj.divide())
main()
I have written this now but 'Calculator' object has no attribute 'seta'
seta must be a mutator in the class?
you have no seta method
well it is a random question I found on the internet to practice code π¦
Wait, let me show you
Write a Python class βCalculatorβ which will accept two numbers as arguments, then make four methods by using which we can add them, subtract them, multiply them together, or divide them on request. Your main program is given below.
class Calculator:
"""class implements here"""
def main():
CalcObj = Calculator()
CalcObj.seta(a)
CalcObj.setb(b)
print(CalcObj.add())
print(CalcObj.subtract())
print(CalcObj.multiply())
print(CalcObj.divide())
main()
so the driver program had this seta
I can write basic classes though but.....
And since I am a self learner
I am still so confused about mutatos, accessors, instance variables and class variables
Can you give me a little brief on that as well?
Would be appreciated, thanks!
you are on the right track
but you should have an answer for what every function is doing
you passed in your 2 numbers on runtime
so having a set function for them makes sense, but seems unnecessary
so what should I do here now?
how can I fix my code?
Can you help me with the fixing?
I am dead rn
I'm not gonna give you the answers, sorry
but I will say class Calculator: def __init__(self, a, b): self.number1 = int(a) self.number2 = int(b) def add(self): return self.number1+self.number2 def subtract(self): return self.number1 - self.number2 def multiply(self): return self.number1 * self.number2 def divide(self): return self.number1 / self.number2 seems to do what you want
each of these defs are a method, learn what each one does
I understand that. This is the code I wrote myself
But I am confused about the seta part in the driver program
okay, what can I answer about it?
you don't need main
python is built to not need that
it's just a way to keep track of stuff for you
Exactly
I never wanted the main()
But the question has that main() already in it and we need to complete the code
main() is just a function youre writing, separate from your class
and youre doing stuff in that function
then when your program runs, it's calling main() at the very end
so I must write a seta method in the class?
well again, what is the purpose of seta?
Exactly
What is the purpose??
I have the same question
what does def __init__(self, a, b): self.number1 = int(a) self.number2 = int(b) do?
a and b are 2 numbers passed as arguments in the class
it is a constructor
we need add subtract multiply and divide
without the seta and setb, the code is working just fine at my end
this is a pretty simple question, can you answer it?
what happens to a and b in the constructor?
assigned?
they are assigned to new variables yes
self.number1
and self.number2
so now you can call the add/muliplty/divide methods
but what if you wanted to change the numbers?
yes, it has to be
because it references self.something
it's hard to explain how classes work, you kind of just understand them more as you work on them
So I will write a method
def seta(self):
return a ?
think about the self variable
it's a way to reference the class youre working with
you don't want to do return here
how about
def seta(self, a):
return self.seta = a ?
happy to help
def seta(self, seta):
self.a=seta
def set_a(self, value):
self.a = value
Just asking, have you seen Dr. Strange?
this is what you want, and no I havent
Sir
I need to ask one more thing?
How can I become a Python Pro?
How many hours would I typically need?
How can I come from my rank to your rank?
I need to ask a question about these academic kinda questions
why are the basic work kinda tasks easy but these exercise questions tough?
you don't usually need a class to do simple work tasks
but when you write a big application, classes make things a lot easier to work with
it's all about object oriented programming
Whenever I see YT videos, it seems so simple and I code too
But when it comes to college books, omg!
just keep coding and don't doubt yourself
thanks sir!
no problem
I need more help
@sly echo in general you should not tag specific people for help
Sorry, thanks
also, this is a channel for web dev in Python. you should probably open a help channel #βο½how-to-get-help
does anyone know how to use django
What's your question @dry bridge ?
im having trouble with this line```py
@app.route("/login", methods=["POST", "GET"])
def login():
if request.method == "POST":
session.permanent = True
user = request.form["nm"]
session["user"] = user
found_user = users.query.filter_by(name=user).first()
if found_user:
session["email"] = found_user.email
else:
usr = users(user, "")
db.session.add(usr)
db.session.commit()
flash("Login Successful.")
return redirect(url_for("user"))
else:
if "user" in session:
flash("Already Logged In.")
return redirect(url_for("user"))
return render_template("login.html")```
like idk wtf im doing wrong
@ me if u see an issue to where i cant get ppl in db
show me what youve tried
ive tried down with app.run and under the if statement
not app.run fuck am i saying
yk
just look where youre doing the query lol
i put it with the query
you cant query from the users, you query from the db
db.session.query.filter_by(name=user).first() probably
oh wait
``` maybe?
ill try both
I havent done sqlalchemy in a while
shits aids
are you using flask-mysqlalchemy or whatever
can you show me the users function
this ?
originally you had found_user = users.query.filter_by(name=user).first()
yea
what was users referencing
the table?
you have overridden your table with the users endpoint
because theyre the same name
where
def users
and class users
so python picks the 2nd one
hence you get a function error when it expects a table object
DJango, in html, with form instead of user inputting, is there a way for me to input a preset number beforehand?
hello hello, I have an issue with jinja - I'm trying to use an if statement in a html class but it doesn't seem to be evaluated at all?
it is an svg class so that might be the issue?
<a class='menu-custom-items dashboard {% if request.url_rule.endpoint == "admin" %}is-active{% endif %}' href='/admin'>
<span class="icon">
<svg version="1.1" width="16" height="16" viewBox="0 0 16 16" class='dashboard-icon {% if request.url_rule.endpoint == "staff" %}is-active{% endif %}' aria-hidden="true"><path fill-rule="evenodd" fill="#999999" d="M1 2.75A.75.75 0 011.75 2h12.5a.75.75 0 110 1.5H1.75A.75.75 0 011 2.75zm0 5A.75.75 0 011.75 7h12.5a.75.75 0 110 1.5H1.75A.75.75 0 011 7.75zM1.75 12a.75.75 0 100 1.5h12.5a.75.75 0 100-1.5H1.75z"></path></svg>
</span>
<span class="text">Dashboard</span>
</a>
fwiw, the same exact evaluation in the a class works perfectly
what is the final html that it responds with
ahhhh wait
and are you saying that the if works in the a tag but not the svg tag?
Yes, my mistake was I didn't actually have the exact same in both the svg tag and the a tag π€¦ sorry for the dumb question haha
Maybe make the connection in your app's __init__.py?
hey guys, I needed to learn javascript for my flask applications but what d'yall think about this?
Brython
ping me
@native tide Brython and similar things are not really production ready, it's better to use javascript
anyone here uses GUI?
there is error when i upload certain images
idk what this even mean, do tell if anyone knows
@native tide use / instead of \ or use a raw string
what happened was that \ is an escape character
which means that for example \n is a newline
Man one more question , is there any way like I change the image in the middle of program
Open('path to different image')
I never actually used tkinter, so I do not know. You may want to ask in #user-interfaces instead
Ok thanks man π₯π₯
@app.route('/change-username', methods=["POST"])
def change_username():
data = request.form
user = session['user']['username']
if data.get('newUsername', None):
if api.changeUsername(user, data['newUsername']):
del session['user']['username']
session['user']['username'] = data['newUsername']
session['user']['data']['username'] = data['newUsername']
# print(dict(session))
return jsonify({
"status": True,
"msg": f"changed username from ' {user} ' to ' {data['newUsername']} '"
})
return jsonify({
"error": "something went wrong !"
})
the session values doesn't change
@native tide why delete the session['user']['username'] if you are going to assign a value to it in the next line?
Yeas
oh, thanks for reply
ok
ok
i have a html,css files then i had made a button,if i click on it it should go to another html file how to do it???[in django]
You can redirect to a different url with an anchor tag <a href='the url you want to redirect to> Text </a> within your button, then just make sure the href's url has a view which then renders the new html page.
ok i had but its now my html file for just 0.1 sec and returning to home page @native tide
You'll have to show some code
does css selectorp+a selects first sibling or first inside? or first children?
i tried without using it, but added it later and forgot to remove it
any code which is relevant...
# Good
user__username__contains="name"
# Bad, doesn't know which attribute to lookup
user__contains="name"
why would you use the MEDIA_URL="/media/" only in development and not in production?
is it insecure or ineffective or sth else?
(I have a website where the user can upload files)
hey i have a little prob:```Internal Server Error: /
Traceback (most recent call last):
File "/home/pi/.local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/home/pi/.local/lib/python3.7/site-packages/django/core/handlers/base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/pi/tyneris/backoffice/views.py", line 10, in home
return render(request, 'index.html', context)
File "/home/pi/.local/lib/python3.7/site-packages/django/shortcuts.py", line 19, in render
content = loader.render_to_string(template_name, context, request, using=using)
File "/home/pi/.local/lib/python3.7/site-packages/django/template/loader.py", line 62, in render_to_string
return template.render(context, request)
File "/home/pi/.local/lib/python3.7/site-packages/django/template/backends/django.py", line 61, in render
return self.template.render(context)
File "/home/pi/.local/lib/python3.7/site-packages/django/template/base.py", line 168, in render
with context.bind_template(self):
File "/usr/lib/python3.7/contextlib.py", line 112, in enter
return next(self.gen)
File "/home/pi/.local/lib/python3.7/site-packages/django/template/context.py", line 244, in bind_template
updates.update(processor(self.request))
TypeError: init() missing 1 required positional argument: 'app_module'
witch django
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'bulma',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'tyneris.urls'
TEMPLATE_DIR=os.path.join(BASE_DIR,'templates')
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'backoffice/templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'backoffice.apps.BackofficeConfig',
],
},
},
]
WSGI_APPLICATION = 'tyneris.wsgi.application'```
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def home(request):
context = {}
return render(request, 'index.html', context)```
when this occur?
yes
"""tyneris URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.urls import path
from backoffice import views
urlpatterns = [
path('', views.home, name='home')
]```
from backoffice.views import home
from django.urls import path
from backoffice.views import home
urlpatterns = [
path('', home, name='home')
]```
File "/home/pi/.local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/home/pi/.local/lib/python3.7/site-packages/django/core/handlers/base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/pi/tyneris/backoffice/views.py", line 13, in home
return render(request, 'index.html', context)
File "/home/pi/.local/lib/python3.7/site-packages/django/shortcuts.py", line 19, in render
content = loader.render_to_string(template_name, context, request, using=using)
File "/home/pi/.local/lib/python3.7/site-packages/django/template/loader.py", line 62, in render_to_string
return template.render(context, request)
File "/home/pi/.local/lib/python3.7/site-packages/django/template/backends/django.py", line 61, in render
return self.template.render(context)
File "/home/pi/.local/lib/python3.7/site-packages/django/template/base.py", line 168, in render
with context.bind_template(self):
File "/usr/lib/python3.7/contextlib.py", line 112, in __enter__
return next(self.gen)
File "/home/pi/.local/lib/python3.7/site-packages/django/template/context.py", line 244, in bind_template
updates.update(processor(self.request))
TypeError: __init__() missing 1 required positional argument: 'app_module'
[29/Nov/2020 19:12:19] "GET / HTTP/1.1" 500 85733
no lol
November 29, 2020 - 20:01:19
Django version 3.1.3, using settings 'tyneris.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
Internal Server Error: /
Traceback (most recent call last):
File "/home/pi/.local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/home/pi/.local/lib/python3.7/site-packages/django/core/handlers/base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/pi/tyneris/backoffice/views.py", line 13, in home
return render(request, 'index.html')
File "/home/pi/.local/lib/python3.7/site-packages/django/shortcuts.py", line 19, in render
content = loader.render_to_string(template_name, context, request, using=using)
File "/home/pi/.local/lib/python3.7/site-packages/django/template/loader.py", line 62, in render_to_string
return template.render(context, request)
File "/home/pi/.local/lib/python3.7/site-packages/django/template/backends/django.py", line 61, in render
return self.template.render(context)
File "/home/pi/.local/lib/python3.7/site-packages/django/template/base.py", line 168, in render
with context.bind_template(self):
File "/usr/lib/python3.7/contextlib.py", line 112, in __enter__
return next(self.gen)
File "/home/pi/.local/lib/python3.7/site-packages/django/template/context.py", line 244, in bind_template
updates.update(processor(self.request))
TypeError: __init__() missing 1 required positional argument: 'app_module'
[29/Nov/2020 20:01:24] "GET / HTTP/1.1" 500 85719
@halcyon lion there is the same error
@open owl You can convert serialize your list into a JSON string, then I think that you can save your list within the CharField or TextField. Something like json.dumps(your_list) should be able to do that...
@woeful atlas can you show us your template, are you calling __init__ anywhere too?
uhhh, what model?
<!DOCTYPE html>
<html>
<head>
<title>Bibliothèque locale</title>
</head>
<body>
<p>coucou</p>
</body>
</html>
Ok and what is the view?
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def home(request):
context = {
}
return render(request, 'index.html')```
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
hmm strange
is your index.html in your templates directory?
and can you show urls.py
Ah I see urls.py above, btw the way he done it was fine too.
@woeful atlas did you register you app in settings.py?
In INSTALLED_APPS
uh what app?
the one you created π
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'bulma',
]```
from django.urls import path
from backoffice.views import home
urlpatterns = [
path('', home, name='home')
]
You're importing from backoffice.views right? So you made backoffice app?
oh no
I'm confused on your response... can you show us a screenshot of your folders?
yeah u need to add backoffice in the installed apps
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'bulma',
'backoffice'
]
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'bulma',
'backoffice',
]```
When you make an app you have to include it in INSTALLED_APPS
remove the comma at the end of backoffice, that's not a valid python list
its valid
how come?
i always put the comma in the end so i dont forget to do so next time π
oh okay, thanks
same with the context π
oh no
also correct me if i'm wrong, but doesn't the templates folder have to be in the same directory as manage.py (unless you change the route)?
not really
from the start of the creation of the site
the convention is to have a templates dir and the name of the app dir inside
like in his case templates/backoffice/index.html should be ok
i have launched manage.py
when he's specifying the template in the view, he has to provide the right path then
because just specifying index.html assumes that the templates folder is in the root directory
right?
he needs to do startapp first π
@woeful atlas watch this 15 mins video https://www.youtube.com/watch?v=UmljXZIypDc
In this Python Django Tutorial, we will be learning how to get started using the Django framework. We will install the necessary packages and get a basic application running in our browser. Let's get started...
The code for this series can be found at:
https://github.com/CoreyMSchafer/code_snippets/tree/master/Django_Blog
Flask Tutorials to cr...
the guy explains everything in a really detailed way
ok i'll see even if i'm french
Does anyone know how to customize and generate similar message like this
Using flask_wtf library
I know it can be done with validator
But is there anyone I can do the same within my function?
how do you guys handle time zone conversion from your db
like, currently my timestamps are being logged under UTC
I read that mysql expects the conversion to be handled at application level
is this true?
there is this module pytz that does timezone stuff so google it
this is way above my level of expertise π
thank you
@karmic egret You can add error messages to form.field.errors
Hello everyone, Can anyone help me with creating a searchable dropdown using flask-wtf forms. I have attached my code for some context.
I have a dropdown with a long list of entries, and I want to be able to search the entries. I find solutions online that are not implemented using flask-wtf.
appreciate any help
why not just store it as a unix epoch, and have the clients interpret it.
hello, friends. I have a question regarding OAuth2 and using it to authenticate a user.
So I have a django app that is using OAuth2 to get a user's info and save it into the account they are creating on my django app.
However I have run into something that seems like a massive security vulnerability. If authenticating with Discord API's OAuth2, after logging in and agreeing, discord appears to send a POST request to the redirect url containing the user data.
This would mean any person could make a post request to that url and spoof a payload, meaning that anyone could put my user id into the payload and then they would own my credentials on that website. I assume this is prevented by use of the "code" in the request, but I really do not understand well enough how this works.
Could anyone reassure me that this is secure? Maybe point me in the direction of some good resources on this?
@acoustic oyster it certainly shouldnt be sending a post request and certainly shouldnt be giving you a url payload with the userid
it works via you redirect them to discord
they authenticate with discord
discord redirects to the redirect uri you gave them
with a url query with a short lived token
that short lived token then allows you to send a POST request to Discord that then gives you back the user info like id etc...
ok, I see. That clears a lot up, ty.
I was misunderstanding exactly how the redirect works then. As well as the token.
it does seem like my implementation would allow someone to bypass the discord auth entirely though by sending their own payload to that url, I am not sure how that is circumvented though.
the payload is a randomly generated string
you cant just make a random token up
if you do get given a invalid token and you send a POST request to discord for the info with the spoofed token discord will just say its invalid
ok, I can see that django gave a forbidden error due to csrf verification failing if I try to spoof data there, so that is good.
I was worried about users spoofing data to MY site, not to the discord api.
But I think you have cleared everything up, so tyvm
np
is this still a good sdk for using oauth2?
https://github.com/requests/requests-oauthlib
im new to oauth2, so i just want to know if this passes the sniff test lol
anyone know how to overide the clean method in django when using the createview class
how come im getting the invalid response twice? it should validate after it realizes that theres at least one uppercase but its not doing so
for (var i = 0; i < password.length; i++) {
var charCode = password.charCodeAt(i);
if (charCode>= 65 && charCode <= 90) {
console.log("Great! Your password is valid.");
} else {
console.log("Invalid: Password must contain at least one uppercase letter.");
}
}```
Can u
```js
```
That plz
done sorry
so im inputting a password, for ex abcDefgh
since it shows that it has a uppercase letter, it should validate and send just the response "Great! your password is valid"
However in my console, it sends both the first message and second message
Yeah
But check how many times your msg are send
3 times then 1 time then 4 times
It matches your password construction : 3 lowercases then 1 uppercase then 4 lower
Your loop is printing something for each character
You should declare a variable outside (prolly a bool) that is set to true if you find a uppercase, then after the loop, if the bool is true then you validate
Else, you write "it must have at least 1 uppercase"
@random shadow it should do the trick
@random shadow your way of implement check for uppercase in string is wrong because it loop through every elements in the string, it will print on each element check, you actually got 7 console log in console and only when it goes to index 3 which is D it print out it's valid, other 6 prints just say invalid(because it's not uppercase)
Can you show me a quick example of what you mean? Thank you very much! @native tide
@random shadow here is a simple logic to implement check for uppercase in string
password = 'abcefGgh'
function hasUpperCase(str) {
// lowercase string to check if not the same as the original string
if (str.toLowerCase() != str) {
return 'Great! Your password is valid.';
}
else {
return 'Invalid: Password must contain at least one uppercase letter.';
}
}
console.log(hasUpperCase(password));
ahhhh okok, thank you both!
How can I like change a variable from flask without having to reload page?
Ping with responses
does anyone know a good resource to study to help me make a popup using flask?
RxPy Observables will do this
Sockets, too
can someone hit page page and tell me if the data is loading for the grid?
its soo weird... I justed loaded it on another one of my computers, but when I load it on the host computer the values are there... π¦ its an AWS app
not on my other machine tho.. so maybe its pulling the values from the app being run locally?
Like I want to be able to update a variable and it updates the webpage without u having to reload?
@fiery portal
I can ask question related to Flask here right?
@copper lagoon you can have make a function with Ajax to run on interval and check for that variable. If variable change use Ajax to update it
yes
Use websocket
You can try socket io, its pretty easy to implement @copper lagoon
@rustic pebble ask your question, someone with the knowledge can help you
hello guys, I need some help in #help-pancakes
check with flask?
Guys I am using a widget media in my django project but it is not rendering when I am deploying it on heroku. Can you guys help me ?
I used {{ form.media }} in the head tag of my html file.
It is working locally but not on the server
@copper lagoon with Ajax, its a jquery framework to change your html template without reloading the page
well im using flask
i basicallt would just like to be able to update a variable without really "reloading" the page
You're gonna need JS for that
And with that you'll need an API endpoint for the JS to retrieve/update the information
Also
can i set the flask app timezone somehow
like in a config file
like is this valid
app.config["TIMEZONE"] = 'Est'```
does this mean the webpage was unavailable for some time
Guys I have a question about heroku
lets say I have a project with an owner and a collaborator
but when we activate the bot worker in which account is it hosted ?
is it hosted in the owners account or the collaborator account
and from which account does the bot use its dynos hours
I m planning to build a web application like xender/shareit but it works on the browser itself for file sharing
Initially i plan to make it just connect via LAN only and then go for the second approach of connectivity
Also i know the transfer speed won't be that high
So what all things do i need to know and explore to achieve the given goal
My major queries are what things should i know and what things/topics do i need to lookout for?
hello, i have a little problem with django, i created a template with an html file named "home" but no information is displayed when i want to embed variables but no error displays
source code ```
<!DOCTYPE html>
<html>
<head>
<title>home</title>
</head>
<body>
</body>
</html>
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
posts = [
{
'author': 'CoreyMS',
'title': 'Blog Post 1',
'content': 'First post content',
'date_posted': 'August 27, 2018'
},
{
'author': 'Jane Doe',
'title': 'Blog Post 2',
'content': 'Second post content',
'date_posted': 'August 28, 2018'
}
]
def home(request):
context = {
'posts': posts
}
return render(request, 'home.html', context)
def about(request):
return HttpResponse(posts[0])```
html code home.html
<html>
<head>
<title>home</title>
</head>
<body>
{% for post in post %}
<h1>{{ post.title }}</h1>
<p>By {{ post.author }} on {{ post.date_posted }}</p>
<p>{{ post.content }}</p>
{% endfor %}
</body>
</html>
but if i add code in home.html
<html>
<head>
<title>home</title>
</head>
<body>
<h1>test</h1>
{% for post in post %}
<h1>{{ post.title }}</h1>
<p>By {{ post.author }} on {{ post.date_posted }}</p>
<p>{{ post.content }}</p>
{% endfor %}
</body>
</html>
its good
i have add s in post
why hello there
Spamming in all channels
!tempban 632892966880542740 7d Spamming across several channels is not acceptable.
:incoming_envelope: :ok_hand: applied ban to @tall dust until 2020-12-07 17:40 (6 days and 23 hours).
π
!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.
boys what was this library that allows you to save/upload images locally
was it pillow or something
How do you read images really FAST from an Amazon S3 bucket with a CDN running in the back? On the previous website I've launched, the loading time for the landing page is 924 ms, and 58.85% of the content being loaded are the images. Compressing them with an ANTIALIAS filter an 95% quality is one step closer to the solution. What is there more to do, in order to load images really fast?
@native tide Are your image able to be converted to svgs?
why would you do that? They are abstract images which would be expensive to convert in an .svg format. Also, how would you go about converting dynamically added images to svg?
hi
anyone know how to empty a Model's data ? without using admin
django
@native tide use python manage.py shell
i cannot do that sadly
its on a remote server
maybe i can make an endpoint that removed all data on entering
In django is there a way to hide a negative sign? I want to pass in a negative value but I dont want to show that
@plucky tapir in what? a model?
@native tide yeah do that or have an admin dashboard where you can modify the DB remotely
I guess django-admin already does that...
I'm using class based views, I am using createview to send in an amount, although I want that number to be negative when it goes into the DB
i get
OperationalError at /api/triage/rules/
(1054, "Unknown column 'triage_rule.name' in 'field list'")
i have access to postman too
we changed the model
and didnt remove all data
@plucky tapir so, you're passing a number into a DB (it's negative on the frontend) and you want it to be positive in the DB? Can't you just do abs(num) to convert it to a positive then store it?
@native tide usually adding extra fields isn't a problem if you have a default value set, maybe you can go back a migration, add a default, and it would be okay? What changes were made?
well
im doing frontend and backend with local
i wait until tomorrow, we can prob work it out
issue is we cannot do makemigrations on remote api
hm i can try
do you guys know whats the best way to create a sign up form
is a class based view that inherits view and usercreationform good practice?
Hey so I have a POST api, I am having issue setting the content-type: "application/json"
Is there a way in the api url I could set this?
Can somebody tell me, why in this code
async def solve_captcha(response: Response, captcha: Captcha, options: List[int], key: str, id: str,
db: Session = Depends(get_db)):
captcha and options are considered request body parameters
and key and id are considered query string parameters?
fastapi
@keen kettle that's a header, you specify that as a header within the POST request TO your api...
5. Do not provide or request help on projects that may break laws, breach terms of services, be considered malicious or inappropriate. Do not help with ongoing exams. Do not provide or request solutions for graded assignments, although general guidance is okay.
I might of miss read that
Thought you were trying to auto solve captchas rather than make them
Mb, what happens when you're tried π€£
content-type is not available for this function :(
How would I go about passing the body via the url in query parameters?
Example of this body I need:
{"filter":{"dataRange": "ALL"}, "sort":{"property": "date"}}
@keen kettle you can't
You need to understand that url queries are completely seperate from headers, body, methods, protocols etc...
Hello there, in Flask Appbuildder does someone knows how to trigger "something" after the form submission ?
:incoming_envelope: :ok_hand: applied mute to @native tide until 2020-12-01 02:19 (9 minutes and 58 seconds) (reason: duplicates rule: sent 4 duplicated messages in 10s).
No.
Reread our #rules.
!pban 715899940605526107 No, you can't hire someone here. You've been told many, many times before that you can't. It seems that you don't want to listen.
:incoming_envelope: :ok_hand: applied ban to @viscid dome permanently.
Hi, so I have a celery application which I have correctly initialized by using redis with ssl. My celery-redis app is also tied with a flask app, so I am launching the flask app through the terminal by doing python app.py and then I try to launch celery by typing in celery -A tasks.celery worker -l info
Which doesn't seem to be working, it tries to connect to an ampq server instead of the redis one
tasks.py
import os
import time
from celery import Celery
CELERY_BROKER_URL = os.environ.get('REDIS_URL'),
CELERY_RESULT_BACKEND = os.environ.get('REDIS_URL')
celery = Celery('tasks', broker_use_ssl=CELERY_BROKER_URL, redis_backend_use_ssl=CELERY_RESULT_BACKEND)
@celery.task(name='tasks.add')
def add(x: int, y: int) -> int:
time.sleep(5)
return x + y
worker.py
import os
from celery import Celery
CELERY_BROKER_URL = os.environ.get('REDIS_URL')
CELERY_RESULT_BACKEND = os.environ.get('REDIS_URL')
celery = Celery('tasks', broker_use_ssl=CELERY_BROKER_URL, redis_backend_use_ssl=CELERY_RESULT_BACKEND)
does selenium module has webdriver class only
Hi, I need help with web app development. I am developing an app with DRF and React. In frontend, I have a form to add client information. A client can have multiple locations. I'll attach the Client form and Location form so that you will have a better understanding of what I am trying to do. I am beginner to this whole thing. I am having trouble figuring out how to write model, serializer and view to achieve what I mentioned above.
after pressing Add button in location a popup with location form comes. How do I relate Location model and Client model? I'm using PostgreSQL, if that helps.
Anyone using django ?
Yup
I am using a widget media in my django project but it is not rendering when I am deploying it on heroku. I have used {{ form.media }} in the head tag of my html file. It is working locally but not on the server. Can you help me ?
I have used py manage.py collectstatic so that all the static files will be in the main static directory. And now all the static files are in the directory but still heroku somehow doesn't manage to render those files.
@fresh frigate it should work on production env after you collect static, you can look at heroku documents for more information https://devcenter.heroku.com/articles/django-assets.
you need to know if your collectstatic failed during the build, you can see what it output with heroku config:set DEBUG_COLLECTSTATIC=1
also from this article https://vonkunesnewton.medium.com/understanding-static-files-in-django-heroku-1b8d2f003977
STATIC_URL and STATIC_ROOT are actually overwritten by heroku to STATIC_URL = '/static/' and STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles'). Even if you have a different STATIC_ROOT in your settings if you were to run heroku run python manage.py collectstatic, they will use staticfiles as the STATIC_ROOT.
Wait
That doesn't look right..
Which version of django?
Because they changed it so import os doesn't work anymore
I mean, it does..
But if you're writing it the old way and you're on 3.1, it's not going to work right β since django is using ``import path`
so now I think you have to do
STATIC_DIRS = { path, ('folder/subfolder') ]
hmm i think flask is easier for begginers then danjao
uh hi how do you integrate front code and back code together to make a webpage?
i've heard of flask and django but i dont understand what purpose they serve
just ask.
okay, so...
pages are basically made of HTML and CSS.
Hey @twin sable!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
β’ If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
β’ If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
I am trying to deploy Django with Celery, Celery-beat, Redis, Postgresql, Nginx, Gunicorn Dockerized on Heroku using container registry. After building the image, pushing, and release to Heroku, the static files are not being served by Nginx, and the Redis isn't communicating with celery, I don't know if the celery is working either.
the backend takes a route (like a URL), fetches the relevant HTML, and sends it back to the user.
so, from the perspective of a backend framework like Django/Flask...
what they do is connect routes to Python functions.
This is my Dockerfile
# pull official base image
FROM python:3.8.3-alpine as builder
# set work directory
WORKDIR /usr/src/app
# set environment variables
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1
# install psycopg2 dependencies
RUN apk update \
&& apk add postgresql-dev gcc python3-dev musl-dev
RUN apk add zlib libjpeg-turbo-dev libpng-dev \
freetype-dev lcms2-dev libwebp-dev \
harfbuzz-dev fribidi-dev tcl-dev tk-dev
# lint
RUN pip install --upgrade pip
RUN pip install flake8
COPY . .
# install dependencies
COPY ./requirements.txt .
RUN pip wheel --no-cache-dir --no-deps --wheel-dir /usr/src/app/wheels -r requirements.txt
# pull official base image
FROM python:3.8.3-alpine
# create directory for the app user
RUN mkdir -p /home/app
# create the app user
RUN addgroup -S app && adduser -S app -G app
# create the appropriate directories
ENV HOME=/home/app
ENV APP_HOME=/home/app/web
RUN mkdir $APP_HOME
RUN mkdir $APP_HOME/static
RUN mkdir $APP_HOME/media
WORKDIR $APP_HOME
# install dependencies
RUN apk update && apk add libpq
RUN apk add zlib libjpeg-turbo-dev libpng-dev \
freetype-dev lcms2-dev libwebp-dev \
harfbuzz-dev fribidi-dev tcl-dev tk-dev
COPY --from=builder /usr/src/app/wheels /wheels
COPY --from=builder /usr/src/app/requirements.txt .
RUN pip install --no-cache /wheels/*
# copy entrypoint.sh
COPY ./entrypoint.sh $APP_HOME
# copy project
COPY . $APP_HOME
# chown all the files to the app user
RUN chown -R app:app $APP_HOME
# change to the app user
USER app
# run entrypoint.prod.sh
ENTRYPOINT ["/home/app/web/entrypoint.prod.sh"]
CMD gunicorn my_proj.wsgi:application --bind 0.0.0.0:$PORT ```
so when the user visits a route, the framework calls a function. that function returns some sort of result, and that result is sent back to the user.
that result can be a full page made of HTTP and CSS
that's one way to do things
but there are also other types of websites called SPAs (single page applications)
basically, there's a lot of JavaScript that runs on the user's computer (called the frontend).
and that frontend makes calls to the backend, just like the other type of website
except that instead of getting full pages, it just gets responses containing data (usually JSON)
and the frontend is then in charge of turning that data into something that will be displayed to the user.
that's a lot of stuff π₯΄
and, unfortunately, it is also quite specialised.
okay, there are several problems
I'm not a nginx person, so I can't help you with that
but what do you mean when you say Celery isn't talking to Redis
like the Redis logs don't show a connection
and the Celery logs say it can't find the broker?
The Redis doesn't show a connection
I can't tell if the Celery would work since the message broker isn't working
@vestal hound thx a lot π i will try
I don't know if there is another setting for deployment, everything works fine in development
hm.
are your URLs correct?
can you try
This is my docker-compose file
services:
web:
build:
context: .
dockerfile : Dockerfile
container_name: django
command: gunicorn my_proj.wsgi:application --bind 0.0.0.0:8000
volumes:
- static_volume:/home/app/web/static
- media_volume:/home/app/web/media
expose:
- 8000
depends_on:
- pgdb
- redis
celery-worker:
build: .
command: celery -A my_proj worker -l INFO
volumes:
- .:/usr/src/app
environment:
- DEBUG=1
- DJANGO_ALLOWED_HOSTS=['localhost', '127.0.0.1', 'app_name.herokuapp.com']
- CELERY_BROKER=redis://redis:6379/0
- CELERY_BACKEND=redis://redis:6379/0
depends_on:
- web
- redis
celery-beat:
build: .
command: celery -A my_proj beat -l INFO --scheduler django_celery_beat.schedulers:DatabaseScheduler
volumes:
- .:/usr/src/app
environment:
- DEBUG=1
- DJANGO_ALLOWED_HOSTS=['localhost', '127.0.0.1', 'app_name.herokuapp.com']
- CELERY_BROKER=redis://redis:6379/0
- CELERY_BACKEND=redis://redis:6379/0
depends_on:
- web
- redis
- celery-worker
pgdb:
image: postgres
container_name: pgdb
environment:
- POSTGRES_DB=databasename
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=password
volumes:
- pgdata:/var/lib/postgresql/data/ ```
image: "redis:alpine"
nginx:
build: ./nginx
volumes:
- static_volume:/home/app/web/static
- media_volume:/home/app/web/media
ports:
- 1337:80
depends_on:
- web
volumes:
pgdata:
static_volume:
media_volume: ```
using Heroku Redis service
there should be a way to connect
from local
there are a lot of moving part
s
this is p hard to debug
especially since you have multiple problems
Okay
This is the settings i used:
CELERY_BROKER_URL = os.environ.get("CELERY_BROKER", "redis://redis:6379/0")
CELERY_RESULT_BACKEND = os.environ.get("CELERY_BROKER", "redis://redis:6379/0")```
is this your local or what
it is my local
yeah so connect to the Heroku redis
I have done so
anyone knows how i can get the hello text a bit higher where the red mark is?
<img style = "height: 45px;width: 45px; float: left; margin-top: 20px; border-radius: 50%; margin-left: 15px", src = "https://cdn.discordapp.com/avatars/700026158904901740/b3a97fda8bffbcc68ccb27a5ce495fed.webp?size=1024">
<h3 style="color: #ffffff; margin-top: 21px; text-align: top; margin-left: 11px; float: left; padding-bottom: 0px; font-family: sans-serif">Deity</h3><p style="color: #8f8f8f; float: left; text-align: left; margin-top: 26px; margin-left: 7px; height: 0px; font-family: sans-serif; font-size: 14px">27 Oct 2020 at 11:42 PM</p>
<p style="color: #ffffff; clear: both; text-align: left; font-family: sans-serif; margin-left: 73px; height: 0px; margin-top: -200px;">hello</p><br><hr style="height:1px;border-width:0;color:#2f3136;background-color:#505050">```
this was my code
u can use transform: translate(0%, 100%) or whatever u want
how to add href i having problem?[In Django]
how can I get the value of city_name variable which I get through HTML forms in jinja template
it's not working
@native tide Check out form.validate_on_submit
The form data is not included in request.form
There is no such attribute
what encoding method should i use on html file for most characters to be able to work
i used utf-8 but some characters wont work
You should only use UTF-8
it's better than any other..
ye i figured after googling a bit
how do i handle content security with flask talisman? I have this policy:
csp = {
'default-src': [
"*",
"'unsafe-inline'"
],
'img-src': '*'
}
talisman = Talisman(app, content_security_policy=csp)
But I get this Error:
Refused to load the image 'data:image/png;base64,iVBORw0KGgoAAAANS...fmja+8LMACM4cURIdXaEQAAAABJRU5ErkJggg==' because it violates the following Content Security Policy directive: "img-src *".
I thought 'img-src': '*' would allow B64 images
Hey guys can you provide me the details or correct my approach regarding this operation.
I along with my 2 other Teammates have been assigned a DBMS mini-project. In this project we have to create a web app that should use any sql database for storing data and the app should demonstrate CRUD operations.
we choose Flask for this purpose as Django would be overkill for this. As for the database we are using MySql.
Now I created a database and 5 tables inside it using the MySql Command Line.
How do I take input from the user?
Here is my approach->
First the user will enter it's detail via html form.
now I need to collect user's detail and store it in some variables.
then I need to pass those variables in SQL insert query . As a result the data would get stored in the tables.
Is this approach correct? if yes can you guys tell me how do I implement it of what do I need to implement it in flask?
Is there any other way to do this thing?
is MySQL mandatory?
recently I heard about this but haven't tested it - https://postgres.rest/
pREST - Instant RESTFul APIs for your data, join data across databases, REST services to build powerful modern applications
well there are other options like oracle db but we chose this
oh you said you need to support any SQL engine. Sorry, ignore my above suggestion
guys a little help
what do we call those you know animations in the html page . that when we hover cursor over and it moves
Animations
Transitions and animations
When I run this Flask application logs in console seem to be fine, but I cannot find my webpage by the default url. Error: Not Found
The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.
Any thoughts?

I am working with a remote mySQL database. Sometimes the database is down and simply won't insert any records, so flask returns a 404. if I manually use ctrl+alt+r I can make Chrome do the post request again. How can I do this in flask.
For example if I get a 404 when inserting a record, I want to try the post request again, how can I do that with the form details already submitted?
it's working fine, also I use VSCode which has integrated powershell terminal so I can go to the given address by pressing ctrl+click.
It's working fine for you? Cuz I still struggle with it
maybe I should install some packages
or download vscode or something else
i'll suggest you to download VSCode and make a virtual enviroment and then install flask
alright, I'll try. Thanks, dude.
also inside your if condition write this:
if __name__=='__main__':
app.run(debug=True)
do you guys prefer fastapi, starlette, flask, or aiohttp for backend servers
this will run your flask app in debug mode so every changes you make will be tracked and you can run your flask app by simply typing python your_file_name.py
oh, thanks @hoary marlin
for my mini-project Django would be an overkill so we decided to go for flask.
awesome, why not an async framework though
also I'll suggest you to watch flask tutorials by Cody Schafer on youtube if you are just starting.
as per our project requirements we don't need to fetch some data from an api so we chose flaskπ
Yeah, I saw a couple of his videos. Didn't know that he had Flask tutorials. I'll watch them 100%, thank you very much for your advices. I really appreciate this.
@lone zealot https://www.youtube.com/watch?v=MwZwr5Tvyxo
In this Python Flask Tutorial, we will be learning how to get started using the Flask framework. We will install the necessary packages and get a basic Hello World Application running in our browser. Let's get started...
The code for this series can be found at:
https://github.com/CoreyMSchafer/code_snippets/tree/master/Python/Flask_Blog
Djang...
π
oh wait
Yep
)
lmao
no as in according to framework benchmarks, async frameworks are much faster and its almost a drop-in replacement if you're using fastapi(https://fastapi.tiangolo.com/)
here's another playlist, if you didn't understand from the above one.
@lone zealot
https://youtube.com/playlist?list=PLzMcBGfZo4-n4vJJybUVV3Un_NFS5EOgX
whats up
I installed the vs code and python interpreter, but when I run the exact same piece of code vs code says this:
from flask import Flask
ModuleNotFoundError: No module named 'flask'
also @hoary marlin :
from typing import Optional
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/items/{item_id}")
async def read_item(item_id: int, q: Optional[str] = None):
# await some database call if necessary
return {"item_id": item_id, "q": q}
it is very easy to drop in fastapi which is much faster than flask as it uses async(just put async in the function signature)
python -m pip install flask
run this in cmd
and show output
thats fine
in the same terminal
can you execute
python
and open the cmd interpreter
Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:43:08) [MSC v.1926 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
awesome
ok now execute
from flask import Flask
that one line of python
i just want to see the output from the live terminal
no output and no errors
On my Desktop
Right
ok
there is probably an issue with vscode interpreter setup
go into vscode and hit
ctrl+shift+c
all at once
Maybe it's because I use 64-bit python version, but log says that I habe 32-bit?
32-bit win
hmm...
^^
all at once
within vscode window
does a terminal show up
Yes
Hello does anyone know how to fix 500 internal server error when deploying python application to azure
probably application code error, check the application logs if possible
it executed with Debug mode on
wait was the cmd window an external window
hello guys,
In django when I use objects.get() on my model I get a ManyRelatedManager from my ManyToManyField but how do I get the keys inside ?
also did it work though
where can I check the logs on azure?
i dont know, havent used the cloud provider before
oh alright
@marble gate
go through this once
Oh shit, I have no idea. Maybe I'll just have to reinstall python or smthn. I'll go google again.
okay
i solved the "no module" problem
but the webpage
it's still 404)
I guess I'll just take my time. And thank you very much Bro, for your efforts
are you sure you are requesting the right route?
oh sure no problem
but how come you are calling me Bro ;-; you must call me DudeBro
DudeBro, speaking of routes I'm pretty sure I did them right because at this point I just copy the code from youtube tutorial
In this Python Beginner Tutorial, we will start with the basics of how to install and setup Python for Mac and Windows. We will also take a look at the interactive prompt, as well as creating and running our first script. Let's get started.
Mac Install: 1:25
Windows Install: 5:44
Installs Complete: 8:37
Watch the full Python Beginner Series he...
right
also here, for legit python setup
so that no more ambiguity :)
Yep, thanks. Cya, maybe)
https://github.com/hhhrrrttt222111/fatigue-detector
Detect drowsiness and fatigue during online classes
Made with Flask and OpenCV
star2
Hello
Anyone who knows django?
I need help
Plz dm π
It's very important
It's solution is not on stack overflow
Someone asked that question but that's not answered yet
Ask the question instead of asking to ask
Lolπ
While being offline my blog app is taking forever to load and not rendering the template as expected but when I'm online everything works as it should
This happened from yesterday
When my pc suddenly got off while I was working in shell π
wdym by "offline"? Is it hosted already
No
I mean when my wifi works, django works
And when not,that happens