#web-development
2 messages Β· Page 211 of 1
thanks Man!
Hi,
What is the difference between using django runserver and gunicorn in development?
any django and vue users here?
What happens if you set debug=False?
how are you running it?
hm
flask run?
debug=True basically just updates the server as soon as you make changes in code, and i assume if u set it to False it won't do that, and I am pretty sure the default is set to False
Yeah i was actually doing that, then I tried python app.py then it worked properly
I mean maybe the debug mode prevents changing the port. Not sure, haven't needed to change the port on local instance
Not exactly stealing but you would be able to make requests with victim's cookies attached to it
yeah the correct name is cross site resource forgery, but either way does the same thing
Also this doesn't sound like a csrf attack, csrf doesn't allow for execution of arbitrary Javascript code π€
which is better for web dev, django or flask?
Gunicorn allows multiple workers to serve your pages, taking the load off of one singular instance.
Depends what you want to do.
Django has a lot more included, Flask requires you to install the libraries you want so it's the "light" option.
if you have to ask, start with Flask. It's quicker to learn the basics with Flask and then learn Django next if you need it
Ask questions in a right way https://pythondiscord.com/pages/resources/guides/asking-good-questions/
A guide for how to ask good questions in our community.
And I used both things
Itβs outside the block
inside didnt work either
lemme send its ss
this is where i define the blocks btw
Thereβs no block content there
Hi! I'm trying to upload image, but it doesn't work, I get empty request.FILES. I feel that mistake is obvious, but I'm to dumb to find it.
My form:
class profilepictureForm(ModelForm):
class Meta:
model = User
fields = ('profile_pic', )
Template, probably I'm doing something wrong here:
<form action="" method="post">
{% csrf_token %}
<div class="pos">
{{form}}
<button type="submit">Send</button>
</div>
</form>
// Add row on add button click
$(document).on("click", ".add", function(){
var empty = false;
var input = $(this).parents("tr").find('input[type="text"]');
input.each(function(){
if(!$(this).val()){
$(this).addClass("error");
empty = true;
} else{
$(this).removeClass("error");
}
});
var id = $("#id_hidden").val();
var repair_id = $("#repair_id_hidden").val();
var description = $("#cost_description").val();
var amount = $("#cost_amount").val();
var paid = $("#txtphone").val();
$.post("/add_expense", { id: id, repair_id: repair_id, description: description, amount: amount, paid: paid}, function(data) {
$("#displaymessage").html(data);
$("#displaymessage").show();
});
});```
Following a tutorial that has this code to submit the values from the current row in a post request but I was wondering how does it know to grab the .val() from the current row when multiple rows have the same ID for each td
does clicking the button in the row switch the context to that row?
How could i update a page everytime a post request to the server is recieved? I want to be able to post images and it goes to the client live.
Hello guys... I have a question regarding models in Django. I'm gonna use Django built-in model for Users, but now I got stuck. If I want to create model for user profile to extend built-in Users, where should I put it? Into new separate app or into current app? What should I do when I decide to add new functionality into my project. Should I create a profile model in new app as well?
A websocket is an option
okay.
You can also look at using ajax for a simpler implementation if it's not a lot of changes. If it is, you're probably better off looking at a full front-end framework, a la React, etc.
Hi all, I have been browsing google and youtube looking for an up to date and good answer, but am coming up short. I want to run a simple blog on AWS. I would like to host some jupyter notebooks at some point. Past that, there are no crazy technical requirements. What would be the best Python framework for this? A tutorial of some kind would be hugely helpful.
I'm not sure about hosting jupyter notebooks but if you want to use python for your blog you could use literally any framework
Django, Flask, FastAPI
Django would be the easiest to setup a blog with + there should be apps for that already if you don't want to code the blog yourself
What Doctor said but also, only do this if learning a Python framework is your primary goal. If your goal is just to host a simple blog, there are much easier ways (I like Hugo personally).
Hi
I have a server as in ip address where it will take me to login to discord
but unfortnately after i login
this is what i recieve
Does that make sense?
@serene prawn @golden bone awesome thanks! The primary goal is to learn a framework. I will go with Django.
Hi can someone help me please
Am trying to connect to my web server but it aint working
Yep, django would be a good start
when would I use flask async?
Flask has very limited support for async, why you think that you need to use async? π€
when I'm requesting data to api
I think it's best to use async for that
but since you said it's limited support I won't
I'll let the user suffer for it 
Docs say it would still process the same amount of requests at the same time π€
Because essentially it would create new loop, process your request in async mode and close it
At least if i understand docs correctly
You could use something like FastAPI if you expect a lot of interactions with other services ig
I'm not making an api
@app.route("register")
def register():
request to api
check if exist
wonder if I should connect to my database using an api or just connect to the database directly?
Your api should connect to the database
or just use an api when the codebase is good enough or big enough
I'm thinking of using supabase because it already has api's
ππ»
what's the average time for a solo dev to do full stack on a website that has basic blog site features?
hi, having issues with flask.
i have an error saying werkzeug.routing.BuildError: Could not build url for endpoint 'users.login'. Did you mean 'index' instead?
this originates from a button in a Bulma html file base.html:
<a class="button" href="{{ url_for('users.login') }}">... etc ...</a>
and here is the function for the login.```python
@users_blueprint.route('/login', methods=['GET', 'POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
if not user or not check_password_hash(user.password, form.password.data):
flash('Please check your login details and try again')
return render_template('login.html', form=form)
if pyotp.TOTP(user.pin_key).verify(form.pin.data):
login_user(user)
user.last_logged_in = user.current_logged_in
user.current_logged_in = datetime.now()
db.session.add(user)
db.session.commit()
else:
flash("You have supplied an invalid 2FA token!")
return account()
return render_template('login.html', form=form)
my structure is as follows:
templates >
base.html
app.py
users >
views.py (login function in here)```
when running the website locally everything is fine, but when i run the app on heroku or my cloud server i get the error. upon removing the url_for() lines, the website functions well otherwise
anyone have django projects?
We all here r python web devs
So yeah
Most of us
hello can someone help me? i cant find resource on the internet regarding this one
how to extract a array inside array to compile it in one array example
[[{"dog1": "doggy", "color": "black"}],[{"dog1": "harry", "color": "white"}]]
to
[{"dog1": "doggy", "color": "black"}, {"dog1": "harry", "color": "white"}]
itertools.chain.from_iterable would be the fastest way
import itertools
data = [[{"dog1": "doggy", "color": "black"}], [{"dog1": "harry", "color": "white"}]]
list(itertools.chain.from_iterable(data))
[{'dog1': 'doggy', 'color': 'black'}, {'dog1': 'harry', 'color': 'white'}]
how about how to get it hit the array sir?
i mean
[{'_id': 1, 'name': 'foo', 'score': '1'}, {'_id': 2, 'name': 'food', 'score': '100'}]
and if i have a parameter
"condition" :{"name":["f"],"score":["1","0"]}
it must hit 3 times
- {'_id': 1, 'name': 'foo', 'score': '1'}
- {'_id': 2, 'name': 'food', 'score': '100'}
- {'_id': 2, 'name': 'food', 'score': '100'}
output will be 3
I don't understand what you want to do here π
@sharp wagon
@sharp wagon
@sharp wagon
hello
happy birthday
@sharp wagon
@sharp wagon
@sharp wagon
I need help setting my web host
Please
Am trying to get my code working but it really isnt working
^
Like host ur website?
yes
^
as in code coding of web application is near to end
where are you registering your blueprint?
hello everyone, did someone know the equivalent of os.getlogin in flask, Thanks!
cause it returns the web server attribute
not the user logged
Hii my server keeps giving me errors
app = Flask(__name__)
@app.route("/")
def homepage():
return render_template("index.html", redirect_uri=REDIRECT_URI)
if __name__ == "__main__":
app.run(debug=True)
have you tried reading the error?
REDIRECT_URI variable is not defined but you are using it at the 7 line, at the end of it
where? You did not define REDIRECT_URI anywhere
I can't see in your code
REDIRECT_URI = "bla bla bla"
there is no definition
show me where in your code you have
REDIRECT_URI=something
that's redirect_uri=
i ask for REDIRECT_URI=
?
you are defining only parameters for function
you can't define variable in a function π€¦ββοΈ
@app.route("/")
def homepage():
return render_template("index.html", redirect_uri="/")
Ohh unless its my localhost web server that i have to insert
Ohh ok
Well nvm
Ohh so thats how it is?
hey can anyone help with some flask?(i am new to it so it's propperyl a easy problem to fix)
can some one help me with django?
?
this doent help
Quote from the link:
What Not To Ask
Q: Can I ask a question?
Yes. Always yes. Just ask.
Q: Is anyone here good at Flask / Pygame / PyCharm?
There are two problems with this question:
This kind of question does not manage to pique anyone's interest, so you're less likely to get an answer overall. On the other hand, a question like "Is it possible to get PyCharm to automatically compile SCSS into CSS files" is much more likely to be interesting to someone. Sometimes, the best answers come from someone who does not already know the answer, but who finds the question interesting enough to go search for the answer on your behalf.
When you qualify your question by first asking if someone is good at something, you are filtering out potential answerers. Not only are people bad at judging their own skill at something, but the truth is that even someone who has zero experience with the framework you're having trouble with might still be of excellent help to you.
So instead of asking if someone is good at something, simply ask your question right away.
can someone help me deploy my weather app please
just help me
ive been stuck for 2 days
ill join vc if you want
in my app.py file
in the init function
can someone help me to code payload
what project
let's see the code
i think you just have a mismatch of names, as the error says users.login but your blueprint name is users_blueprint
sent you a dm of the repo
if that was it then I thought it wouldn't be able to run locally
it's only ever produced errors when I've tried to host it
in mine, i have the blueprint names consistent everywhere and works for me both locally and on heroku so i would give that a go first π
your code all looks fine, only thing i can see as issue is blueprints right now
what would I change them to in mine? @summer beacon
anyone?
also I thought users.login would work because the login function is in users/views.py
the thought process makes sense, but it works slightly differently in the jinja templates, its not like importing a python module if that makes sense
i've cloned your repo so let me have a quick look and ill find a solution
thank you, I really appreciate it
been stuck on this for a few days and it's making me pull my hair out π
ahaha no worries, im bored in a lecture so something nice to do lol
ah omg
@wheat verge Where do you want your app to be deployed?
heroku or python anywhere I just want to deploy it
What is your problem exactly?
i just dotn know how to deploy it ive been watching a lot of tutorials but all i get is error
i tried in heroku but im getting this error
im getting this link which I think is not a real addres
this is what i am getting
thank you so much but it is not loading any of my static files....and can you fill me in what is this error
what should i include in my proc file?
Do you set any domain and DNS on your herku
?
i really dont know i am just following tutorials i really need help
when i do this there is the same problem
@atomic ermine I recommend this guide from MDN if you want to learn about how HTTP works: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP
thank you π
guys, should i do template inheritance for my first flask program??
im getting confused trying to string everything together
Hello Guys, we have used python flask for developing the website https://avilpool.xyz/. Frontend is html coded. Need your comments on this.
Crypto Tracker made for investors and creators. In search of next BTC/ETH/BSC, shit coin detection, scam token detection, shitcoin
How big is the template? Is there enough overlap over all pages to make it worth it?
googling "Jinja2 inheritance". Flask uses Jinja2 as templating language
https://jinja.palletsprojects.com/en/3.0.x/templates/
thanks, the website isnt very big, im trying to learn template inheritance, stringing together routes, models and init is... interesting
Can any front end developer please quickly look at the UI of my website on both Mobile and Pc and give me some suggestions on how to improve the UI. Link: https://codewani.pythonanywhere.com
actually u should better ask UI designers ;b
anyway
I think for your rectangle card things would look good a bit of hover animation:
.card {
transition: transform 0.5s;
}
.card:hover {
transform: scale(1.05);
}
and u have messed up width of top level objects
Let me guess, u a using javascript to do that. That's really bad.
Use CSS for that. Using anything else but CSS for responsiveness is a really bad idea π
Remove the javascript animation that does it. That just harms
Sometimes it works, sometimes it wents bad
I'm having a problem on setting my favicon and navbar img in html5 (with Flask)...
I have this '<link rel="icon" type="image/x-icon" href="../images/favicon.ico">' for setting it, but it doesn't get imported.
My folder structure:
website
---images
-----favicon.ico
---templates
------base.html
---main.py
My os.getcwd() is within website, but I still can't access the file...
Root folder for static objects is not from where template is located
But from which static folder path is set in flask settings
https://www.google.com/search?q=flask+static+folder+path
By convention, Flask looks for a folder named static next to your application, and serves the files there at the /static/<path:filename> URL, matching all the files in your static folder and its subdirectories.
Thank you so so much!!! I got it working now 
Why is there no difference between flex: 20 10 30px; and flex: 20 30px;? (css)
Can someone help me with this
app = Flask(__name__)
@app.route("/")
def homepage():
return render_template("index.html", oauth_url="OAUTH_URL")
if __name__ == "__main__":
app.run(debug=True)
Hello
it wont redirect me to the discord login
Hey, I could need help with my hcaptcha integration (no bypass...)...
I use Flask-hCaptcha to integrate it to one page of my Flask website.
Here's what I aim to do:
I want the only thing on the page to be captcha and after it got solved I want to redirect the user to a specific website.
I made an account on hcaptcha and set the values for hcaptcha in the config ('RECAPTCHA_SITE_KEY' & 'RECAPTCHA_SECRET_KEY')
I use this code for rendering:
@app.route('/verify', methods=["GET", "POST"])
def discord():
if request.method == "GET":
return render_template('verify.html')
elif request.method == "POST":
if hcaptcha.verify():
return "You have completed the captcha!"
else:
return "Please complete the captcha"
This is my verify.html:
{% extends 'base.html' %}
{% block title %}Verify{% endblock %}
{% block content %}
<form method="POST">
<label for="text_input">Name</label>
<input type="text" id="text_input" name="text_input" />
<input type="submit" value="Submit" />
{{ hcaptcha }}
</form>
{% endblock %}
My problems:
- The hcaptcha is not showing up
- I can just click on the submit button and get redirected with a success...
I first want to get this captcha to work, so any help would be appreciated ^^
I don't see where you're returning hcaptcha context in the function.
I've not used that library but the function probably needs to tell the template what hcaptcha is, since you're using {{hcaptcha}}.
def hello(name=None):
return render_template('hello.html', name=name)
Yes, I thought so too, but after looking through some other peoples examples and documentation (well... there isn't really any doc) it's not needed
Hmm, maybe the library has something built in then, but if it doesn't then you would need that.
Otherwise, what tells the template what {{hcaptcha}} is?
Hello can someone help me?
Well... For others it seemed to work... I now again integrated it, but it doesn't change anything
Hello guys, i have a problem with my administration panel using django version 2.1, i am not using the latest version because i am doing a specific project, anyways, after creating a table in admin.py βββadmin.site.register(Product)βββ i went to the admin panel to add a product, everything is smooth but when i pressed save it gives me this error: no such table: main.auth_user__old
Iβve been stuck with this problem for a while now can someone please help
Hi #web-development
This question is about web scrapping.
I would like to extract info from an Azure page. But I don't know what to do with Azure authentication :c
Anyhelp, please
I made a custom function but in Rest it doesnt work?
what do you mean it doesn't work
Hello can someone help me please
Why python frameworks (Fastapi) is not suited for production in Windows
Windows licenses are expensive, and microsoft demands constant access to all servers that run windows servers
Windows consumes a lot of server resources even if it is not running anything, which again increases cost to run windows servers
Windows is a hell of unsafe
That makes windows usable only as Desktop thing as development environment as maximum (but linux is better even in this regard, because linux usage is much better when you develop for linux servers)
Windows is best used when it is used.... to develop for windows, applications?
Game development and Desktop app development basically.
and Windows Server makes probably sense to use only when you are system administrator, regulating a techno park out of many PCs with installed Windowses (Not sure for sure though, because certain amount of things can be replaced with linux server even in this case, but some things can not be replaced though, so it depends on tech stack)
But why then liunx severs are prefer more than windows
Can anyone tell me how I can send a canvas image from frontend to backend flask app?
You can convert canvas images to png or jpeg and send it
I told you already, because Linuxes are free in licenses (we pay only for hardware), and because they are more efficient in hardware utilization and more secure.
And because of the above reasons and long time usage, linux already has a lot of production grade software for servers, leaving other oses very much behind.
There are no alternatives. Linux is the only free system
When you told me bro
Can you tell me how to send it via Axios or Ajax
just @stark tartan above your question
You can use form data
Ohh yeh thanks
Linux is devlops π
what is devlops? π
Can you send a link?
Developer + linux
That's a lot of help. Thanks a ton
first time hearing about such abbreviation. and it is too close in letters / pronunciation to another abbreviation that has a very different meaning (DevOps)
Hey I want to filter the name and description with different languages like I also able to search same thing in other languages in Django Rest framework
I did not understand what u wish to achieve. be more precise
You can refer mozila documentation for these
Search the same item like apple π in english if user search or in other languages like ΰ€Έΰ₯ΰ€¬ in hindi (India language)
Like Amazon is doing
Fastapi use async gateway
it sounds like you need Google Translator API
it can recognize currently used language
and translate reliably to any other lang
Okay I will look fwd in that π
can you elaborate please
in desktop view the button is in center
I'll quote one famous man then
im a serving a react app with a flask backend and everything seems to flow smoothly but upon refresh, the browser redirects to the flask api instead of staying on react router, which is the expected behavior. any workarounds for this ?
@app.route('/')
def serve():
return send_from_directory(app.static_folder, 'index.html')
spill the details what you use to serve them
im using this to serve the react app
okay. interesting perversion. let me think π€
usually people try an approach...
serving both things with Nginx
you could have served react at / route
while serving flask strictly at /api route for example
it should work better I think
yes
supposedly yes, but I am not hundred percent sure
I would say with 90% probability
the problem is with refresh
oh yea I forgot
i thought about defining a route in the end that accepts all undefined routes and redirect to the react app with the above function
HTML:-
<section class="bgimage">
<div class="container-fluid">
<div class="row">
<div class='layout-btn'>
<h5>Hero-unit header</h5>
<p><a href="#" class="btn btn-primary btn-large" style="background-color:orangered; width: 8em;">CLICK</a></p>
</div>
</div>
</div>
</section>```
```css
CSS:--
.bgimage {
width:100%;
height:500px;
background: url('bgbi.jpg');
background-repeat: no-repeat;
background-position: center;
background-size:cover;
background-attachment:initial;
margin: auto;
overflow: hidden;
align-items: center;
position: fixed;
top: 50%;
-ms-transform: translateY(-50%);
transform: translateY(-50%);
}
.bgimage h5 {
color:white;
text-shadow:2px 2px #333;
text-align: center;
}
.row{
display: flex;
margin:auto;
position: absolute;
justify-content: center;
overflow: hidden;
top: 50%;
transform:translateY(60%) translateX(146%);
}```
but this will redirect to the home page instead of where the refresh actually took place
nginx should help with 90% chance
you did not give the image so i made as much as I saw it
.bgimage {
background: url('bgbi.jpg');
background-repeat: no-repeat;
background-position: center;
background-size:cover;
background-attachment:initial;
/* centralizing stuff */
width: 100%;
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
.bgimage h5 {
color:white;
text-shadow:2px 2px #333;
text-align: center;
}
.row{
display: flex;
margin:auto;
justify-content: center;
overflow: hidden;
}
deleted some of the mess (but not all of the mess) and placed centeralizer for you
im serving with heroku currently
- feel free to centralize the words too
.layout-btn {
justify-content: center;
align-items: center;
flex-direction: column;
display: flex;
}
perhaps the time to use better way of hosting
that you own more
getting regular VPS for shit and giggles π
the problem is im looking for free stuff
yea i should get some π
google gives free period for a quite long period
ofr a vps ?
i gotta install all dependencies and setup the environment manually right ? π
aws does provide this kind of services i guess
AWS I remember offers 3 months of free usage VPSes in comfortable Lightsale section
and 12 month of IC2, less comfortable being used in GUI, intended for IaC
are vps restricted in some way ?
Google provides trial of 300$ for 6 months i think
or u can do anything on them
this isnt very affordable to someone not doing any serious production yet
300$ credit for free
just to try products
why is it not affordable? it is free π
oh yea i misunderstood what u said i guess
hard to say.
There are two possible limitations
ill definitely take a look, and ill try solving that bug now
- AWS is a bit strict in security, so they have their firewall at least for Lightsale category setup always on from their web site GUI.
so you would need to open ports in GUI
- It could be having some limits for CPU power?
for testing purposes u can surely try it, they give I think 1 CPU power for this period for sure to run 24/7
but anything more than that, not in the free section
u a welcome. Azure could be having possibly some similar big enough offer
AWS / Google/ Azure are big three known providers
they can afford doing it
There are small good providers in addition, but they give only smth like 1-2 months at best of free trials
if u dont mind me asking
what is the difference exactly between these and something like heroku or similar platforms
for deployment
I usually recommend
AWS / Google / Azure / DigitalOcean / Linode / Vultr because they are providing means to have Infrastructure as a code (can be controlled being setup from code)
with usage from VPSes to managed Kuberenetes to Managed databases
while Heroki... did not try a lot, but i guess they provide running App as a service first. Basically VPS is abstracted away by being presetup for you / + scaling of infrastructure
As far as I know DigitalOcean provides hosting applications too, it should be similar experience to Heroku in theory.
Probably other providers have same feature
I just don't try it, because i prefer to worry about my infrastructure on my own
it gives bigger flexibility to control stuff and room for more custom complex infrastructure
well, may be managed app can actually do better in some cases, but if I would have used managed apps services, I would not learn how to wield infrastructure on my own
Which is essential to DevOps related field
I think DOs managed service is more like Vercel, where updating your github repo automatically redploys to DO.
But still abstracting out the setup process, yea.
@inland oak Have you ever manually setup auto-redeploy on DO?
Just with the standard droplets.
Having it setup at work by my own hands
Even better, a month ago upgraded being auto deployed to kubernetes
I would like to learn that process for DO, so I can just stop having to setup new servers from scratch and maybe setup a no-downtime solution in the future.
Gitlab CI is friendly.
Minimalistic beginner solution would be
Gitlab CI + Ansible
With highly recommending adding Docker to it
Optionally adding Terraform or Pulumi for a full pipeline
Gitlab CI watches repository and executes jobs at every commit
Ansible connects remotely to servers and makes initial configuration, installing docker or dependencies to applications if without it. Launches / restarts what is needed
Docker is abstracting away a bunch of tasks you would have been doing by ansible otherwise
Terraform automates clicking cloud provider GUI, to buy necessary servers / naming them / setting up domain settings / optionally load balancers. Getting their IP addresses
Well, no down time solution means using stuff like Kubernetes already ;)
Possible to do without it technically. But k8s offers it out of the box with like almost zero code
Ah, good to know.
how do I install latest version? I want to install the latest minor relase for django 3.2. Instead of pipenv install django==3.2.0. it's something different but i forgot?
web monkeys 
When I attempt to run the server, the TiffModel page fails to load
(context django) how do I know in disconnect method of consumer if it was closed before accepting or after? I saw it has close_code but the docs don't say much about it
Hello all, I am looking to see if anyone has experience with the Johnson Controls API?
can you link the docs
you gonna quickly get experience or what lol
must be very pro then
what is your question regardless
So I am new to python and trying to grab trend data for analysis into python without exporting to excel first. I am a bit confused on the object identity I should be referencing. I will share what code I have so far, on min
one*
Hey @quaint mural!
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:
Hey @quaint mural!
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:
hmmmm wont let me share text
I found status codes here https://www.rfc-editor.org/rfc/rfc6455#section-7.4.1 , does django consumer use code 1006 only when self.close called before self.accept?
I think you are right
I am passing custom code (4000) to self.close but in disconnect method I still recieve 1006 why?
Hellooooo
im quite new to django framework and i want to make an auth system with jwt httpOnly Cookies
If anyone is able to give feedback on what comes to mind when you see these colors that would be magnificent!
Awesome! Let us know how it goes!
Sage/nature maybe, and the right side looks like a sliding card.
i like them
i feel like peace
Thanks for those answers! Doing some brand research and stuff like this helps get other opinions on how people associate to colors together
when i'm trying to test my app with postman sending data to get the status i always get this:
{
"detail": "Authentication credentials were not provided."
}
instead of this or this
{
"success": "User created."
}
{
"error": "Some error on signup"
}
Are you using graphene?
Usually that's a default response code from libraries that work with JWT
oh, I mean django-jwt
yess
Yea it means you need to be logged in, so you might be setting that somewhere in your user signup by accident.
but in the tutorial he makes the posts requests without that message
Helps to see your code.
okay
on my settings.py i have this
REST_FRAMEWORK = {
"DEFAULT_PERMISSION_CLASSES": [
"rest_framework.permissions.IsAuthenticated",
],
"DEFAULT_AUTHENTICATION_CLASSES": (
"rest_framework_simplejwt.authentication.JWTAuthentication",
),
}
SIMPLE_JWT = {
"ACCESS_TOKEN_LIFETIME": timedelta(minutes=30),
"REFRESH_TOKEN_LIFETIME": timedelta(days=1),
"ROTATE_REFRESH_TOKENS": True,
"BLACKLIST_AFTER_ROTATION": True,
"AUTH_HEADER_TYPES": ("Bearer",),
"AUTH_TOKEN_CLASSES": ("rest_framework_simplejwt.tokens.AccessToken",),
}
and my register view just takes the data and works with that info
Check your middleware as well - I think django-jwt requires a specific placement of the library at a certain level
maybe first
this is mine
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"corsheaders.middleware.CorsMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
]```
where's the djangojwt middleware?
pretty sure the docs will show what to put in there
I just don't remember off the top of my head
It needs to be above sessionsmiddleware I believe
__init__.py'>' does not appear to have any patterns in it. If you see the 'urlpatterns' variable with valid patterns in the file then the issue is probably caused by a circular import.
i have this error in django rest framework. dose anyone have idea?
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('Products') ),
]
this is my urls file in the project
where is Products coming from?
Products.py with its own urlpatterns?
its an app, is the solution Products.urls?
Not sure you can import an app this way?
I think you can only include other files with urlpatterns
Oh snap, django 4 is out
Hello #web-development , i have a problem with my administration panel using django version 2.1, i am not using the latest version because i am doing a specific project, anyways, after creating a table in admin.py βββadmin.site.register(Product)βββ i went to the admin panel to add a product, everything is smooth but when i pressed save it gives me this error: no such table: main.auth_user__old
If anyone is familiar with this problem Iβd appreciate the help
First link on google:
Did that not work?
The problem is caused by the modified behaviour of the ALTER TABLE RENAME statement in SQLite 3.26.0 (see compatiblity note). They also introduced the PRAGMA legacy_alter_table = ON statement in order to maintain the compatibility with previous versions. The upcoming Django release 2.1.5 utilizes the previously mentioned statement as a hotfix. It's expected on January 1, 2019.
If you have an error in something you're doing, we can help troubleshoot it.
Share the specific problem.
Well no error but ```from quart import Quart, request
from discord.ext.dashboard import Server
app = Quart(name)
app_dashboard = Server(
app,
"secret_key",
webhook_url="",
sleep_time=1
)
@app.route("/")
async def index():
guild_count = await app_dashboard.request("guild_count")
member_count = await app_dashboard.request("member_count", guild_id=776230580941619251)
return
@app.route("/dashboard", methods=["POST"])
async def dashboard():
await app_dashboard.process_request(request)
if name == "main":
app.run(debug=True)```
Am trying to make this direct me to the discord login page
How do i do that?
You're trying to do a discord login in a flask app?
I don't know but I'm sure there are some tutorials about it.
Well not flask any more am doing with quart
Thanks a lot man
hey guys
question from a newbie here - I was wondering how does actually a website work in terms of storing different data in the same pieces of code/variables
meaning, there is one and only code for some website, but different users can input their own unique values (like for example a bank's site, different users put their own passwords and for example different amount of money to be transferred somewhere).
how does the webpage work and know not to mix the different values entered into the same forms/places of code?
are sessions responsible for that? I read that they mostly track the time spent on a page, so I'm not sure about it
and I could not form the question properly enough to get google the answers I'm looking for
to be more specific, I assume that somewhere in such bank's site's code, there is a variable named "amount_to_be_transferred"
it can be assigned to different numbers from different users at the same second, so how does it know to store different values using the same code?
The first time you land on a website it gives you a random session token
And your browser will send that token with every request. It's often called a session cookie
Each time a web server recieves a request it can look up the token in a database and associate data with it, eg the currently logged in user
The same pieces of code can have different state because of the call stack. Each Python thread/coroutine has it's own call stack and local variables are stored there. Often a single request is associated with a single call stack
I see
so those cookies are allocated to each user and are they constant? meaning, what if the same user uses different computer? how would the website know to allocate the data he is entering to his account?
You would have to authenticate from that second device
okay so with every new user, there is a unique ID associated with that user, right? such key is stored in a database in one row with said user's other data, correct?
yes
you can log in from different devices as the same user but in general those will be different "sessions"
so sessions are responsible for that, that User A doesn't see User B's saved data on his account and vice-versa?
yes, the session cookie is sent between the browser and the web application and the web application knows what user is associated with that session
even non-authenticated users can have their own sessions as anonymous users
huh, alrighty
I'm thinking of building my own simple website to get a grip of all those aspects
thank you all for spending your time answering me π
that will probably be the best way to start to understand how it all works together
good luck!
Hello can someone help me? does anyone here know swagger ui? or openapi 3.0? im currently having issue in accepting null in values, I tried adding nullable : true under oneOf but doesn't work please help
Hi! Does anyone have any recommendations for django courses? I found one from jose portilla on Udemy but it hasn't been updated since 2019, so I was looking for something more recent
(env) C:\Users\coadi\Desktop\AlterBot>c:/Users/coadi/Desktop/AlterBot/env/Scripts/python.exe c:/Users/coadi/Desktop/AlterBot/dashboard.py
File "c:\Users\coadi\Desktop\AlterBot\dashboard.py", line 14
os.environ("OAUTHLIB_INSECURE_TRANSPORT") = "true"
^
SyntaxError: cannot assign to function call
can anyone help me with this error?
i dont really know whay it occured
to assign values in a dictionary you use hard brackets []
You cannot assign values to function calls, it says that
like os.environ["smth"] = "true"?
now what is this?
(env) C:\Users\coadi\Desktop\AlterBot>c:/Users/coadi/Desktop/AlterBot/env/Scripts/python.exe c:/Users/coadi/Desktop/AlterBot/dashboard.py
Traceback (most recent call last):
File "c:\Users\coadi\Desktop\AlterBot\dashboard.py", line 3, in <module>
from quart_discord import DiscordOAuth2Session, requires_authorization, Unauthorized
File "c:\Users\coadi\Desktop\AlterBot\env\lib\site-packages\quart_discord\__init__.py", line 4, in <module>
from .client import DiscordOAuth2Session
File "c:\Users\coadi\Desktop\AlterBot\env\lib\site-packages\quart_discord\client.py", line 3, in <module>
import discord
File "c:\Users\coadi\Desktop\AlterBot\env\lib\site-packages\discord\__init__.py", line 20, in <module>
from .client import Client, AppInfo, ChannelPermissions
File "c:\Users\coadi\Desktop\AlterBot\env\lib\site-packages\discord\client.py", line 38, in <module>
from .state import ConnectionState
File "c:\Users\coadi\Desktop\AlterBot\env\lib\site-packages\discord\state.py", line 36, in <module>
from . import utils, compat
File "c:\Users\coadi\Desktop\AlterBot\env\lib\site-packages\discord\compat.py", line 32
create_task = asyncio.async
^
SyntaxError: invalid syntax
yeah now this one
invalid syntax from another file
is asyncio.async a thing
yeah
so it is web dev related
idk how to fix i'm still learning
even google cant help
as far as I can see the fastest (in terms of performance) solution for frontend framework in images is usage of CSS sprites
can anyone recommend tool for CSS sprites?
well done
"Around here, however, we don't look backwards for very long.
We keep moving forward, opening up new doors and doing new things, because we're curious... and curiosity keeps leading us down new paths."
- Walt Disney
Keep Moving Forward.
A life lesson from the Disney film: Meet the Robinsons.
Does anybody has experience in Django ? for whatever reason I can't include results app or any other apps in django project.
hi, we working with framework and i don't understand it a lot . we have created a website, i used html, css and javascript. she asked us to find framework and libraries in our website. how to do that?
Any django 101 article. They might differ a bit but usually describe the basics quite well, there's nothing too complicated. Start with a venv, then installing dependencies, then running the instance. Once you understand that process, you can move on to creating stuff.
Which command are you using, runserver? How does your file structure look?
views.py
class GeneralFeedbackCreateView(APIView):
def post(self, request, *args, **kwargs):
serializer = GeneralFeedbackSerializer(request.data)
if serializer.is_valid():
data = serializer.validated_data
name = data.get('name')
subject = data.get('subject')
message = data.get('message')
# email = data.get('email')
send_mail(
'Sent email from {}'.format(name),
'Subject: {}'.format(subject),
'Here is the feedback: {}'.format(message),
# settings.EMAIL_HOST_USER,
'test@gmail.com'
['info@test.com'],
fail_silently=False,
)
return Response({"success":"Sent"})
return Response({'success':"Failed"}, status=status.HTTP_400_BAD_REQUEST)
#serializer.py
class GeneralFeedbackSerializer(serializers.Serializer):
name = serializers.CharField()
subject = serializers.CharField()
message = serializers.CharField()
#Error
Cannot call `.is_valid()` as no `data=` keyword argument was passed when instantiating the serializer instance.
Request Method: POST
Request URL: http://127.0.0.1:8000/api/feedback
Django Version: 3.2.10
Exception Type: AssertionError
Exception Value:
Cannot call `.is_valid()` as no `data=` keyword argument was passed when instantiating the serializer instance.
Please help. :)```
anyone django
I don't see in your code interactions with database
serializer = GeneralFeedbackSerializer(data=request.data)
have you tried reading the error
yes
data= keyword is missing
Also i think it's better to use serializers.is_valid(raise_exception=True)
I was heavily missing validators for sure
Also don't use dict.get π
remembered how much of code i wrote in the place of missing validators
π
I should read about all drf features
You didn't know about serializers? π€¨
I did not know they could be used without database
Then what to use?
They could:
class BookCreateSerializer(serializers.Serializer):
title = serializers.CharField(max_length=60)
class BookSerializer(BookCreateSerializer):
created_at = serializers.DateTimeField()
class BookCreateView(APIView):
@swagger_auto_schema(
request_body=BookCreateSerializer,
responses={
status.HTTP_201_CREATED: BookSerializer,
}
)
def post(self, request: Request):
serializer_in = BookCreateSerializer(data=request.data)
serializer_in.is_valid(raise_exception=True)
book = Book.objects.create(**serializer_in.data)
serializer_out = BookSerializer(instance=book)
return Response(serializer_out.data, 201)
You don't have to use inheritance here but in this case it's convenient
#web-development message
I know, we discussed it already
use [] or pass your data via **
Yep, i remember, i just sent a code example π
It's a python thing, it's not related to django
dict.get would return None if key is not present in a dictionary it's better to use [] where possible
Is django used for backend ?
Yep
class CommentSerializer(serializers.Serializer):
content = serializers.CharField(max_length=200)
page = serializers.IntegerField(min_value=1, default=1)
def test_using_valudator_with_extra_data():
serializer = CommentSerializer(data={"content": "data", "123": "456"})
serializer.is_valid(raise_exception=True)
validator is not giving error for "123", can it?
π€ I think it will ignore extra data, but i'm not really sure
it ignores at the moment
I wonder if it can enforce being not ignoring
There's a bug btw, you SHOULD use serializer.validated_data
Not Python related, but anyone has a good HTML with JS tutorial/guide?
This might be too broad for what youβre after but the MDN documentation is pretty good for vanilla HTML & JS guides: https://developer.mozilla.org/en-US/docs/Learn/HTML
Thanks
good resources for react?
there is a validate method on the serializer class you could override. Perhaps you could check that only the fields inside of the serializers.fields show up in the posted data
I have a question regarding web development with Python. So currently I have a website where I upload a file. When the upload is finished, I run a command line program on the server with the uploaded file as input. Afterwards I echo the path to the processed file. I did that with PHP about 6 years ago and it was fine. Now I wanted to update some parts of the website and extend it and noticed that after 6 years of not touching PHP, I might as well go and re-do it in Python. So based on my short description, how hard is it to do with e.g. Flask?
it should be equally easy
I dug around a little and it definitely seems doable
Might be something for the weekend... :D
I must warn you though about unsafety of running linux shell commands from user input data, it just asks for injections to hack the server
I'm really not sure how else to do it. You have to go through two screens where you have to enter your password being able to upload anything at all. With PHP I was able to work with prepared statements as well and I definitely check the input. Definitely not hardened against everything though.
how about renaming in python all incoming files into same or random name
then you would have been using linux command for the file
that has certainly safe name
That's what I do with PHP at the moment
for example renaming files to
import secrets
secrets.token_hex(16)
that's just random generator
hello, how do you do this in flask?
class="nav-item {% if 'ui-forms' in segment %} active {% endif %}"
segment global does not exist in flask i think. I just want the active to appear if the url segment has ui-forms.
you might want to start with the django tutorial first then have a look at the F12 developer tools network view and see what's going on. https://docs.djangoproject.com/en/4.0/intro/tutorial01/
then once you have that down fully you can check your understanding by making an asgi app from scratch that manages sessions and state
if you start with a tool that does it all for you already you'll be able to more clearly see the target you're aiming for
Hello folks,
I'm currently trying to make a flask app, and i've structured it using blueprint, but i can't hit my end points.
A more detailed description can be found in #help-orange .
I'd appreciate the help a lot !
Thanks :B
hi, can i get some help about running a web server whit pyton?
i have this code that run a web server:```py
from http.server import HTTPServer, BaseHTTPRequestHandler
class CustomHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('content-type','text/html')
self.end_headers()
h = open("index.html","r")
self.wfile.write(h.read().encode())
if name == 'main':
PRT = 8000
srv = HTTPServer(('',PRT), CustomHandler)
print('Server started on port %s' %PRT)
srv.serve_forever()```it run the index.html
but the page has no javascript or css
and whit the inspector this code is basically sending only index.html as any request
What's the question? Are you getting an error message?
the web page has no css or javascript
and i think is because self.wfile.write(h.read().encode()) only give index.html
idk, i just want to run a test server to debug a web page.
@golden bone
Your index page has CSS and JavaScript, it's just not displaying correctly when you serve it with Flask?
Flask?
Ah, nevermind. I'm not familiar with http.server
Does it even support JavaScript?
ok, i'll try flask.
If all you want is a webserver use a webserver. Nginx or Apache whatever
i made a web server but i still get these errors
using flask this time
here: ```py
from flask import Flask, render_template
app = Flask(name)
@app.route('/')
def index():
return render_template('/index.html')
if name == "main":
app.run(debug=True)```
Nginx and Apache can run whit pyton? i want to use pyton because i don't have enough time to set up a new software.
what is WGSI file in django? does that stand for something?
actually this doc isn't that useful
wsgi is an interface that lets web servers like apache and nginx interact efficiently with a python application
so the wsgi file in a django application is the module that the wsgi server uses to interact with your django application
yes, you can use them as a "reverse proxy"
but you still need to set them up and configure them
i strongly recommend learning how to use nginx or apache
@surreal thicket thank you this is very helpful
static files should be in folder static
template file html should be in folder templates in flask
Flask will serve static files only as development server
for production ready solution u would still need to learn something like apache/nginx, while launching python web servers with things like gunicorn
didn't work
here my setup
this in the console:
change url addresses, add to them /static in the beginning
like this?
What can I do to make driver.execute_script('window.print();') work while running headless chrome with selenium? The following code does what I need just not while headless
#Open print dialog and save page to PDF
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
import time
import json
#SET DEFAULT PRINT OPTIONS
settings = {
"recentDestinations": [{
"id": "Save as PDF",
"origin": "local",
"account": "",
}],
"selectedDestinationId": "Save as PDF",
"version": 2
}
prefs = {'printing.print_preview_sticky_settings.appState': json.dumps(settings)}
options = Options()
options.headless = True
options.add_experimental_option('prefs', prefs)
options.add_experimental_option('excludeSwitches', ['enable-logging'])
options.add_argument('--kiosk-printing')
driver = webdriver.Chrome(options=options, executable_path=r'S:\Selenium\chromedriver.exe')
actions = ActionChains(driver)
driver.maximize_window()
driver.get("https://www.imdb.com/title/tt5071412/")
print ("Headless Chrome Initialized")
getTitle = driver.title
time.sleep(5)
print(getTitle)
driver.execute_script('window.print();')
time.sleep(5)
#driver.save_screenshot("screenshottest.png")
#actions.key_down(Keys.ENTER).key_up(Keys.ENTER).perform()
driver.quit()
@inland oak yet dont work
this is what the insector show me
plus the style.css appear to be empty here
app = Flask(__name__,
static_url_path='',
static_folder='web/static',
template_folder='web/templates')
<link rel="stylesheet" type="text/css" href="/css/bootstrap.min.css">
https://stackoverflow.com/questions/20646822/how-to-serve-static-files-in-flask
app = Flask(__name__, static_url_path='/static')
<link rel="stylesheet" type="text/css" href="/static/style.css">
@golden bone I will take a look, thank you
Not sure that's 100% relevant but hope it helps :)
@inland oak still don't work
this is the python: ```py
from flask import Flask, render_template, send_from_directory
app = Flask(name, static_url_path='/static')
@app.route('/')
def index():
return render_template('/index.html')
@app.route('/static/path:path')
def send_js(path):
return send_from_directory('js', path)
if name == "main":
app.run(debug=True)```
this is the html: html <script type="text/javascript" src="/static/script.js" defer></script> <script type="text/javascript" src="/static/version_read.js" defer></script>
ok, wait. i found a typo and now it works
thank you!
@golden bone it helps in telling me that its not possible to pass preferences to chrome headless so I can stop playing around with that now so thank you for that, but the type of pages I am trying to save to PDF are converted to a different view when the print dialog box opens up and are quite different looking than standard view in the browser
i guess because its a web app made in angular
Hi, I have a question. I am trying to upload a file from the client end (PDF, TXT, CSV, Excel), to the server, in Flask. And, after hitting the API, if I open the Developer Tools, on my browser, and go to the Network Tab, to monitor the API, I can view the content of the file I have uploaded in the API Request Body. And as a design and security requirement, I do not want that to happen. Ideally, I would like to have the API Request Body show up as empty.
How can I achieve this?
How about some encryption/decryption
Won't that be an issue, as the file size can be greater than >1GB, and encrypting on the front end, of such a large file, even if it is being processed in chunks, might be too much for JS?
Find some encrypting algorithm that has public and private keys
And allows anyone to encrypt that has public part
And let your server have private key that allows decryption
Yes it will be an issue
But sending 1gb file will be always an issue
Why would u wish sending such big file
Yes, it will. But the best way would be to break the file into chunks, and do what something like Microsoft does, which is creation of an upload session and reassembly of the chunked files. But the problem is the encryption algorithm itself, as from my experience, JS is not great at heavy encryption because of it's single threaded nature.
Highly likely there is limit 5 megobytes
At least it is the limit of local storage
Taken it up more as a challenge. Want to build an ETL system that allows for massive files (i.e. >1GB)
Js is quite fast. I would worry about memory limits first
Once it reaches certain point, js can become super slow
Yes
The memory issue is something I have found resources on. But the problem is that I cannot actually find anything on Google for my API security requirement. Maybe I am searching for the wrong thing.
Perhaps u will rely on simple TLS
Everything is already encrypted by SSL certificates / HTTPS connection
Just enable it
And make sure your web server supports last existing secure algorithms, enable enforcing only of secure algorithms if u wish
Hello. I've never worked in a web develepment project before. Actually i want to creat a web formulary with python. I have a server and a MySQL model. Does someone recomend me any course to get this into web as soon a possible?
Any nginx expert?
what is nginx?
don't "ask to ask". state your question, and if someone knows the answer they will answer
ok
it is an http server that is especially good at acting as a "reverse proxy", meaning that it forwards http requests to other applications. a common setup is to use nginx + gunicorn to run python web applications
i want to redirect https://www.example.com to https://example.com
yes, i want to deploy django project
i think usually this is done at the DNS level. but you can do it in nginx by returning 301 or 302:
server {
server_name www.example.com;
return 302 $scheme://example.com$request_uri;
}
With dns should I use A record?
sure, you can have an A record at both @ and www pointing to the same IP. another solution is to set an A record on @, and set a CNAME record on www that points to the non-www version. i assume the latter is better for SEO, but i am not sure
i assume you are using gunicorn?
maybe
if anyone here can help me with web scrapping that would be amazing just shoot me a dm and a friend req
theroretically it is usually solved at DNS level of records
CNAME record from www to @ (or example.com) should do the trick
can i use flask and django together ?
sure. But it does not make sense at all.
so I would say no
but
it does make sense actually if they are two different microserviced applications
but still does not make sense in terms of increased cost of maintanance to support code for two frameworks
ohh i see
thanks
is making a website with python good or i should use html or css
?
If u intend to make visual part of web site, then here is the list of what you can do from the worst to the best options:
- Plain html/CSS(worst)
- Using backend framework (like flask or Django)
- Using Frontend framework(like react / angular / vue.js) (best for visual part)
Optional augmentations:
- U can improve plain html and backend Frameworks with jQuery
- u can improve backend framework with attaching Frontend framework (better than jQuery usage, but worse in my opinion than using frontend separately)
- u can improve all three choices with attaching SCSS
when i try to find scss it shows me sass is it the same thing ?
Sort of yes
By default SASS tools often work as SCSS tools
i cannot find SCSS so should i go with SASS
but i guess using frontend framework will be better for website
sigh
if i use react or something similar would i need to learn js first ?
speaking from my experience, i learned Vue.js after just reading HTML and CSS Head First and Javascript Head First book
my initial knowledge about javascript was close to zero, but it was not an issue to get into the flow
Javscript knowledge is requried and it needs to be learned, but it should be possible to learn JS in the process
For visual part of web site, yes. Frontend Framework + SCSS/SASS is the best π
backend frameworks main purpose to do server side jobs..
people often resort to scheme...
using Frontend for visual + Backend as REST API that returns/accepts JSON inputs/outputs for server side tasks if they exist
What category websockets come front-end or backend
both. Websockets are type of connection between frontend and backend
Okay sir
Can I connect websocket in android or ios App for notifications
@inland oak
yes it should be possible. your Android/IoS app is sort of frontend app in this case
And I have a dbout why django Oauth kit is used with django JWT in django rest is it compulsory to used both in production @inland oak
Didn't quite get the question but authentication can be achieved in multiple ways, usually you have to choose one and don't mix it with others.
I think django Oauth kit is used with jwt
Is it correct
Hm, I have to check but afaik Oauth and JWT are two different methods
https://www.django-rest-framework.org/api-guide/authentication/#django-rest-framework-oauth
Docs confirm those are different, not related methods.
Django, API, REST, Authentication
And again, generally you'd use either one of them, unless it's some massive corporate service, but even then it's best to avoid such practice since it is over-engineering.
Hey guys, Im trying to host a django project on heroku. But im getting an error in the logs:
ModuleNotFoundError: No module named 'widget_tweaks'
Can anyone help me how do I solve this error
For localhost user or for public internet access?
Public internet access for one - two persons at maximum or for dozens and more people?
Have you got your requirements.txt in root directory?
Yes
Is that module in it?
is there a way to attach a header to uvicorn that it accepts CORS-requests?
But the thing is that if someone stole our jwt token how can we protect it in frontend or Ani App .
you don't want to manually specify that header
for each endpoint in your app right
right now, i just get an error saying my browser cant communicate with my endpoint sicne they have different addresses. and i dont like the hack of proxying stuff and it also makes the architecture more complicated. I would appreciate any solution to this problem. The only one i could think of was to just attach the header and allow cors. What do u have in mind?
hello everyone, got a small question, not sure this is the right channel: I did a Flask course and I am building something myself. Was asking myself if I can get a status variable value from a POST request in a GET request. Running a GET every 1s to get the status that is being processed in a POST. Thanks
Hello there, anyone got his hands on Django Graphene?
I've never done that but theorically I don't see why you can't
can please some one tell me in laymans term what is react js and what does it do
which packages or how we can use for image thumbnail in DJANGO REST FREAMEWORK
You mean the favicon.ico?
React is a reactive frontend framework for building dynamic webpages. Reactive means it reacts to changes like the url, mouse clicks, time, local storage, etc
Hi all, I am looking to make a website for a family member who recently started a hotel if anyone can guide me or has information please get back to me thanks.
thanks
similar frameworks include vue and angular
I like vue because its components are valid html
i.e. no special parsing of <x y={{z}}/>
instead you get <X :y="z" />
:y is a shortcut for v-bind:y
there's also @x= => v-on:x=, #z= => v-slot:z=
So I am kind of confused on what is going on here, I have a <href> download link to download a File off of my server but instead of download it, it just translets the page into a non CSS mode.
<a href="/mnt/disk1/appdata/nginx/www/BetaProjects/KivyCentered.zip" style="color:#11e763;">Source File</a>
I am pretty sure u have a wrong path/href
U a supposed to write a filepath starting from root of website
Not a root of filesystem
/mnt/disk1/appdata/nginx/www/BetaProjects
Your root of website is highly likely this
If this what u wrote in nginx config
I am using default nginx config, I didn't want to break anything.
i want to make a carpooling website for my school and people can offer/request rides
but i don't think i can do that with just my knowledge of html/css/javascript
what should i learn? where do i start learning this kind of stuff? what do i do?
You could use javascript on the backend since you already have knowledge of it, but I would recommend Python/Django
Official django tutorial is a decent place to start. https://docs.djangoproject.com/en/4.0/intro/
Hi i dont know if i should ask this. But, it wont let me import 'semantic-ui-css/semantic.min.css' this? To design my buttons for my discord bot dashboard
Could I make a game on a website or would I need to use JavaScript
you'll need JavaScript
Okay. Thanks
i want to learn python from beg to pro
thanks
So u intend to use for real production, not for demonstration or development environment.
Then... Don't host in windows. Host in Linux.
@inland oak Hey wassup
Yeh if you're targeting web js is only way to get put
(context djanog)
this is the chess model i currently have
class Game(models.Model):
ONGOING = "O"
ABANDONED = "A"
COMPLETED = "C"
STATUS_CHOICES = (
(ONGOING, "ongoing"),
(ABANDONED, "abandoned"),
(COMPLETED, "completed"),
)
white = models.ForeignKey(
settings.AUTH_USER_MODEL,
related_name="games_as_white",
on_delete=models.CASCADE,
)
black = models.ForeignKey(
settings.AUTH_USER_MODEL,
related_name="games_as_black",
on_delete=models.CASCADE,
)
fen = models.CharField(
max_length=90,
default="rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",
)
status = models.CharField(max_length=1, choices=STATUS_CHOICES, default=ONGOING)
created = models.DateTimeField(auto_now_add=True)
any suggestion on status field? I now implementing win/lose and draw and I think i think the abandoned and completed status represent the same thing and i am a little confused rn
also is it recommended to define the ONGOING, ABANDONED ... STATUS_CHOICES inside or outside the class?
once again do you want to manually "attach the header" under ever single function in your app
or do you want some kind of shortcut, like set a setting, and it will be applied to all the functions
Anyone good as password encryptions? Having issue with registration and hashing passwords in Django project
from django.contrib.auth.hashers import check_password as django_check_password
from django.contrib.auth.hashers import make_password as django_make_password
class Customer(models.Model):
@staticmethod
def make_password(value):
return django_make_password(value)
def check_password(self, value: str) -> bool:
return django_check_password(value, self.password)
django has it inbuilt, not reallly a problem
Does that work efficiently?
Can we talk in message? I will show you part of the code, it's a company code so do not want to expose it too much. π
Well, I am having a bit of time, call if you want
Would be great, lemme grab headphones
Is there anyone who is a ui / ux designer here or learning it now?
If the status is completed then only in match can be draw win or loose right?
I am gonna replace completed with resigned, timeout, checkmate or draw
and draw*
Call karu ka
and put a winner user fk field
kr na
ty, that's great since i already know python
Is there anyone who is doing ui ux designing or learning it??
{% extends "index.html" %} {% block title %}Changed{% endblock %} {% block content
%}
<h1>HOMEPAGE</h1>
{% endblock %}
HOMEPAGE should appear but it is not can anyone pls help i am using flask
anyone pls
tell me also
So my backend is implemented all in Python and I want my JS code to show that. How can I "pass" the data from the backend to the frontend? What's the way used for this thing? Ping me if you know
what means JS code to show that ?
So my Python code is processing some data with tensorflow and returning some JSON dicts. I want the JS to process them and show those in a beautiful way (which is gonna be coded, ofc)
simpliest way to transfer data from backend to frontend: is making REST API end points in backend that accept requests in GET/POST/and e.t.c. JSON format
and frontend would make with something like Axois fetch request to them
And how will I prevent the outside people from accessing the API?
can't resist writing meme to it
π€£ tf
in Backend application you can firstly setup which domains origins are allowed to make requests to your API
Okay....?
secondly, you can make some sort Authentification procedures
but
no matter what you do your web site is still going to be web scrapped
and your frontend would be still used to access backend without limits
to protect it further you need something like Cloudflare protection with captchas π
installed to your web site
if you backend will be allowed to have access only to authentificated users
then make authentificating process
and the end points for your special stuff allowed only for authentificated users
so ig I can ignore those since we are still on the development phase
usually people use JWT auth system in microservice architecture where front and back splitted
Oh
it scales well when you have a lot of backend microservices
JWT allows to authentificate user once in auth backend API
and having access transmitted to other backend APIs without repeated requests to auth API
Well so what is your preference to make an API? Something like flask or...
i prefer Django, Django Rest Framework modification is quite having everything ready for making REST API
I wish to try FastAPI, it is cool too
in the end of the day if nothing helps
it is possible to setup Throtting limits
how much requests are allowed from specific IP in a specific time period for specific type of request
Django Rest Framework has this feature as one of its modules already
I am just a newbie to web dev, since I prefer making standalone apps more FYI
standalone apps? u mean Monolith apps? π
I meant non website stuff. Using modules like Kivy and stuff
oh. so you were desktop and/or mobile dev
Ah yea. My bad, my braincells are only half working rn
i knew i wish being web dev so fully dived into it
still feeling myself as newbie though
but newbie that can do small scaled projects, probably
Haha well I know only the basic API projects and stuff only
I am that kind of person who does something like
@app.route("/")
def home():
return jsonify({"message": "Hi"})
for every project/API
ping
pong!
Vscode update server responds with π
???
Hahaha
Hey BTW Darkwind, do u have any frameworks in mind, for JS, to make my work easier? (Keeping in mind that I am a complete newbie, even in JS)
You could use vue
Vue.js
I don't think you can go wrong with any of the popular 3
I learned it within a matter of weeks / one month from complete zero
Vue.js is recommended as the most beginner friendly π
at least learned to level to do my task
Well I was thinking of using/learning React before, but thought to first make myself comfortable with Vanilla JS, then diving into something like this, that's is why just asking
Once you finish the frontend, I recommend nginx unit to join it with the backend
React could do the trick as well.
If you're familiar with programming in general learning a language when learning a framework would be fine imo
Example project (using fastapi): https://github.com/killjoy1221/nginx-fastapi-vue-docker
perhaps he has an infrastructure engineer in his team
then it is not his issue
Oh thanks for that!
On my team, I am that guy
startup, i am all guys
My team's company has 10000 employees
The only thing I don't manage is the kuberneties infrastructure
I already do that too
as a matter of fact refactorizing my homelab to it as well at the moment π
It is just a side project with a friend of mine 
(My net went, sorry)
What do you mean by refactoring code
refactoring code means
removing mistakes or improving code quality.
there are multiple types of bad code smells, if to fix exactly bad code, read Clean Code by Martin, but that's actually topic for multiple books
but in my situation i am improving code by migrating it to better technology.
my old pet projects were running in docker compose in multiple servers
I migrate all my pet projects into single kubernetes server
that can utilize distribution of resources efficiently even within single server
which will save me money
+kubernetes allows me easily to setup monitoring/logging system to all of my pet projects at once
i'll have at last Prometeheus / Loki / Grafana / AlertManager and e.t.c. array of systems to track my apps
kubernetes alone introduces a lot of services, like its internal DNS service, its configuration management system, self healing properties
that will improve my infrastructure code by magnitude
hmm... also I gathered a bit of data while maintaing pet projects
so I know where they require from me operational manual actions
I am automating small stuff I did before that
part of refactorization too
That is way away from my headπ© π π
π
WHAT library will be good for playing js online?
how would i build a ticket system that users can create a ticket and have a conversion with a admin? (django)
Playing js online? If you mean loading js as if in a browser, Selenium
okey
does anyone know of a good way on storing a conversation via a ticket in django? e.g user opens support ticket and can reply/chat with the admin
im just struggling to think of a good and secure model to make something like this
i would have to make a new row for each message right?
I see loads of tutorials online for doing chat in Django. I haven't tried it but definitely check some of those out if you haven't
Frankly, the data modeling is the easy part.
You can store ticket id, user id, timestamp, and message content in your conversation model
if you want to have multiple conservations on a ticket maybe create a convo and message model
but for support specifically, I assume you'd want admins to be able to see other admins conversations
hello
do u know flask?
i need help in flask
urgent
please
https://www.pythondiscord.com/pages/guides/pydis-guides/asking-good-questions/
What Not To Ask
Q: Is anyone here good at Flask / Pygame / PyCharm?
There are two problems with this question:This kind of question does not manage to pique anyone's interest, so you're less likely to get an answer overall. On the other hand, a question like "Is it possible to get PyCharm to automatically compile SCSS into CSS files" is much more likely to be interesting to someone. Sometimes, the best answers come from someone who does not already know the answer, but who finds the question interesting enough to go search for the answer on your behalf.
When you qualify your question by first asking if someone is good at something, you are filtering out potential answerers. Not only are people bad at judging their own skill at something, but the truth is that even someone who has zero experience with the framework you're having trouble with might still be of excellent help to you.
So instead of asking if someone is good at something, simply ask your question right away.
A guide for how to ask good questions in our community.
u know or not
I want to show posts on home page in flask
but here the home page is admin panel so the posts which users can see should be their own posts rather then seeing every user's posts
make the page rendering the posts only for the user currently mentioned in Query Params (url) of the web site (https://yourwebsite.com/user_Identification)
make the necessary SQL query for the chosen user, to get only his posts
feel free to authenticate users and redirecting them to their home page
a matter of simple SQL query
instead of quering
SELECT ALL POSTS
change to
SELECT ALL POSTS
WHERE USER_ID=USER.ID
or its equivalent in ORM language
and regarding your questions to DM. You are again asking questions in a wrong way.
highly recommending to read carefully https://www.pythondiscord.com/pages/guides/pydis-guides/asking-good-questions/
otherwise you would have a trouble to get help from anyone
A guide for how to ask good questions in our community.
No one really wishes to help person who just calls for pity, without making even an attempt to seek for answers
usually such person is just ignored and blocked away and never answered why
brother actually u dont want to help
Whatβs your file structure like?
I want to show post on home page which were posted by users
here the home page is admin panel
and rather than showing each and every posts i just want to show the post of the user which he has posted on his admin panel page
In flask
Darkwind just told you exactly how to do this right before you accused them of not wanting to help. If you don't understand the solution maybe you can share a link to the code
Hi, Faraz
How are you?
I would like to discuss about your spec
Could you dm me right now?
I am Python developer, have rich experiences with Flask and Fast API and Django Framework.
Can someone help me with this?
I get "no module named 'config'" when I try to add a new row in admin zone
the error is caused by an ImageField
that works in local but not in production
Hi, Enrico
you need to add module to your app/setting.py
do I need to put
"import config" into settings.py?
no
what then?
you can find INSTALLED_APPS in your setting.py
yeah
inside there there's my configuration app of my app
the line before the last one
you have to add 'config'
you need to add 'website'
I will try
i thought that i do not need to put "website" if I have already put "website.apps.WebsiteConfig"
I will give a try
btw thank you for your time, luckystar
the thing that scares me, is that the problem is caused by a field of a module
yeah yeah, I am uploading to try if it works
it takes some minutes (I am using app engine)
no problem
what do you think about that?*
if I do not use that field (in views.py, in a template etc...) the website works fine
but I do have to use that field, is one of the most important
now I just got 502 bad gateway
from the logs
as i thought
i do have to remove website.apps.websiteconfig
What framework do you use?
please change your app name "website" => "others" and try again
and you need to add name to setting.py/installed_app config
why? I can't change my app name
which I did
let me check
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.postgres',
#'website.apps.WebsiteConfig',
'corsheaders',
'website'
]
how is it working?
it's not working π
.
yes, of course
I am not new with Django
I am new with Google Cloud
I think the error is caused by the storage
it would make sense, because the error appears only if I use the "ImageField", that has access to Google Cloud Storage
okay, good
Hey guys, want to separate my django project into dev and production branches. I am using docker-compose and github actions. How to organise it better? I know that using sqlite in dev and postgres in prod is a common practice but what do I do with docker and what stuff is better to be done in this case? I am also planning to add gunicorn + nginx later
so i have a textbox and i want to make sure that when the user presses enter, the first characters arent spaces. how do i do that (javascript)
on what language should i code a chat application?
Try to use the same database in both dev and prod. You can end up with weird edge cases if they are different. Not as familiar on the docker side, but should be able to build the branch and tag the build dev or prod. You can use gunicorn and nginx in dev as well and with docker-compose it might even be easier than the django dev server.
Hi, everybody
I am looking for a good job in python and django and flask and fast api.
if anybody have a good job, please let me know π
please dm me
Anyone have experience with HTML/CSS?
For some reason my CSS file won't connect to my HTML file
your path is right?
to import CSS file in your HTML
Yeh it is, in the head of my HTML I have
<link rel="stylesheet" href="/css/style.css" />
Because style.css is in a css folder
Can you click href with Ctrl + Lmouse?
Yep, it takes me to my stylesheet
I mean it is not imported right now.
you did import style css to your last position?
or the problem is in your style css file I think
Yeh that's what I'm thinking as well
Can I check your css and html file?
Yeh sure
please send me
Give me just one moment please π
ok
that path is wrong. it starts with a forward slash which will make it relative to the root of the server not the currrent directory
you want this... href="css/style.css"
FYI. I don't think that's a html/css thing either. I think that's just how paths work on computers.
Can i ask PHP questions here?
HI all what's the best way of Passing Semantic Web (RDF,JSON-LD,eRDF,RDFa,Microdata,Microformat) in python?
can someone help me in open edx?
someone here try this?
I clone an open edx at git and run the set up file using docker at pycharm
right now I'm having this error
hello everyone
Hey guys, I have an idea for a business that would require a high end website, mobile app, and large scale databases. I currently only know a bit of python. where would I start with a large project like this? im mainly asking if i should build the server first or the website/app. and after I get that answer where do I start with that subject.
Thanks!
Try ./css/style.css
