#web-development
2 messages ยท Page 137 of 1
(venv) C:\Users\SpyD\Documents\flaskmyproject\demoapp>python app.py
Traceback (most recent call last):
File "C:\Users\SpyD\Documents\flaskmyproject\demoapp\app.py", line 1, in <module>
from flask import Flask
ModuleNotFoundError: No module named 'flask'```
some help to fix that?
code:
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return "Hello! This is a website where you can find many things about python (for begginers)"
@app.route("/<name>")
def user(name):
return f"Hello {name}!"
if __name__ == "__main__":
app.run() ```
did you install flask?
yes
i saw this vid:
https://www.youtube.com/watch?v=zYhpx63SPKY
How to Install Flask and run on Windows 10
- Create folder name flaskmyproject
- py -3 -m venv venv
- venv\Scripts\activate
- pip install flask
- flask --version
- mkdir demoapp
- flask run
http://127.0.0.1:5000/
help plz ๐ฆ
are you sure its not in another environment cause what error means is that the flask flask is not installed
i install it i am sure
Hey guys, how can I serve static files in an ASGI web application?
I've looked into whitenoise, but thats just for WSGI apps
in django right?
No
ok
My own web framework
not sure we gotta ask you
I'm figuring out how to add static file serving
try typing venv\bin\python flask run in your venv.
ok
The system cannot find the path specified```
????
why
Hey @silver wagon!
It looks like you tried to attach file type(s) that we do not allow (.mkv). We currently allow the following file types: .3gp, .3g2, .avi, .bmp, .gif, .h264, .jpg, .jpeg, .mov, .mp4, .mpeg, .mpg, .png, .tiff, .wmv, .psd, .ai, .aep, .xcf, .mp3, .wav, .ogg, .webm, .webp, .flac, .afdesign, .m4a, .csv.
Feel free to ask in #community-meta if you think this is a mistake.
Hi, can anyone point me in the right direction on this? I'm using django and I have a form set up as text input and when the submit button is pressed it sends the form. I'm wondering how can I make it so that I have multiple fields to input to and send all of it as a list? I need it to be dinamically generated so that it starts with one input field and when something is entered into it, a new one opens up, or something similar to that.
Oh okay, gotcha
Does bootstrap come equipped with some tools to achieve that or would I have to dive into JS from scratch
All my experience so far has been python
I don't use bootstrap so I don't know haha. But vanilla js can achieve that too
Thanks for the help. I was gonna get stuck on this with django but it makes sense now that you wouldn't do this stuff on the backend
Hello I am using a method inside docker container, where the code is:
import logging
...
#The code here is inside a method
body = request.get_json()
logging.debug("JSON: " + str(body))
user_id = body['user_id']
room_id = body['channel_id']
channel_name = body['channel_name']
When I build the docker image, and run all the containers I get an error at "channel_name". Why do I get that in the terminal, and not also the logging.debug message with the whole json body?
i follow this vid step by step and it returns me that error:
C:\Users\SpyD\Desktop\Flask Test>app.py
Traceback (most recent call last):
File "C:\Users\SpyD\Desktop\Flask Test\app.py", line 1, in <module>
from flask import Flask
ModuleNotFoundError: No module named 'flask'```
vid:
https://www.youtube.com/watch?v=vCi2aDNXml8
code:
```py
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return "Hello! This is a website where you can find many things about python (for begginers)"
@app.route("/<name>")
def user(name):
return f"Hello {name}!"
if __name__ == "__main__":
app.run() ```
some help ๐ข
How can I use jinja2 templates in an ASGI app?
Doesn't work
But yeah, I figured it out, thanks though
python app.py
Or python3
It depends on which version you installed on your venv
You're calling only the file, specify the executor
Does anyone know the answer to my question?
Hello I am using a method inside docker container, where the code is:
import logging
...
#The code here is inside a method
body = request.get_json()
logging.debug("JSON: " + str(body))
user_id = body['user_id']
room_id = body['channel_id']
channel_name = body['channel_name']
When I build the docker image, and run all the containers I get an error at "channel_name". Why do I get that in the terminal, and not also the logging.debug message with the whole json body?
I have this problem which is really annoying i have been searching and trying for hours and i know that it's suppost to be really simple but i can't seem to get it to work and it's really annoying. I want to make 2 buttons that if you press one it prints "thing one" and if you press the other one it prints "thing two" with flask.
can someone please explain to me why this is so hard to do?
flask is a backend framework
what youre trying to do could be done with just plain html
you meant javascript
onclick
i need to do it with python?
i want a buttom click in the website to do something in python
Alternatively
You can have soemthing like
<p>{{message}}</p>
message = "hello"
if request.method == "POST":
message = "post"
return render(request, "jss.cjeksmd" {"message":message})
Ofc, the button as a form
But it's really inefficient if you want to add more stuff
With javascript you can do stuff like
.onclick and change its value / innerhmtl depending on the click
Then with javascript variables like
var message1 = {{message1}}```
thanks for the help but after hours of searching i finally got it
it's also very ineffecient but it works
The one i sent?
no mine ๐
lemmie have a look so i can add it to my mental database :)
<html>
<head>
<title>Phone Remote</title>
<style>
body {
background-color: black;
color: white;
}
</style>
</head>
<body>
<h1> EPIC DUDE</h1>
<form action="/button1">
<input type="submit" value="Go to Google" />
</form>
<form action="/button2">
<input type="submit" value="Go to yup" />
</form>
</html>```
import pyautogui as pg
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html')
@app.route('/button1')
def input():
print('yes')
return redirect("/", code=302)
@app.route('/button2')
def input2():
print('pls work')
return redirect("/", code=302)
if(__name__ == "__main__"):
app.run(host='0.0.0.0')
hmmm
atleast it works right ๐
I'm jumping back into Django after not having looked at it since 3.0.8. I've updated to 3.1 but my project now says my template files can't be found. The file is located in /users/templates/users/logout.html. Has this changed in 3.1 or have I set it up incorrectly?
One thing I noticed was that settings.py finds the base directory in a different way in 3.1. I've merged my project from 3.0 to 3.1's new set up so that's likely the cause.
that does not sound rule 5 compliant
no need to use template_name
oh its pycharm isnt it
i got confused, lmfao
@celest torrent where yyour template folder at?
Each app has a templates folder. This was working on 3.0 so I'm wondering what's changed. I figured it must be something to do with my settings.py but I can't figure how it's configured. It's probably something simple.
By the looks of the 2.1 settings.py file, I should be doing it as BASE_DIR/templates? Like how PHP templates might be done
gimme a minute, im checking one with template each app, using 3.1 as well
thanks man
seems to work fine for me, maybe its cause your using class based views, try switching to functional based views
it could also mean your settings config is set in a way django cant find your templates file, cause by default it should in each app
also send a code of your ssettings and hide the security part of things
Hey @celest torrent!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
Hey @celest torrent!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
also ferby make sure you include your app as installed appes in settings
lol
@celest torrent what was the app name again?
I dont seem to see it in settings.py
from the pastpinlink you showed me
I think thats the problem you did not include your app in INSTALLED_APPS
Tomorrow will be the start of the development for my start up's web app (MVP). I've built multiple apps for work & side projects to practice. This will be the first time i'll develop for myself with full drive and i'm all in for this (quit my job for this). The business is planned, UI/UX is designed and the tech stack is decided. Today i'd like to only focus on the product development.
While i have an idea of how i'd see this project through. I'd like to know;
- From your experience, what would you do before starting a big development project?
- What do i need to be mindful of?
- What mistakes have you made that could've been avoided from the start?
- Your pre development routine / checklist
I have 1 & half years of experience. I will be using the MERN stack. I will be building a social commerce platform (discord + shopify). I'll be developing myself for now.
which one of those should I use?
they both work well
dang sorry for my spelling, I'm bad at typing on phone
which one are you more comfortable with?
that's the one you should use
because you can do the same thing with either
thanks! I'm more comfortable with Python so yeah
no worries good luck
thanks!
Good luck man! I'm really hoping everything goes well, and u make a successful website! Don't give up, be persistent, you got this
How can I start building a web browser?(Tell the commands)
a web browser from scratch?
A home page with a textbox and a search button
once the user enters a query get the result
So I made a website for some friends of mine and hosted it on digital oceans. I can view it by going to the droplet IP. The thing is they bought the domain through wordpress. Does anyone know if it's possible to point the wordpress domain to an IP? Ive been googling around, but it been hard to find results (I'm starting to think its just not possible)
how can i put a css file in html using flask
put the css in the html file or host the css file with flask then access that url from the HTML
youd do the same for a js file or an image
like this <link rel="stylesheet" type="text/css" href="{{url_for('static', filename = 'official_login1.css')}}" />
after i open my flask i don't see any changes
also the css files are in the folder of static
did you host the css file the same way you did with the html file?
@app.route("/")
def login():
return render_template('official_login.html')
i have this to open html so i have to do the same with css?
I believe that would be the correct way. Once the html file is hosted it no long has access to the local file server. Any external files that it references, like css, js, or images, need to be hosted on the webserver as well.
ok thanks
so it would be like
@app.route("/css")
def my_css():
return render_template('official_login.css')
and in the html something like
<link rel="stylesheet" type="text/css" href="/css" />
the href might need the whole domain
i solved it thanks
raise InvalidHash()
argon2.exceptions.InvalidHash``` can someone help me fix this error in my flask app pls
Is someone here experienced with django(serializer) who can teach me a little and code 1 or 2 for me
you have to manually edit DNS settings on your droplet. https://serverpilot.io/docs/how-to-configure-dns-on-digitalocean/
Once you have created a server on DigitalOcean, you'll likely want to configure DNS for your domains at DigitalOcean.
i am trying to do a reading from database and copy it to another node so i tried to red values from the db i got result from db as a object like {obj1 :{answer:"test"}, ...goes on} i need to get the answer from that variable so i tried like
val1 = Object.keys(val)[1]
console.log(val.val1);
val is the object from db
but this code searched for val1 in the object not the one in the val1 value
how can i do it?
this is how my database is
i need to get answer for everything with a for loop
(JAVA SCRIPT)
hey guys I need help with M2M Field how to make that form within the generic form but add and delete button?
I have tried several options but none worked so far
hye guys, my flex box doesnt work properly and i have no idea why, when i display flex on the links class it works fine but i would like a container class for that, does any1 know why it doesnt work?
.container{ display: flex; top: 70px; right: 70px; justify-content: space-between; width: 800px; border: 1px solid; }
Does any1 know a website or youtube channel that theaches you the basics of creating a website with python and django?
This one is really good:
Welcome to my Channel. This channel is focused on creating tutorials and walkthroughs for software developers, programmers, and engineers. We cover topics for all different skill levels, so whether you are a beginner or have many years of experience, this channel will have something for you.
We've already released a wide variety of videos on to...
show HTM:
here you go, its running on a master page and the content is just there for design as of now
`<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>
<!DOCTYPE html>
<html>
<head runat="server">
<title></title>
<link href="StyleSheet.css" rel="stylesheet"/>
<asp:ContentPlaceHolder id="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<div class="title">
<asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
<hr/>
<div class="links">
<a href="home.aspx">Home Page</a>
<a href="home.aspx">Home Page</a>
<a href="home.aspx">Home Page</a>
<a href="home.aspx">Home Page</a>
<a href="home.aspx">Home Page</a>
<asp:ContentPlaceHolder id="ContentPlaceHolder2" runat="server">
</asp:ContentPlaceHolder>
</div>
<div class="pic1">
<asp:ContentPlaceHolder id="ContentPlaceHolder3" runat="server">
</asp:ContentPlaceHolder>
</div>
<div class="pic2">
<asp:ContentPlaceHolder id="ContentPlaceHolder4" runat="server">
</asp:ContentPlaceHolder>
</div>
<div class="text1">
<asp:ContentPlaceHolder id="ContentPlaceHolder5" runat="server">
</asp:ContentPlaceHolder>
</div>
<div class="text2">
<asp:ContentPlaceHolder id="ContentPlaceHolder6" runat="server">
</asp:ContentPlaceHolder>
</div>
</body>
</html>`
so where's the container meant to be
i deleted it bcz id didnt work but it used to contain the links div
display: flex is meant to be applied to containers
like
it doesn't cascade
i.e. a child's display attribute will not be flex just because it's parent's was
Hello everyone, I have a doubt in a Django code-along that I have been following.
I'm learning about static files and images, and the folder structure for images is root/static/images/img.png
To use this we additionally need to configure the main settings.py file and add a variable
MEDIA_URL = '/images/'
My question is, why is this url not '/static/images/' How is only '/images/' working?
how do I get these be side-by-side with either HTML or CSS
this is my HTML ```html
<div class="dashboard_two">
<div class="au_div" name="au_div">
<h1 class="au_title" align="center">AutoRole</h1>
</div>
<div class="wel_div" name="wel_div">
<h1 class="wel_title" align="center">Welcomes</h1>
</div>
<div class="mi_div" name="mi_div">
<h1 class="mi_title" align="center">Moderation</h1>
</div>
</div>
Guys, for some reason, static files aren't being served in my code
I'm using starlettes StaticFile class
And my logging is showing that everything is ok
thanks @timber basalt๐ฝ
Hi. Can someone help me to understand the meaning of decorators in CLass subjects? like @property
You could try looking into display: table or flexbox for .dashboard_two. If not them, you could set each .au_div to display: inline-block.
Yeah, inline-block is depenendant on what width they're set to. Flexbox is probably what you're looking for
@summer wyvern Not quite. This site will help
https://flexbox.help/
It's quite new so you probably want to check if your project needs to work on older browsers. If not, then it's probably good. Support for it will only get better as times goes on so it's worth knowing
What are their sizes/widths set to?
min-height: 200px;
max-width: 400px;```
also ```css
.dashboard_two {
display: inline-flex;
flex-direction: row;
flex-wrap: nowrap;
justify-content: center;
align-items: stretch;
align-content: stretch;
}
anyone know anything about django channels/redis?
So as you've npt set it to something specific, they'll change depending on how much content is inside them, e.g. the text
ok
should I change the size of the text maybe
or is there a better way
Depends on what you're trying to achieve. Do you want them to be the same width?
width: 400px for each of them
I urgently need help with M2M fields if someone can please help me please contact me.
then set the individual items to a width of 400px. if you need them to also grow, min-width: 400px; flex 1 1
yes
works
thx
how do I put spacing between them?
@summer wyvern You can set a margin
ok
try pacing: 5
Or flexbox might have something about spacing
1200px is huge for width though. most dont use that big of a resolution
for example
Yeah, this is right. You'll have to consider other screen sizes if your project needs to work on them, like a mobile. You can look into media queries to do that if you needed
so anything smaller is gonna make your boxes wrap
for a computer, aim for 800px and allow your flex containers to expand to fill larger screens.
I urgently need help with M2M fields if someone can please help me please contact me.
i know a bit, what do you need?
please go ahead
whats your question?
I have an issue with M2M form
I have explained it on this https://stackoverflow.com/questions/66126105/generic-formset-with-m2m-field-not-saving-entry-correctly
could you kindly take a look and let me know if you know what is wrong
thank you @celest torrent I figured it out!
im still not sure what any of this has to do with many to many fields. should avoid M2M though unless absolutely necessary
right so let me explain (I don't insist on those if it is possible I can do it without them)
So the Prescription can have Many LinePrescriptions
I need to have the possibilty to have one, 2 or 3 in one prescription
How would you do it with a ForeignKey I presume
@summer wyvern you should really find something besides dreamweaver to build your sites in. it causes issues. kinda likes taking control of files
so your talking 1 doctor prescribes 3 different medicines?
yes exactly to one patient
which is summed up in model Prescription
is this structure correct
or is that not necesary
from which angle are you coming from? like doctors office, pharmacy, or patient
so from a docs perspective you can use a foreign key... in django this is super simplified, but
class Doctor(models.Model):
doctor = models.TextField(maxlength=100)
class Patient(models.Model):
patient = models.TextField(maxlength=100)
class Prescription(model.Model):
prescription_doc = models.ForeignKey(Doctor, related_name='prescription_doc', on_delete=models.CASCADE)
prescription_patient = models.ForeignKey(Patient, related_name='prescription_patient', on_delete=models.CASCADE)
medicine = models.TextField(maxlength=100)
then you just write your prescriptions to the prescriptions model. one at a time. the foreignkeys have to match with the primary key of the doctor and patient models.
then you can look up all the medicines doing a reverse lookup on the patient model
I am not sure you have understood the structure
i do understand the structure. im helping you avoid many to many. when you talk 1 of anything, its a one to many relationship. 1 doctor, 1 patient, many medicines
I am still trying to understand I do believe you are on the right path
this method seems to have validity
from a pharmacy standpoint it would be easier to do m2m with a through table, many doctors, many patients, many medicines.
right
ok let me think about this. Because to change a stucture that I have implemented long time ago is a bit difficuly
I have to get my head around it
Can I use url_for inside a .css file? (flask)
background: url("{{ url_for('static', filename='background.png') }}");```
Thank you Kendal can I come back to you
when I need to ask a follow up question
yea no problem, like i said though that's a super basic explanation, but thats the idea.
Hey guys. So, i have a flask api that builds a list of object and them i should return it to the user. But i can't serialize it. Could you help me?
In my main function i have a Serialize method, so i can return a single object easily
def serialize(self):
return {"Name": self.name,
"NationalNumber": self.national_number,
"LocalNumber": self.local_numbers,
"Species" : self.species,
"Height": self.height,
"Weight": self.weight,
"Types": self.types,
"Abilities": self.abilities,
"Weakness": self.weakness,
"BaseStats": self.base_stats,
"MaxStats": self.max_stats,
"PokedexEntries": self.pokedex_entries,
"ImageUrl": self.image_url}
How can i do that with a list of Objects ?
thank you Kendal
np
How does static file serving work, and how can I implement it on my own?
im not sure what your asking, django doesnt serve static in production, i dont think flask does either. could be wrong though
I know, I looked at the source code for Flask
I'm trying to implement it in my framework
Its ASGI, so I can't use whitenoise
I'm trying to use the StaticFile class from starlette
But it doesn't seem to be serving
The GET request is going through fine
But its not changing anything
Wouldn't you just have to read the static file and return it as bytes?
basically from my understanding, a get request just passes whatever was requested back to the browser
Hm, so shouldn't I read the static file as bytes
and return the bytes
I'm not sure how to implement the StaticFile class in my use case
As starlette uses it differently by mounting it as a route
i dont know the nitty gritty of it honestly, just what i need to know. like uploads are passed as blobs to the backend. but how the backend passes to the frontend i dont know
Huh ok
I've been looking at the starlette source code
Seems like it returns an HTTP response
yes, thats basic networking. nothing to do with a server really. the client sends a packet saying hey i need this, so a server responds back with hey i have it, or hey i dont have it sorry.
i mean the server is what decides what is sent back, but your talking networking a lot more then what most know in web dev
I'm familiar with that and did try. Don't I also need to create records on the wordpress side though?
I want to build a foreignkey where I have industry ,and categories, but some of the categories are cross-named like other domain. should I use m2m or onetone or fk?
can someone help me understand what the "default 100 connection limit" in aiohttp means?
By default the aiohttp.ClientSession object will hold a connector with a maximum of 100 connections, putting the rest in a queue.
ref: https://docs.aiohttp.org/en/stable/http_request_lifecycle.html#how-to-use-the-clientsession
im trying to implement an oauth2 client with discord on a website, so does this mean that the webpage I send to an end-user could only have - for example - a max of 100 different oauth2 connections to 100 different resources?
Hello Guys, we have a project with java backend and we need something for a SEO friendly frontend. The client prefers Python. I am really fond of the idea of using Django for it although haven't got much experience (more with Ruby on Rails and PHP stuff). Do you think Django is suitable for such a stuff and does it support having a REST API behind the models instead of a database? Thanks in advance for the answer.
I think django is pretty good for seo, idk about others
Im trying to get data from serializer in react using axios but when i get data it says Error: Objects are not valid as a React child (found: object with keys {id, verified, user}). If you meant to render a collection of children, use an array instead its obvious but when i add id, verified or user then it says TypeError: Cannot read property 'verified' of undefined but its a little wired to me because it already detected the other properties but when i use them it says it doesnt exist.
anyone has experienced it?
looks like you're trying to render an object of something
are you using .map()?
true
its not collection of data
im sure its true
but i said maybe you guys already experience such thing
can you show us some code
ok let me see what can i do
The page that gets the data: ```import React from 'react';
import axios from 'axios';
class Profile extends React.Component {
constructor(props) {
super(props)
this.state = {
user: ''
}
}
componentDidMount() {
axios.get(http://localhost:8000/api/current-user/${localStorage.getItem('token')}/).then(res => {
this.setState({
user: res.data
})
})
}
render() {
return (
<div>
{this.state.user.id}<br />
{this.state.user.first_name}<br />
{this.state.user.last_name}<br />
{this.state.user.username}<br />
{this.state.user.email}<br />
{this.state.user.password}<br />
{this.state.user.verified.verified}<br />
</div>
)
}
}
export default Profile;The models:class Verification(models.Model):
verified = models.BooleanField(default=False)
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='verified')
def __str__(self):
return f'{self.id}'``` The serializer: ```class UserSerializer(serializers.ModelSerializer):
verified = VerificationSerializer(read_only=True)
class Meta:
model = User
fields = ['id', 'first_name', 'last_name', 'username', 'email', 'password', 'verified']
and of course when i check the serializer view on browser its all true
I think this would be a great time to see what your API is returning, by doing console.log(res.data) to see the format of the data.
{this.state.user.id}<br />
{this.state.user.first_name}<br />
{this.state.user.last_name}<br />
{this.state.user.username}<br />
{this.state.user.email}<br />
{this.state.user.password}<br />
I am thinking this part is fine, I think the issue lies with the data that this is trying to fetch.
{this.state.user.verified.verified}<br />
yeah you right
SEO for sure, the question here is Django and a Java Backend and using REST instead of a database. Rails has a pretty good solution for that but I think Django must have also.
its probabaly from the frontend side
console.log(res.data) so we can see the format. The 'verified' field is returning an python model instance (I think).
but wait does console.log() print the data in the cli while react is running?
no it prints it in the browser's console
oh ok
wait
its true right? ```verified:
id: 2
user: 2
verified: false
got displayed beside other objects
i event checked all of them and they all are true
How would I get this navbar button to redirect me to the home/about page
<div class="navbar-links">
<ul>
<li><a href="homepage.html">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Contact</a></li>
</ul>
</div>```
I completely forgot, would I use url_for?
I am using flask.
Because just putting the .html file in the href doesn't work
if im right you use redirect(url_for('function based view name'))
yw
what did you console.log for this output?
I dont understand what you are saying here
It was an object within the res.data object, correct?
yeah
and in that object there another object like verified: {id: 2, verified: false, user: 2}
ok the main problem is that when i want to get serializer data in frontend using axios when i set that to a state it should print all the data but the problem is it knows that the serializer has that nested serializers and can detect the properties but when i want to access the properties it says the nested serializer is undefined. i even add data to fill it but it says it doesnt exist
it sucks
what is the best way to setup onetone field automatically? https://dpaste.org/Vawv
If someone connects to flask page how to get ip of this guy?
@cinder knot <@&267629731250176001> sounds malicious
Is it possible to make an open source Django based website with limited access to database?
The reason behind this is that, there will be authentication and user data.
I can use API to hide the user data but making it open source is the problem since I will have to host it somewhere.
(I apologize for asking such dumb question)
oh boy
iirc its request.remote_addr
dont do meany head things tho
Idk man, every service now a days saves your ip, including the big FAANG, usually used for more marketing research
still i don't feel comfy w him just having my IP
or having anyone's IP
he's not a company
Discord also saves ur ip for market research
how do u know if he doesn't have a company huh
and u don't have to HAVE a company so u can be able to do market research on yoyr buisness
"anyways i've seen the mods ban people bc they talk about tracking IPs"
bruh
bruh
how can I access a HTTP-Only cookie (django session cookie) on my frontend to attach it to my request headers? It seems that HTTP-Only cookies aren't readable.
let's be explicit, so your res.data is looking like this?
{user: ...,
first_name: ...,
last_name: ...,
verified: {id: 2, user: 2, verified: false}
}
right?
If by limited, you mean requiring authentication sure. You could also hide some parts of the API and make it internal, although I'm not sure how to approach that
You shouldnt give companies a free pass at your data just because theyre companies
Hi, im looking for a python programmer for hire I need to get a bot made not a rat DM me if your interested
'bot' is quite ambiguous, is it a web scraper or somethin
@somber nymph we do not do programmer-for-hire requests on this server
@cerulean vapor okay sorry about that thank you have a great day!
how does aws handle websockets?
are u kidding me... i have a react app running on port 3000, all the auth works and django sees request.user. I make django serve my react app on port 8000, now it doesn't work
shouldnt change anything. but just so you know django only serves in development
to serve in production youll have to run a different server
most say a stripped down version of apache or nginx
Is there any way to auto delete bulma message after some time? I am using flask
https://stackoverflow.com/questions/66406505/how-do-i-consume-rest-api-dynamically-through-component
Just for fux
Can anybody help me with google maps Javascript api? i actually want to display markers on the map, coordinates are stored in a database, i just want to fetch the coordinates and some other information e.g names status etc and display it on the content window of each marker,
I got a question guys i just started learning how to code a video web chat, i did the coding as i followed the tutorial, it worked my camera turned on for me however my goal now is to make it work with another person, right now i have no clue how ,i just used nodejs, peerjs to make this work, any ideas?
Yeah. That's what I actually want to do.
Actually, the main motive of my project is to make an open source project finding website for beginners and intermediate developers where they can contribute or share their project also if they need contributions. Without much knowledge, It is very hard to find projects where someone can contribute and github explore have comparatively less filters and becomes hard to find projects.
thanks for responding. i fixed it
it's still in development, I have no idea, gonna try token auth maybe it'll be different
uhh, how is js async/await asynchronous? Doesn't await make it synchronous since we are waiting for another function to complete?
guys, I tried to follow the webdevsimplified tutorial on zoom clone but mine is not working...
const express = require('express')
const app = express()
const server = require('http').Server(app)
const io = require('socket.io')(server)
const { v4: uuidV4 } = require('uuid')
app.set('view engine', 'ejs')
app.use(express.static('public'))
app.get('/', (req, res) => {
res.redirect(`/${uuidV4()}`)
})
app.get('/:room', (req, res) => {
res.render('room', { roomId: req.params.room })
})
io.on('connection', socket => {
socket.on('join-room', (roomId, userId) => {
socket.join(roomId)
socket.to(roomId).broadcast.emit('user-connected', userId)
socket.on('disconnect', () => {
socket.to(roomId).broadcast.emit('user-disconnected', userId)
})
})
})
server.listen(3030)
this is the Server.js
const socket = io('/')
const videoGrid = document.getElementById('video-grid')
const myPeer = new Peer(undefined, {
host: '/',
port: '3030'
})
const myVideo = document.createElement('video')
myVideo.muted = true
const peers = {}
navigator.mediaDevices.getUserMedia({
video: true,
audio: true
}).then(stream => {
addVideoStream(myVideo, stream)
myPeer.on('call', call => {
call.answer(stream)
const video = document.createElement('video')
call.on('stream', userVideoStream => {
addVideoStream(video, userVideoStream)
})
})
socket.on('user-connected', userId => {
connectToNewUser(userId, stream)
})
})
socket.on('user-disconnected', userId => {
if (peers[userId]) peers[userId].close()
})
myPeer.on('open', id => {
socket.emit('join-room', ROOM_ID, id)
})
function connectToNewUser(userId, stream) {
const call = myPeer.call(userId, stream)
const video = document.createElement('video')
call.on('stream', userVideoStream => {
addVideoStream(video, userVideoStream)
})
call.on('close', () => {
video.remove()
})
peers[userId] = call
}
function addVideoStream(video, stream) {
video.srcObject = stream
video.addEventListener('loadedmetadata', () => {
video.play()
})
videoGrid.append(video)
}
```this is the Script.js
can anyone help me?
can anyone please help me?
async function f() {
let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("done!"), 1000)
});
let result = await promise; // wait until the promise resolves (*)
alert(result); // "done!"
}
f();
^ This, in my opinion, is synchronous. It's classified as async, so is it doing some other stuff in the background?
anyone guys?
what's the error?
I run the server hoping that I see another screen, but I only see myself
I don't see the other user
@opaque rivet well, if you given it nothing to do in the background, it won't do anything in the background. But try something like
for(let i = 0; i < 10; i++) {
(async()=>{await setTimeout(()=>console.log('Hello'), 100)})()
}
``` all the hellos can printed at once, so all the async functions are happening at once.
can you help me?
i wouldn't know how to, i'm not familiar with websockets or such syntax
await can be put in front of any async promise-based function to pause your code on that line until the promise fulfills, then return the resulting value.
oh, so the function f I stated before, it's asynchronous because our JS will not wait for the function f to complete to continue executing code below (opposite of synchronous). Am I understanding that right?
yes
and the code within f, could be said to be synchronous?
yes, to an extent. That is the main benefit of async, you know exactly when there is a chance to start evaluating something else that may change some global state
or I guess since f is async, all of the code within it is async because the program (in the bigger picture) is not relying on it completion
such as a databasae
awesome, thanks for the clarification ๐
since you may have a few async functions, doesn't that mean you'll be uncertain on when state changes will happen?
?
for example
async def fun():
numbers = await read_1000000_numbers_from_db()
results = [sth for number in numbers]
await write_to_db(results)
``` here you know that the 1000000 numbers you read won't change while the loop is running. await essentially means "do other things until after what I am waiting for happens"
the state will not change during line 3
unless you also include threads in the picture
i see, makes sense - and i guess async is the go-to for ajax requests to not create a backlog of requests which have to be waited on (one after the other)
yup
thank you for the explanation!
glad to help
guys, no one?
Yo! Just started learning Django. Do you guys have some recommendations on what to start reading?
I used the Corey Shafer tutorial series, as well as the official tutorial
Thanks!
when can I get my solution?
just wait on someone to reply
Hey, I am looking to implement microservices, most of them will rely on FastAPI and a GoLang framework called Fiber. I will be using GoLang to create my communications microservices. Obviously I need the microservices to talk between themselves, I found out that gRPC would be the fastest and most scalable way to do this. I have done research on how gRPC can be implemented in both languages but I cannot find anything on how to implement it with FastAPI. I will give you an example case scenario in which gRPC would be used by GoLang as a client and FastAPI as a client.
User logs in to the app through a FastAPI route, they get connect to the chat websocket on GoLang. Upon connection the user-client will send a unique session token to the GoLang websocket server, the server should be able to verify that session token so it makes a request to the VerifyChatToken() function in one of the FastAPI microservices, the VerifyChatToken() should return a bool and a new token to pair the user-token.
So there is an alternative way I could develop this, I could recode all the database models and related functions in GoLang and have it done in the microservice directly, but that wouldn't be a good approach for 2 reasons:
- It would defeat the process of microservices
- It would take much time compared to the alternative gRPC method
So my question is, how the hell do I implement gRPC with FastAPI?
[dajngo] how do i create interactive list in admin console like this
@potent wraith not sure what the screenshot shows - but your models within your admin dashboard can be customized with custom forms. Look into Django's modelAdmin class.
Hey guys, so I have this issue where my video background is bigger then the screen so it lets me scroll like this, but how do I make it so it doesn't do it and it just cuts out that part of the video if it can't fit onto the screen.
.background-video {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100vh;
z-index: -2;
object-fit: cover;
}
This is my css
give the container of that video: overflow: hidden, this will cut off any content which doesn't fit within the height/width of the parent.
is it an image or did you set the background in css? because its different for both cases
it is a video
I did it but it doesn't work, I'm going to go see if something else might be conflicting.
could it be that the parent's width is the issue (>100vw?)
Are you talking about the 100vh? Becuase that is the height
i'm talking about the width, you can set it to 100vw so it doesn't exceed the viewport
.background-video {
position: absolute;
top: 0;
left: 0;
width: 100vh;
height: 100vh;
z-index: -2;
overflow: hidden;
}``` Like this?
Because this still doesn't work, it still overflows.
Here is the html, html <section class="background-video"> <video src="{{ url_for('static', filename='assets/backgroundvid.mp4') }}" loop muted autoplay></video> </section>
I am using flask btw.
although it does work if I just set it as the background
like css background: url(video);
oh wait
๐คฆ
@opaque rivet Your first example worked, my tiny brain forgot to reload properly.
Thanks.
how can I have django session auth w/ react frontend? my requests have the X-SessionID header with the sessionid as the value, but it's still not authing. Is that right?
Hello, I'm just wondering what is the best way to accommodate for capitalisation with logins(usernames) using Flask / SQLite3? At the moment, I have a 2nd field in the DB for the username to be lowered but it seems a bit sloppy
what are you using for auth? django knox?
uh I actually just got it to work, just had to make a new user as I moved from token -> session auth. Just using the session auth out of the box, not sure what knox is.
knox does does auth, its secure
how can i serve a vue project using django?
Yo! I'm trying to use render to redirect to my index.html page, but it keeps saying that index.html is not a template. I see that I'm missing a template directory. Can someone give me a tip on how to fix this? (django)
uhh, now I have another issue, trying to delete any user within my django User model gives me a foreign key constraint. I have no foreign keys w/ my model
@molten surge add a template folder in your app directory and place index.html there
have you made the templates directory within the root folder?
alternatively, check the 'DIRS' of your TEMPLATES object within settings.py to specify where django should look for the template
I'll create one manually and let you know of the result
Thanks
Kind of sad that I installed it, wrote 3 lines of code and it's no longer working.
haha
is it an SPA? you can have django render your frontend's index.html and the rest is handled by your frontend routing.
so all i have to do is compile it and just serve the html file?
wow thats alot easier than i thought it was
yes, you'll have to go into your settings.py and let django know where to look for this file though - as technically the page it renders is a 'template'.
right, should i worry about the delimiters in index.html and all of my views/components? they're all using the default {{...}} which django uses as well
Im facing this issue
duplicate key value violates unique constraint "alfaDataId_pkey"
DETAIL: Key (member_id)=(2) already exists.
my model
class Alfadataid(models.Model):
member_id = models.AutoField(primary_key=True)
ar_name = models.CharField(max_length=100, blank=True, null=True)
birthday = models.DateField()
city = models.CharField(max_length=50, blank=True, null=True)
omma = models.IntegerField(blank=True, null=True)
bladi = models.IntegerField(blank=True, null=True)
job = models.CharField(max_length=25, blank=True, null=True)
relation = models.IntegerField(blank=True, null=True)
note = models.CharField(max_length=25, blank=True, null=True)
def __str__(self):
return self.ar_name
class Meta:
managed = True
db_table = 'alfaDataId'
the database is postgres and i set member_id as serial id
I switched from community to professional in PyCharm and I had to option to click Django from the New Project window. Added the template folder automatically.
you are trying to save an object into your database which has a member id of 2, but that already exists. this violates the primary key constraint (which implies unique=True).
@opaque rivet lemme try it
so you have an object which already has a member id of 2
you're trying to add duplicates to the database when unique=True, and you can't do that
anyone tried django channels? do you think I could create a pluggable chat software w/ it?
or any other notable use of websockets
you can use .exists() to check if something in the database already exists. e.g.
if Alfadataid.objects.filter(member_id=id...).exists():
# object exists, generate new id
else:
object.save()
thanks a lot mate ๐ I will try it
How do I make some HTML buttons change its state from being "disabled" to "active"... Here's the code block of what I'm trying to do and doing the following still makes the HTML buttons "disabled" - I don't really know where I'm going wrong :(```js
/* Fetch () call awaits the response from Flask's "/page" endpoint */
fetch('/page')
.then(function(response){
if(response.ok) {
// successfully return response object
// return response.text();
return displayImage()
} else {
throw new Error ("Oops! Something went wrong here")
}
})
.catch((error) => {
console.log(error)
});
/* Detects an onclick event on button "btnDisplay" - triggers an image display to show up */
const btn = document.getElementById('btnDisplay');
btn.addEventListener("click", displayImage);
function displayImage() {
var wrapperImage = document.getElementById("wrapperImage");
console.log(wrapperImage);
if(btn.disabled == true) {
btn.disabled = false
btn.style.cursor = "pointer"
if(wrapperImage.style.display === "none") {
wrapperImage.style.display = "block";
}
else {
wrapperImage.style.display = "none";
}
}
}
This might be beginner question but, when reading django docs I see class called UploadedFile and I don't know how to import it properly. Is it stated somewhere ?
ive never used UploadedFile, ive just used the model for upload file and gave it a path. never done anything more advanced then that
I need to do something with uploaded file via POST request so I thought this would be optimal solution
what kind of file?
.csv
im gonna give you my code for images, im assuming its identicial though.
models.FileField(upload_to=file_path)
def file_path(instance, filename):
return "/".join(["files", str(instance.username), filename])
then when you submit the blob it should upload there. not sure though, ive only ever done images
thats in you models.py file
Thanks !
instance refers to anything else that was submitted with it. i have username as a field, so i can pull it and place it in their folder. the filename is the original filename of the file, you can set it to whatever i believe
'DIRS': [BASE_DIR / 'templates'] That fixed it with the community version
Thanks guys
Hey! Is there anything noticeably wrong here? I am using flask with html/css but this file is not displaying.
{% extends "layout.html" %}
<!doctype html>
<html lang="en">
<head>
<title></title>
</head>
<body>
<section>
<h1>Hello, I am <span class="h1-name">Anton</span></h1>
</section>
</body>
</html>
I think the flask might be breaking this file but I have no idea.
I have everything that will be displayed on every page in a file called layout.html which is why the {% extends "layout.html" %} is there
such as the navbar
Hello, anyone here?
My login app
@app.route('/login', methods=['POST', 'GET'])
def login():
error = None
if request.method == 'POST':
if request.form['username'] != app.config['USERNAME'] or request.form['password'] != app.config['PASSWORD']:
error = 'Invalid username or password'
else:
session['logged_in'] = True
flash('You were logged in', 'success')
return redirect(url_for('upload'))
return render_template('login.html', error=error)
My config
import os
class Config(object):
"""Base Config Object"""
DEBUG = False
SECRET_KEY = os.environ.get('SECRET_KEY') or 'Som3$ec5etK*y'
ADMIN_USERNAME = os.environ.get('ADMIN_USERNAME') or 'admin'
ADMIN_PASSWORD = os.environ.get('ADMIN_PASSWORD') or 'Password123'
My innit
from flask import Flask
from .config import Config
UPLOAD_FOLDER = './app/static/uploads'
app = Flask(__name__)
app.config.from_object(__name__)
from app import views
I am getting an error on the login
KeyError
KeyError: 'USERNAME'
Anyone know why?
Phew, thanks Phil
@white spruce app.config[โUSERNAMEโ] is returning None
What does app.config object do?
Youโre basically saying app.config should be a dictionary that contains a key called USERNAME
But it doesnโt so itโs throwing an error
so where would I put that @round thistle because I am confused
should this fix it
ADMIN_USERNAME = os.environ.get('USERNAME') or 'admin'
ADMIN_PASSWORD = os.environ.get('PASSWORD') or 'Password123'
I assume you want ADMIN_USERNAME @white spruce
yeah
KeyError
KeyError: 'ADMIN_USERNAME'
still samething
this have been giving me problem for so long sigh
if request.form['username'] != app.config['ADMIN_USERNAME'] or request.form['password'] != app.config['ADMIN_PASSWORD']:
Print out what app.config is
I just fix it
I had to change
app.config.from_object(__name__)
to
app.config.from_object(Config)
Ah yeah. Dope
you work in flask?
Not a lot. Worked in django a lot more
why isnt there new support for django channels v3. can find all kinds of stuff for v2. but its 2 years old now
Oh
not sure
could you answer that question for me?
I am having an issue
that's if you know flask
i dont know anything about flask, im sorry. just django
okay no problem
does anyone use pychram?
please dont repeat your post, just have to wait for someone that can answer to answer
yes i do, whats up?
cuz im trying to learn Flask rn but i want to use flask_sqlalchemy but when ever i import it it says there is no such thing
and idk how to fix this rly
are you using a virtual env?
wdym?
you can open a help channel, sometimes people dont always look here der
i have the app.py file in my venv yes
does that make it in teh venv?
is pycharm recognizing your venv?
wdym recognize?
pycharm when you open it up and create the "project" should catch that you have a virtual enviroment set up. note: you can't use global modules inside your virtual enviroment, you need to install them inside the virtual enviroment
for instance, im using pipenv which creates a pipfile. when im in my project, it recognizes the enviroment and uses the modules associated with my project
ok so how do i check if it is recoginized?
right?
this?
oh yeah i didnt mention but
when i realized i woudl need sqlalchemy i decided to go to teh interpeter settings first and there i searched for SQLAlchemy but even tho i did that it still gives me the error in
from flask_sqlalchemy import SQLAlchemy
open your project, go to settings -> project<Name> -> python interpreter should show your venv and which version of python your running
looks like it recognizes it and SQLAlchemy is included in the venv
but why do i still get an error for
from flask_sqlalchemy import SQLAlchemy
your backwards i think.... from SQLAlchemy import flask_sqlalchemy SQLAlchemy is the module
you dont have this module installed Flask-SQLAlchemy your import is correct
you can use pycharm to install the correct module though. jusr right click on it
i swear to u
when i tried to fix this during teh day and tried to isnatll that it gave me an error
now it workd
HOLYYYYYYYYYYYYYYYYY
lmao it happens
lmao no your fine... pycharm is incredibly powerful. if it says it doesnt exist, right click and therell be an option to install the module.

ill keep that in mind
do you guys ever think "maybe I should be studying something over than web-dev?"
this is just a side project for me honestly
i mean do you know DS/algos?
do you know polymorph and recursion?
do you know error handling?
front end web devs can make a decent amount of money in the right company. full stack makes even more
full stack is a section of SWE
and as long as you're good at web dev you will have a company anywhere and they will be paying you the big bucks
As long as you are good and have professional experience, references, and a good looking resume*
lol
It sucks getting your first job
lol. you never know. you come up with a product and launch it, then you may never need another job. can always dream lmao
for sure
many billion dollar companies started in their garages
Id say that route is even harder, but definately possible. And at least you get to work on something you are passionate about at the same time
kinda, been learning recently. i'm liking fullstack dev just because you can sorta chase your dreams and make your idea a reality.
what does fullstack mean? using multiple languages to create something?
even if you dont make a ton, you build a network. and programmers have the potential to make a lot of money the longer they are around
and now that i do a bit more research, fullstack for me is the right route. lots of oppotunities (compared to stuff like ML) and the pay is not bad.
developing the frontend and backend
front end, backend, and ui/ux
Front end is the webpage, back end is the server, and full stack is both. basically
i've seen the salaries in the usa, for fullstack, are out of the roof
Anyone have a flask tutorial they recomend?
definitely good money in it for the right company.
learn django if you havent started, django is much more common then flask in the professional world
I prefer django personally
yeah i switched flask -> django as they had 2x the oppotunity (job listings), felt a bit obsolete learning flask
and I have used flask before, but the company I am interviewing with wants me to make an app with flask.
The starting code has an api with handlers. I'm just not familiar with the best practices for project organization
django has full built in support with rest api and channels for web sockets. plus a ton of documentation and tutorials
the flask I have don has been in one file :3
my django project is 17 different django apps :/
all the endpoints, apis, serializers, ect its insane. and im working on implementing in web sockets now. huge project. my front end consists of over 150 js files
backend is easy compared to react.
bruh anyone here familair with django mongodb ?
for some reason, mongodb db is being made on localhost only, idk why the online one isn't working
i am not. MySql is what i use
well can you then tell me how to configure mysql then
you set it up in settings like any other db, download it from the mysql page
Can anyone point me towards a guide to for the following :
In one view I want to display info from a local Django model and at the same time display data from a third party api. Iโm sure this is โsimpleโ within reason I just need pointed in the right direction.
Iโm not sure what you mean? Iโm using Django and Iโd like to display my local Django model info (which I can do) and a third party api in one html template/view.
I hope that helps.
really depends what your wanting to do.. you can fetch the 3rd party data in javascript and display it in your html. not sure how you do it in django though to load 3rd party data
import sys
from PyQt5.QtWidgets import *
class QmainWindow(object):
pass
class MainWindow(QmainWindow):
def init(self):
super(MainWindow, self).init()
self.showMaximized()
app = QApplication(sys.argv)
QApplication.setApplicationName('OmniSci: The Worlds Answers at your fingertips')
window = MainWindow
app.exec_()
can someone explain why this code doesnt open a web browser app
import sys
from PyQt5.QtWidgets import *
class QmainWindow(object):
pass
class MainWindow(QmainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.showMaximized()
app = QApplication(sys.argv)
QApplication.setApplicationName('OmniSci: The Worlds Answers at your fingertips')
window = MainWindow
app.exec_()```
@quartz yacht You could build a model to store the data from the third party api and then just display both from your models?
guys is anyone good at websockets?
Not I, but its generally best to ask away anyways
anyone?
does anyone know how to Django foreignkeys work? I dont quite understand how to connect them to their parent objects after like 5 tutorials and would appreciate it if someone reviews my code to make sure i did it correctly
In models.py, I have: user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True, )
and in views.py, I populate the field by doing:
save_data.user = get_user_model().objects.get(username=request.user)```
Is this the correct way to handle foreign keys, where it's initially set to null and then populated in the views? What I'm doing also works without issue, so I'm curious if is there's another more practical way to do this and if I'm doing it wrong.
weather.com tried to force me to turn off my ad-blocker to use their site, unforunate for them i know how to disable their css lmao
i actually do yes
well i should say i know how to do them with serializers. you have to do a reverse lookup using the related name that you set in your model
that should actually be a one to one relationship though
i suppose that would depend on if you had multiples in the table you was building. so for likes build a seperate profile table to expand the default user table, it would be a one to one. if for instance it was for a foreign key to table of blog posts, where there could be multiple blogs, it would be a one-to-many or foreignkey. which is it? be able to help better
There is one user who can have multiple models so it's a one-to-many relationship
I'm still a bit new to Django, so sorry if I say something wrong
anyone good at websockets or webRTC?
Is there any free method to turn my website from 127.0.0.1:port to www.websitename.com?
you need to buy a domain and a server, run your website on the server, then point the domain to the server.
Any web developer using flask socketio ?
Well I think you need to buy a domain
You can also use Yahoo small business for 1 year and cancel the plan before 1 year you will get it for free only
I need to integrate SAML sso in flask , anyone who could help ?
Is there anything like this php example $_POST['filename'] where 'filename' is from <input name="filename"> in django ?
uploaded files can be accessed within the view, via request.FILES
I got that result: <MultiValueDict: {}> I followed docs, added <form method="POST" enctype="multipart/form-data">
is your input type="file"?
in models.py I have
class Offline(models.Model): file = models.FileField(upload_to='media/')
so I guess thats type="file"
but if you want whole html
<link rel="stylesheet" href="{% static 'css/df_style.css' %}"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form }} <input type="submit" value="Upload"> </form>
Hi. I'm using Flask to develop a website. I want the website to have specific images according to each person (/<person>/image.svg). My main objective is to access those images from another website or file that supports HTML syntax, but the thing is that the image generates dynamically by taking data from a file. Of course, the image is generated only when you go to the specific url, but not when you reference it outside (not generated yet). How would I do this?
Okay sorry, I'm extra dumb.
hello where can I learn backend dev
?
@north summit
@native tide
@native tide
@kind steppe
@deep cave
please do not spam ping people
ok
That's scummy bro
if you use it then please tell me which version do you use and which cdn you use
hi
yeah
its shows the first 3 posts in perfect alignment
then
but after wards its keeps spoiling then alignment
what
<ul>
<li>
<div class="container">
<div class="row">
<div class="col-sm">
Blog 1
</div>
<div class="col-sm">
Blog 2
</div>
<div class="col-sm">
Blog 3
</div>
</div>
</div>
</li>
</ul>
and go on with doing this
remember each list item must contain three div
nah lol
I'm on vid โ4 and the quality of the series is unbelievable
ye, the dude is excellent
my problem is different
i am using django
okay fine
and it has to on its own show the blogs
okay alright
so i have to only set a normal format and it will shoow all blogs which are posted
okay fine bro
oh me too
Okay well whatโs the error lol
its shows python not found
what does python โversion say?
If that gives an output then you do have python installed.
Not sure why itโs not recognizing it
but i think some folder issue is there
did u run python manage.py runserver or anything of its list
if you have multiple versions of python do python3 or python2
if python is not added to ur PATH then add it uwu
is there any alternative to flask socket
Ajax
are you sure
so with ajax
can we completely replace socketio
well if I wanna make a chat app then what should I use
??
how do i serve an image with py?
like i have image a saved on my pc, and i want someone to be able to see it when they sent a get request to my domain
which module would i use
@native tide please do not spam
In django, is it preferred to extend the user class or should I just make a new model with a oneToOne relationship?
you were sending the messages with your bot? 
yes
:incoming_envelope: :ok_hand: applied ban to @tiny stone permanently.
https://docs.djangoproject.com/en/3.1/topics/auth/customizing/ this has some good info on your question
rip
Lul rip
This man thought it was a praise. Top 10 anime plot twists
he chose death huh
It literally takes 30 seconds to make your own discord "server" for testing purposes lmao
I want to make a website using django and in that I wish to add files (pdf) on the website for users to access.
for accessing the file there has to be some filters to be matched to reach that specific file after searching.
I am thinking of doing it with JSON with the filtering parameters as
Language, Standard, Subject, ...
and a Location to specify where that file is saved.
How can I implement this so that the user fills the details for file to be accessible?
Any sort of help will be really appreciated!
Note: I'm a complete newbie at Web Development and Django
do you know basic web dev? html css?
he said he was a complete newbie, so thats where he should start if he doesnt know them
Guys, I have cookie support in my application, but how I can secure the cookies?
Flask uses a secret key, right
Cookie Security for Flask Applications - miguelgrinberg.comhttps://blog.miguelgrinberg.com โบ post โบ cookie-securit...
check this out?
sorry that link sent weirdly
also if you're using SQL be careful you don't fall for SQL injections
Hm, thats with Flask though
oh you said flask uses a secret key
so i assumed you wanted flask stuff about cookies
my bad
not sure tbh i only did one thing w flask so far and i haven't even finished it yet
Make sure your cookies HTTP only, this means your cookies don't show in document.cookie thus are not JS accessible
Hm ok
How else should I secure them?
well, cookies are cookies, maybe encrypt the cookie's value but apart from that the question is how do you further secure your application
Hm
I want options so the use can secure it themselves
Its for a web framework
And how does a secret key play into all of this?
And what about session data, is it stored in a single cookie?
yes session data is stored within a single cookie, but you can always make it modular
i'm not sure how the secret key plays into it, probably something w/ encryption
yes
I am just worried about this particular part which I mentioned
ah, well django isnt super difficult
i say that as im downloading django 3 web development cookbook to learn the advanced topics of django
Hey guys, have a random Django question, wondering if I could pick anyone's brain?
If you shoot it, we'll know if it's a quick or a long way answer
Sure - I am storing an API key in an .env file, and I need to pass the key to a static JS file I have created (I am using it to add TinyMCE to my Django Admin page) But I am struggling to understand how it should be passed, if there are any good articles or something I could read or if its a simple solution I am just not seeing..
Typically you render it to the amin template that calls the tinymce setup, but it may be a good idea to handle this different
What's the surrounding context
Sorry, not sure I follow what do you mean by surrounding context? What I am using it for?
Yeah, like is it custom views, or integrated in a admin form
Also have you checked if there isn't a dango admin add on that already adds tinymce roughly like you need
I haven't checked that actually that's a good idea, I'll go do some more research
okay, this book wasnt a complete waste of time. found out how to do image manipulation in django uploads
but it still doesn't explain what i was hoping it would explain, class viewsets. dont need to learn how to display pages with django, just use django as a backend it.
erm
not really a question or something
just this
Couldn't find a channel to "report" this
@native tide probably best if you post this in #community-meta
Aight thanks ^^
nope
are you talking about https://channels.readthedocs.io/en/stable/index.html
yes, ive gotten channels to work, but im not understanding how to implement my rest api views into it. have to use this https://github.com/hishnash/djangochannelsrestframework
the channels docs dont explain it. just how to do stuff with a redis server
your question is quite vague, what do you mean by how to implement your rest api views into it?
im trying to have real time notifications from my django models. im connected, but theres no explanation on how to retrieve the results and send them back to the javascript websockets api
sorry this isnt something I can help with, it seems quite specific
specific to this particular package i mean
should be fairly basic to have a web socket long poll on a db table watching for changes. its the only package that connect to rest api. but its obviously not. lots of stuff for v2 nothing for v3 channels
out of interest what are you trying to build if u dont mind me asking?
social media site. its already built, trying to impliment real time messaging and notifications
its either front end polling or websockets to keep them up to date. and polling every 10 secs will eventually lead to basically ddosing my own server.
not really my area of knowledge tbh, but sounds interesting
hope u manage to solve ur issue
good luck
may have to just downgrade to channels v2 that has really good examples for now. we will see
to be fair ur working with very up to date versions, which is great
only downside is less stuff online for troubleshooting
asgi still pretty newish for django right?
its been around for a few years now at least because django channels is several years old now
isnโt Django ASGI 3.0 onwards only
Anyone around here familiar with apache kafka?
what do you mean?
i think its trying to move to ASGI if thats what your asking to be asynchronous. cant run web sockets without async
your actually the person i was hoping to see. i figured youve dabbled in channels
Yo anyone here have experience implementing the python-chess UCI into a web app?
Is it enough to just render the game with generated SVG?
i made my own chess ai from scratch, and i had it export board data as a .json file, then used p5.js to draw a board and load the json
its prob a terrible solution, but worked surprisingly well
it appears so
Ah nice
But
Did you use any tools to like make any sort of animation?
Best I can do so far is having a input field to enter the action like โe1e2โ and then send post request to get a new generated SVG with the new game board after the move
Terrible idea
So Iโm wondering
Hi guys I am using Django, and I am dynamically adding images (using Django Administration Models Objects blah blah), but there is a random space between two of these images(the images are of different sizes)
how do I fix this
thats practically what i did lol
Ah, so you didnโt make anything that allows you to drag the pieces or sum?
I couldnโt figure that out
nah
well my hot take is: if you have the position of where the piece is, and obv where it needs to go... so make a function that moves the pieces sprite in a linear fashion towards the destination
and just make it slow, or somthin
you get the idea ye?
I guess maybe this UCI library Iโm using probably have some sort of features like that
Not sure
prob
Image of the Problem
How do i use discord oauth2 on my website?
You have to create an app at developer portal and then select the scopes and stuff
^
I think thatโs a css problem
There should be docs for it I think, itโs similar to the google consent screen
thanks
HTTPSConnectionPool(host='www.google.com', port=443): Max retries exceeded with url: / (Caused by SSLError(SSLError(1, '[SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1125)')))
Would anyone know why i'm facing this error? i'm currently trying to ping google with proxies to check the quality of the proxies through repl.it (im building an api that uses proxies)
for discord oauth2, it sends me to the redirect url, but does not connect my account
how do i fix this?
django-channels has been around for a while, but the person you replied to seemed to be specifically asking about ASGI support in Django
which AFAIK has only been around since 3.0
and is therefore p new
asgi support for channels has been around since at least 2017 according to the docs. so by no means new. channels v3 is new though.
well im slowly getting closer to things working. can at least pull data through the websocket. although im still manually having to call it instead of it automatically passing it to me on update
huh
I mean Django compatibility with ASGI
what's the simplest way of handling a user session in a secure way? Should I just use a cookie? I wanted to use JWT and send it thru the header, but I've been finding it to be a challenge to handle these kinds of requests/responses on the client side. Im using vanilla code and micro frameworks too. Any suggestions?
So far Im using bottle, jinja2, and sqlite3 for deps. No node or js deps, but I implemented my own ajax. Just wanted to bohnce ideas b4 I make any major modifications to code.
Im really new to any sort of web dev but i have the following problem in Django:
{% extends 'main/base.html'%}
<!-- This like gets everything from the BASE HTML file and lets me add onto it -->
{% block raw %} Login {% endblock %}
<!-- this basically allows me to change the name from the BASE HTML file -->
{% load static %}
{% block content %}
<html>
<!-- This is how I edit custom things on top of the base HTML page. -->
<head>
<link rel="stylesheet" type="text/css" href="{% static 'css/login.css' %}">
</head>
<tag>
<input type="text" placeholder="Enter Text"/>
</tag>
<body>
</body>
</html>
{% endblock %}
```HTML CODE
h1{
color:orange;
}
.tag{
width: 100vw;
height: 100vh;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
font-family: sans-serif;
font-size: 16px;
}
input{
width:200px;
height:30px;
}
CSS CODE
The question that I have is how do I get the .tag working. I can't use the body class as it is already used by my navbar
.tag is a css selector where you have the tag element
If you want to apply it as a class, use the prefix ., and then add class="tag" to the tag element. Another way is to just select the tag element directly, but this would apply it to all tag elements
@marble spade so all you have to do is <tag class="tag"> and it should apply the css
how do I print the output?
@marble spade not sure what u mean
You asked how to get the css applied to the element, so that's what I replied to
I think the certificate might be invalid or something
at the top of the browser next to the URL (on the left) there is a lock. click it and click certificate
send an image of what it looks like
@native tide
its saying the certificate is invalid
thats not code
<html>
<b>
Coming soon...
</b>
</html>
i am
it should look something like this @native tide (this is discord's one)
i have other websites that dont look like that
hmm...
i think discord just has a ssl from cloudflare?
you have to change your nameservers to cloudflare's after you add your site to it, then it takes a bit for it to load depending on your domain provider
i think
i have...
maybe just host it using something else
like 2 days ago
k
whats zoru
link?
alr
Hi, I have a css file linked to a html file, when I look at the console I can see a request been sent to the css file (from the terminal) but the response status is 404, i am using django, thanks
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '('') from register WHERE Email=''' at line 1
can someone help me
how do I log into my admin page on Django? Where do I find the username and password?
You have to run ./manage.py createsuperuser to create your first admin
yeah got it, thanks
I've got the following HTML which is just a form (label, input).
Currently the user can't continue a text selection across to the label from the input and vice versa. Is there anyway to allow this?
<form>
<label name="Header">
C:\Users\user><input type="text">
</label>
</form>
Like this for example (cobbled it together in paint.net)
Guys, has anyone worked with integrating onedrive javascript file picker to a web app?
<input type="text" placeholder="Enter text">
{{form.email.label}}
{{form.email}}
How do I merge all of these into one?
thats what it looks like right now
and I only want it to display Enter Text
your above code doesn't look like proper html
and proper use of the django template syntax
uh what do you mean
i don;t know what your code looks like but atleast start with something like
<div>
{{form.email.label}}
{{form.email}}
</div>
and see what it looks like now it will maybe still not what you look for but no it looks like your generating 2 input fields
i'm not sure why the CSS auto updates as it's a div
anyway
@polar trellis is there a way for me to say: Username inside of the input field?
yes look into the django docs for widgets in your model
to adjust the html code that django will generate
ok thanks I will have a look
maybe in your model username definiton you will have to add something like:
widget=forms.TextInput(attrs={'placeholder': 'Username'}))
but it will depend on how you defined your username in the model
or in the form.py you could add it in the Meta class
^^^ Thanks
did you read through: https://docs.djangoproject.com/en/3.0/howto/static-files/
did you know why this dosent work?
from bs4 import BeautifulSoup
URL = 'https://www.finanzen.net/devisen/bitcoin-euro-kurs'
page = requests.get(URL)
soup = BeautifulSoup(page.content, 'html.parser')
results = soup.find(id='content')
print(results.text[2606:2607])```
Anyone know a secure passwort hash for login and registration. I want to make it secure as possible
If I had to take a wild guess here:
results = soup.find(id='content')
@carmine terrace maybe look at the output of your soup variable it could be that your hittinh a captcha
Hello anyone know how to solve that Attribute error while web-scraping?
so if you also are hitting a captcha you either will have to play around with the headers of the request of switch to selenium to try if that gives better results
Traceback (most recent call last):
File "g:\KekBot\auslesen.py", line 9, in <module>
print(results.text[2606:2607])
AttributeError: 'NoneType' object has no attribute 'text'
PS C:\Users\User> ```
that is not your soup variable that is your results var
hello, im having some issues when setting an image as background.
and please don't post the output of the soup variable here it will be long, just look through it and see if your hitting a captch
there is no captcha
im setting an image called Backgroud.png as a background of a div. But when i open the page it doesnt show the image. The image is in the right dir.
image: home/container/Resources/Pages/Background.png
page: hom/container/Resources/Pages/index.html
The html file for the background image is
Background.png. Why wont the image load?
@carmine terrace also your looking for an id content when i use my browser to go to that page i cannot find an element that has an id with content, there is an element that has the class content is that what your looking for?
i used an other code with an api and know it work. thanks for help
This is what I thought originally too
hey. im having an issue when loading a background image. The image is not loading
im setting an image called Backgroud.png as a background of a div. But when i open the page it doesnt show the image. The image is in the right dir.
image: home/container/Resources/Pages/Background.png
page: hom/container/Resources/Pages/index.html
The html file for the background image is
Background.png. Why wont the image load?
can someone help me how can i get the output of the following code like this: 40000,00โฌ and not like this 40000โฌ?
import cfscrape
scraper = cfscrape.create_scraper()
url = 'https://api.cryptonator.com/api/ticker/btc-eur'
cfurl = scraper.get(url).content
data = json.loads(cfurl)
price = data['ticker']['price']
rounded = price.partition('.')
print(rounded[0])```
so that the code is displayed with 2 decimal places
!d round
round(number[, ndigits])```
Return *number* rounded to *ndigits* precision after the decimal point. If *ndigits* is omitted or is `None`, it returns the nearest integer to its input.
For the built-in types supporting [`round()`](#round "round"), values are rounded to the closest multiple of 10 to the power minus *ndigits*; if two multiples are equally close, rounding is done toward the even choice (so, for example, both `round(0.5)` and `round(-0.5)` are `0`, and `round(1.5)` is `2`). Any integer value is valid for *ndigits* (positive, zero, or negative). The return value is an integer if *ndigits* is omitted or `None`. Otherwise the return value has the same type as *number*.
For a general Python object `number`, `round` delegates to `number.__round__`.
Note... [read more](https://docs.python.org/3/library/functions.html#round)
I read it but I wasn't able to fix my problem
is django throwing any error/log about the 404? and how does your html line look like that contains the link to the css?
value = 40000
print("{:.2f}".format(value))
# '40000.00'
print("{:.2f}โฌ".format(value))
# '40000.00โฌ'
A general Question... We use Flask at my organization, however I think I see more companies using Django. Is Django more popular within organizations? To be clear, this is not a question of which is better, only which is more popular within companies. Thank you in advance for your answers. ๐
Django is indeed more popular
it may be easier to convince exec into using it, since you can say IG uses it
tbf i would say they're about equal now
hi there, is it the Django standard to have a huuuuuuuge models.py?
still not 100% sure, ASGI means its async, WSGI is not. cant have web sockets without the server be async though, cause it would only allow one connection at a time.
you can set it up so your models.py is split among your apps. doesnt have to be all in one fille.
i see, but is it the standard? i've seen more django projects with 4k loc in models.py
thanks anyway
so you think that models should not include any logic (basically methods)? just fields?
it contains field related logic, constraints, field set ups ect. but most logic is handled in views/serializers