#web-development
2 messages ยท Page 140 of 1
Yep, thanks
so what files do u need
in your website
static or media
all websites should have static
for templates
I think media, because I want a user to upload their pfp
Ok
create three new folders in the same directory as manage.py
static, static_cdn, media
!discord
u can try learning with a project
i would recommend python crash course
there are three projects at the end of the book
then @wooden ruin
you will have to set some constants in settings.py
STATIC_ROOT = '/static_cdn/'
Ok
anyone know why this is throwing this error?
async def changeStatus(self, messages, recipient, **kwargs):
for pk in messages:
message = await database_sync_to_async(get_object_or_404)(Messages, pk=pk)
try:
if message.recipient.id == recipient: #Error stems from this line. which isnt a database call. so idk
await database_sync_to_async(message.changeStatus)()
await database_sync_to_async(message.save)()
else:
raise ValidationError("Only recipient can modify seen field")
except TransitionNotAllowed as e:
raise ValidationError(e)
return {}, 200
error:
django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async.
completely solved it for anyone wondering. if you have a similar question i can answer it
You could post it here, in case someone runs into the same thing
they do, you can render pages on the server side with flask and django and return a complete HTML code to the user
but what you want here is not that but rather simple API where JS front-end sends a request to python's back-end, receives a response and processes that response, maybe incorporates it in the page
Yeah I think this is exactly right
What JS library should I look into for that?
XMLHttpRequest is the object you can work with
to send and receive responses
from JS context
does flask handle concurrent requests automatically, or do I need to handle that?
For example:
if 10 users are signing up at the same time
and 10 customers are placing an order at the same time
Will flask handle this automatically?
I'm trying to figure out typescript. How do i make tsc emit imports that browsers understand and so they have correct paths not just for tsc, but for browser :D? And how should I collect used libraries from node_modules to a location where they're available to get. Can someone link me to a good read, please? ๐
Hello! Does anyone know if you can use github pages to host a site that uses flask / other back end functionality? I know it's for static sites, but I'm still not 100% sure what that means, exactly.
Lesser flask and more the webservee you're using but yes something like gunicorn should support concurrent requests like that, if youre concerned about the amount of concurrent requests you can look at gevent to improve flasks async ability
Static only so no dynamic backend
okay thanks will look into gunicorn
can django create schema automatically if not exists?
you can host your backend on heroku
Hi guys, may I have a Django related question here? I am working o a website where a user can register their own organization and i use a slug field in the Organization model. The slug field is based off of the name of the organization so the name must be unique on a website. Now it's simple to create a form to register an organization but what about when I want the user to have an option of editing it? If I instantiate the form with database data and submit changes only in any field but the name field, I cannot submit it, because, obviously, the name exists already. How do I deal with editing an existing database record where there is a field with unique=True and I am not changing the value of that field? Thank you!
Do I have to create two separate forms just for that?
@lapis heron in your view, you clean the form, search the entry from the database, update it and save the changes
@lapis heron something like this:
def update_org(request):
update_org_form = UpdateOrganizationForm(request.POST)
if update_org_form.is_valid():
org_data = update_org_form.cleaned_data
organization = Organization.objects.get(name=org_data['name'])
organization.address = org_data['address']
organization.save()
also make sure the org you're retrieving belongs to the user otherwise other users can edit other org
maybe add another filter:
organization = Organization.objects.get(name=org_data.['name'], user=request.user.id)
Wow such an elaborated answer I feel like I don't even deserve it, haha. I think this will work. Thank you so much!
you certainly deserve better ^^, that's the spirit of this community, you're welcome ๐
s the g
Just tried it. Works like a charm!
Hello i m using flask dance for discord oauth
But i have an error
https://bin.readthedocs.fr/lsphan.py
What is wrong ?
A simple pastebin
how do you write PrimaryKeyRelated serializers in DRF for threaded comments?
Best place to host a python flask app? Heard pythonanyhere is good.
app = Flask(__name__)
@app.route("/")
def home():
return "Hello, this is my first website! <h1>HELLO<h!>"
if __name__ == "__main__":
app.run()``` it can't connect
i deployed my django project but i have a problem about django's admin panel. admin panel has not css. how can i fix?
i need help
:((
did you deploy your app behind an nginx server ?
maybe you missed to collect static ?
python manage.py collectstatic
what does that mean?
should i write this in putty?
ok, first of all how did you deploy your app and where ?
i deployed my project on cpanel
in python app
actuall yweb site has no problem, just problem is admin panel has not css
I'll send photo to you
hey, does anyone have an experience connecting to a docker mysql image from a django app in the same container and can answer a few questions?
I suppose that's more suited to #tools-and-devops
thank you ๐ I will ask there
Is it possible to live stream terminal output from python script over to a Flask website with no javascript?
app = Flask(__name__)
@app.route("/")
def home():
return "Hello, this is my first website! <h1>HELLO<h!>"
if __name__ == "__main__":
app.run()``` it can't connect
what error does the terminal show?
There is no error
Thats the problem
But i use repl.it is that a problem?
"live stream terminal output" What? You mean like auto update something in the terminal? @regal sparrow
would this approach involve setting up a separate server?
Because the optimal solution for me would be if I can have a .py file in my chrome extension's folder (alongside my html, js and json files), with functions on it that I can call from a js file
but i don't know if that's even possible
that is very unpopular
thing to do
even if there is a way I've never seen anyone actually go down that road
before
i dont remember what was your original question but python on server-side and JS on user side
is how you should proceed
and no you dont need another separate server
given that you do have 1 already that serves JS, HTML and CSS to users
when they access the website in a browser
ok thx
because basically i've coded a big portion of my project using modules and api in python
which i don't think exist in js (and if they did it would take a long time to recode it)
so i've already packaged up all the code i would need to run in this extension into 5 or 6 python functions
Hi guys ๐๐ฝโโ๏ธ
^^
So I'm having a little difficulty from a task a friend gave me for his UI
that is not something i have seen anyone do
JS is not a hard language
it really isn't
if you know any language well enough
such as python
the issue isn't so much difficulty, but that i don't think the apis and modules i have used exist in js
I need to find a way to code this out
could you give examples
of particular python snippets
Hi
It's something I want to implement in the UI of a web app
My friend's though
anyone here
i forgot, how do i move navbar items in bootstrap to the right?
default is left
How do you get the name of the webbrowser that someone is using
I tried looking as os docs but I found nothing close to it, I also looked through webbrowser docs and found the same thing
anyone?
i dont know bootstrap sorry. i build my own css
well from what im reading, its hard to get the browser without 100% certainty, but theres libraries out there that can guess at it
ah now i know it didint work, its removed in bootsrap 5
hello any styling good guys here
basically i have a glass class which is a blur class
but when i try to make it responsive
the glass doesnt render / extend with the screen
any solutions?
from flaskk import db
from datetime import datetime
class Doctor(db.Model):
id = db.Column(db.Integer, primary_key=True)
doctorname = db.Column(db.String(20), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
password = db.Column(db.String(60), nullable=False)
image_file = db.Column(db.String(20), nullable=False, default='default.jpg')
total_patients = db.relationship('Patient' , backref='doctor' , lazy=True)
def __repr__(self):
return f"User('{self.doctorname}', '{self.email}', '{self.image_file}'), '{self.total_patients}'"
class Patient(db.Model):
id = db.Column(db.Integer, primary_key=True)
patientname = db.Column(db.String(20), unique=True, nullable=False)
dob = db.Column(db.String(20) , nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
password = db.Column(db.String(60), nullable=False)
image_file = db.Column(db.String(20), nullable=False, default='default.jpg')
doctor_id = db.Column(db.Integer,db.ForeignKey('doctor.id'),nullable=False)
def __repr__(self):
return f"User('{self.patientname}', '{self.email}', '{self.image_file}')"```
hi i create the model in which doctor has multiple patient
i create doctor first
then create the patient during creating patient i pass doctor.id
but when i run doctor.total_patients it give me null
How do I link a js file to my html?
Hello everyone. I've learnt the python to do this github project but I know the calculations and only thing that I didn't success is how do I visualize the results like in this example.
https://github.com/EmilienDupont/openPitMining
GitHub
EmilienDupont/openPitMining
Open Pit Mining example with Gurobi. Contribute to EmilienDupont/openPitMining development by creating an account on GitHub.
He uses the Gurobi optimization library for optimization but how did he do this interactive webpage which it calculates the bloks according to economic values and produces the bloks from surface to bottom of pit
my question is what should I do to do webpage like this working with python and What should I learnd to do this
thank you
Bit late, but:
<head>
<script type="text/javascript" src="the-script-file.js"></script>
</head>
alright thanks
one doubt, does it matter where is script tag? like in head or body or at the end of body
CORS question, I'm using Flask-cors and it works fine if the origin is *, but as soon as I say localhost it doesn't want to work.
I moved from
CORS(app)
to
CORS(app, resources={r"/*": {"origins": 'localhost'}})
What am I missing?
is django the only option to develop web servers?
what do u mean by making it responsive
when you do width: 60% you literally say that the width will be 60% of the total width it could be, if that's what you want for wider screens you can use media queries and remove it for smaller screens
https://www.w3schools.com/Css/css3_mediaqueries_ex.asp
like only with python or in general?
only python
Flask is also an option
Flask can be used for quick and simple apps whereas django for complex ones
I am trying to access my media files in deployment mode and im using whitenoise for static files. is there anyway to access media files or it automatically detect the medias on debug false?
Thanks, but i already fixed it
can someone help me with modeling a restaurant menu
menu might contain something like this:
Veg: -> Meal
-> others
Non-Veg ->Meal
-> others
how should i approach creating the model?
you can create two model with different names likeVeg and NonVeg then create two other models one related to Veg model and other related to NonVeg model for others part like VegOthers and NonVegOthers
Hello everyone. I've learnt the python to do this github project but I know the calculations and only thing that I didn't success is how do I visualize the results like in this example.
https://github.com/EmilienDupont/openPitMining
GitHub
EmilienDupont/openPitMining
Open Pit Mining example with Gurobi. Contribute to EmilienDupont/openPitMining development by creating an account on GitHub.
He uses the Gurobi optimization library for optimization but how did he do this interactive webpage which it calculates the bloks according to economic values and produces the bloks from surface to bottom of pit
my question is what should I do to do webpage like this working with python and What should I learnd to do this
thank you
I thought of that initially but u see I also have other items and there will be too many models
thats normal
how about this approach
Create a model defining each items type like veg non veg drinks and so on
another model which will refer to the above model and then contain items?
is there a way for me to give options only after certain type are visible
it seems that way i would be able to select veg pepsi lol
i think that i didnt get you cause about what was i thinking if you add a field imagine a boolean to choose its a veg or nonveg(is it what you wanna do?) it wont work cause this field will be related to a model maybe veg items will be different from nonveg items
no no there will be many types like drinks, veg, non-veg if it was only veg and non-veg than a boolean would have been enough but it is not the case here
it seems multiple models is the bet choice of action lol
thats the only(the best) option
if i try to confine them into little models i would need to add validation and that's tedious
thanks @nimble epoch dude
may i contact u on dm if i need u as a devil's advocate to my thinking?
for what i dont know but YOURE WELCOME ๐
im stupid as f...
i dont know what did you like lol
i just converse with myself and get the answers lol
being an extra view certainly helps
good
Will all websites be WebSockets in the future?
no because that would suck on so many levels
but real time updates
We used to have flash ads on every page and pop-ups. Now we have auto-playing videos on every page. What's so bad about WebSockets for actually useful updates?
and pop-UNDERS!
I'm saying the web has always been filled with junk
web sockets are only really used for systems where it needs 2 way communication
but generally websockets are likely to be phased out as http developments go on
things like HTTP/2 already offer Push that can do the job of websockets, http/3 adds another layer ontop of that
Is HTTP/2 push commonly used?
On most large scale websites yes because it's significantly quicker for loading times
but that depends on if the server support HTTP/2 or not
and whether it directly supports push or not
which at the moment a decent amount do support HTTP/2 but the majority do not
Is HTTP/2 push used to send like XHR updates, or only eagerly load assets?
can be
most browsers default to use HTTP/2 now
and by most i mean all modern browsers use HTTP/2 now
Are there any popular HTTP/2 servers in Python?
damn I started learning the wrong language for writing backends...
I mean just stick it behind Nginx
unless its a large server eco system it generally wont support http/2 yet
just because its so freaking impossible to get accurate info on how to setup a http/2 compliant server
I want to send real-time updates to the client as my server processes something in another thread
I mean you can just us a WS for that 
WS = WebSockets? I thought you said it was old news and everythings HTTP/2 now
Everything is moving towards HTTP/2 but its still along way off
websockets still have their usages in regards to real time updates
Maybe I should start working on HTTP/3 so I'm not behind on the times
I mean you can try
but i mean good luck lol
at the moment its pretty much still a google only thing
Is letting Google control everything about the web really a good idea?
i mean they already do
but http/3 was a collaboration aspect, they just implemented it in chrome first
nothing will really support HTTP/3 for maybe 5 - 10 years or so im guessing
alot of QUIC tests exist, python surprisingly supports it but that was mostly before the api started stabilizing so there's a decent amount of in-compatibility
sounds like a mess
it is
HTTP/2 is hard enough to get decent info about how to implement it
HTTP/3 is just... a yikes
its a good idea but seems like everyone's sorta forgotten to actually make the docs to allow devs to implement their system
Looks like there is a framework called Quart which lets you write websockets easily and might even handle HTTP/2: https://gitlab.com/pgjones/quart
Flask uses threads, whereas Quart uses an async event loop?
When did browser js modules start coming to browsers as a feature?
quart uses the asyncio event loop
Flask is sync or async depending on it's worker type
most companies deploy flask with something like gevent as it gives you async performance without any extra effort
i've found Quart to also not really be any faster than Flask's async system and certainly found it to be a bit weird server wise just getting it to work properly
Quart supports HTTP/1, HTTP/2 and HTTP/3 ish and WS, but the framework itself doesnt really give the advantages of the newer protocols because it just bottlenecks so hard
For small applications, having some WebSockets is better than nothing. But that sucks to hear
What does Flask use by default?
A pool of threads that it sends requests to?
i disagree tbh, most applications have no use for websockets, they generally do nothing good for the server other than make a complicated state system to try scale
oh that's right Flask uses Werkzeug by default
werkzeug is a development server and WSGI handler
its not a production server
Flask just interfaces to WSGI
then any other WSGI complient server can run it
e.g. gunicorn, meinhead etc...
Is gunicorn the most popular way to run Flask in production?
guys I need to create setting objects with one to one key as soon as a user is created . I tried it using django post save signal, but since settings has some default value user objects in settings is not getting created . is there any alternative way I could achieve it
I don't really understand what WSGI is, or how these different servers interface with Flask. Do you know any article that explains it?
Hey is it wise to seperate a chat database (Firebase) and flask API server?
WSGI is the foundation of most Python web frameworks, but there's a good chance you've never had to interact with it directly. In this talk we'll explore why it exists, how it works, and what the heck it's doing in your stack.
A great web framework abstracts away all the low-level stuff so that you can focus on the core functionality of your ap...
Thank you!
Javascript is quite the confusing can of worms. Makes me very grateful for PEP8 and Python, it seems super messy to me on the face of it ๐
Im introducing a chat room onto my app. Is it wise to seperate the chat storage (Firebase) with my node, mongo backend
I am writing some custom authentication in Django. What kind of exception should I be raising to signify malformed authentication?
Hey guys, I'm making a flask app. Runs fine on local machine but can't access from other devices on same network. I've put the host as 0.0.0.0. I'm on linux and ran sudo ufw allow 5000 but no luck
Any ideas?
Can you ping your PC from other devices on the same network? Might be Windows Firewall or another firewall is blocking it
I'm on linux and ran sudo ufw allow 5000 that should've taken care of firewall?
Dunno. But it's probably a firewall issue if it's not an interface issue
Just pinged from another device, says destination is unreachable...
So it's blocked... What do I do?
gotta figure out what's blocking it and where. Could be your router. or you might be on a different subnet
Is your local ip like 192.168.1.X?
check that your device has the same 192.168.1.X
Yeah its 192.168.1.X
On your other device, what address are you typing into your browser to access the server?
you should type in http://192.168.1.10/ or whatever the server's local IP is
That looks right
unreachable. I think if it were a firewall you'd get connection refused?
I'm not very good at networking.
Is it a good idea to stop the firewall altogether just for now?
Anyways, thanks
Hi guys, what is in your opinion the best practice for auto-populating slug fields while preserving their uniqueness? How do I avoid duplicates in my database and performance issues related to that? I don't want to expose auto-incremented id value in the url because I find it obsolete. I saw some solutions like combining slugs with date_created or attaching some random string at the end like some kinda hash. Currently I auto-populate a slug field of my model Organization based off of 'name' field because I set it unique=True (when You have an organization that someone registered already, you are screwed) I don't expect it could cause any trouble because I don't expect that there will be many organizations registered with the same name. I do expect that with a model Course (courses provided by the Organization). Thank you!
easy option, covering all of your bases:
https://pypi.org/project/django-autoslug/
alternatively you can use django signals to create random slug values (using django's get_random_string()) and looping through possible slugs until one is available (which can be found by using django's Model.objects.filter(your_kwargs).exists())
can someone help? flask isnt updating the image (as seen in the bg)
nvm i fixed it
@app.after_request
def add_header(response):
response.headers['Cache-Control'] = 'public, max-age=0'
return response```
Thanks! Haha I actually already started using it just wanted to know about someone else's opinion.Thank you ๐
Hey, this is a very weird question.. I'm wondering what the best way to go about hosting a local blog for personal documentation would be... I don't really want to code it from scratch given that it would be a lot of work (and i'm not super good at web development yet). I have a raspberry pi 3 that I would host the actual site on. I just want to be able to host it locally, and post to it for personal documentation reasons. I appreciate any info/tips.
Using python?
You could also find a free bootstrap doc template and just host it on the pi after you edit it?
Doesn't have to by python. Sorry, should have specified.
flask-socketio.emit can broadcast a message to all connected clients even without specifying the Broadcast=True argument ?
seems to work in my case
dont understand why
does this look modern enough? its a pop up menu
I'd say so
trying to get rid of my dated looking stuff in my site. its what i threw together last night in an attempt
Yeah, looks good mate
well good deal. gotta a another small form to do it too now as well. figured id check in before making another form look similar
I'm of course only one opinion but yeah, I'd say it looks up to date with everything I've come across
i think it looks nice as well, but if you seen some of my older CSS designs you wouldnt trust my design skills
Lol. Well the only web design exp I have is editing html from the days of myspace, so I'm sure you're leaps and bounds beyond me ๐
@eveyone can you save progress on python before you close it
I use Visual Studio and you can save with that client
hey thats where i started myself. build myspace pages for people
Lol, yep! Used to be my high school side hustle to make some money
i use pycharm it autosaves on keystroke
it was Blogger for me
and I had no idea what I was doing
๐ฅด
lmao. i only knew how to edit back then. not actually write it. but we all had to start somewhere
lmao notepad thats where i started. didnt get dreamweaver for several years. but the stuff now is even more advanced then that
those inputs looking better for you lmao
What is the language that makes buttons in a web page do stuff?
I want to get into frontend
Javascript
depends what your asking. a form is passed to the backend onSubmit. now you can make buttons do different stuff, thats front end and javascript
In Django how do you pass a variable to a view?
For example, I have a view that displays basic info from a model. I want to take a piece of information from the model- say customerNumber and pass that to a url in a view to pull an outside api and display this results.
Yeah Javascript
Thank you
Is there any course you guys would recommend to how you can use it in Web Development
Django for beginners
Django for professionals
Django for APIs
I believe you can just do:
var.customerNumber
this will display that data
And "var" being the specific model being get
and with the data, you can just turn it into text and use it to request data off an outside api
uThanks
flask v django
Hello everyone. I've learnt the python to do this github project but I know the calculations and only thing that I didn't success is how do I visualize the results like in this example.
https://github.com/EmilienDupont/openPitMining
GitHub
EmilienDupont/openPitMining
Open Pit Mining example with Gurobi. Contribute to EmilienDupont/openPitMining development by creating an account on GitHub.
He uses the Gurobi optimization library for optimization but how did he do this interactive webpage which it calculates the bloks according to economic values and produces the bloks from surface to bottom of pit
my question is what should I do to do webpage like this working with python and What should I learnd to do this
thank you
django will take you more places
HELP !!
TLDR: Way to Migrating Users from One Django Project to another
Context:
I have a Django website, which was initially written using django's default template engine. Later on I decided to update the website, finding something different for the front end. Hence I created a new django project (DRF) that connects with vue front end. A different project all together. So, I currently have users in my initial project. But, the new project doesn't have them registered. I want to migrate the user credentials from one project to another. So that the current users does not need to create a new account.
Problem:
The password are hashed, so when I export the user's credentials from database they are hashed. I was wondering if there is a way to add users to django using already hashed credentials.
Hey guys, I am a beginner - intermediate programmer and I want to web scrape my teams attendee list to compare it with a complete list so that I can find out the absentees.
Can someone please guide me through BeautifulSoup and the html as I am not very faimliar with it?
hello guys ..
how to work with jsonfield in models(mysql) in django 2.2
Yo! Is there a way to make the redirect function redirect to a new domain? Like Google or Youtube? Django
When I try to redirect to youtube it just adds www.youtube.com to the back of my domain [localhost:8000/something/www.youtube.com]
You need a full url for that
Otherwise its redirected relative to the current url (just the nature of http redirects)
Hello everyone. I've learnt the python to do this github project but I know the calculations and only thing that I didn't success is how do I visualize the results like in this example.
https://github.com/EmilienDupont/openPitMining
GitHub
EmilienDupont/openPitMining
Open Pit Mining example with Gurobi. Contribute to EmilienDupont/openPitMining development by creating an account on GitHub.
He uses the Gurobi optimization library for optimization but how did he do this interactive webpage which it calculates the bloks according to economic values and produces the bloks from surface to bottom of pit
my question is what should I do to do webpage like this working with python and What should I learnd to do this
thank you
You mean like put https:// and so on in front of it?
Yup, that worked. Thanks!
when is node js better to use than python for the backend?
@dapper tusk cheers. Doesn't Python handle SSR great with templating though?
templating yeah, but if you are using something like react for an SPA, you can't really render that in python (though there are packages for that as well I am sure)
ah wasn't aware of a way of doing it for SPAs. I'll look into that thanks ๐
heya, im trying to add Arc.io to my website but I dont really know how to serve the JS file so the application can read that file
it was a application/javascript header
Hey there, I am uisng django to develop a web app and I wish to implement this functionality where only the registered users get option for login using google oauth, has anyone implemented this?
are media quaries actually useful to make your website look good on mobile as well as desktop becuase when i make two media quaries one for desktop and one for mobile, if i change lets say the padding on mobile it also changes for desktop
becuase i dont know any other way to make it also look good on mobile
you want to work with media queries because they are one of the best ways to make your website responsive. however css frameworks like bootstrap/bulma are based centrally around making your website responsive and make developing responsive web pages much easier
hmm ok but how would i change it so if i have 2 media quarries, one for mobile and one for desktop, lets say o change the padding of something how do i stop it from changing the padding of the other media quary
if that makes sense
you can overrride the rules in each media query
how do I debug client javascript with vs code? basically, I have a python app running locally, if I click a button, that would call JS. how can I set a breakpoint in vs code and catch that client side js?
when I set a breakpoint it doesn't get caught
wdym lol the rules, sorry im new so it might be a dumb question
like if you have body { padding: 40px; } on a desktop, you can change it in the media queries for mobile to be body { padding: 0;}, which "overrides" the existing css style rule in place
yea when i do that it also changes the padding in the other media quarry for somereason
body{
background: #161614;
width: 100%;
overflow-x: hidden;
}
.title{
position: relative;
top: calc(1em + 1em);
left: calc(20% + 21%);
color: #BABA1E;
font-weight:lighter;
font-size: 4rem;``` this is the desktop one
if i change it on a nother medi aquarry than it changes this one to
Yo! Is there a way to style my url type field to look just like the text field?
When type is text it looks okay, when I change it to url however it changes its style
im trying to get the value from the select tag but it says "none". could someone please help me out?
flask
could someone help me really quick its probably an extremly easy fix
this is my first try at making the structure
one second
i dont know why there is a gap over box 1
cant figure it would appreciate help
@lime fox can u remove the AAAAAA part from box 2 and check
that did actually fix it thanks
how do i put text in the boxes without messing it up again? @red aspen
i see in ur css that u used the tag as selector, maybe give both divs a dif class and style them accordingly
and target them by class names
i had 0 knowledge of html prior to this im not sure what you mean exactl
im not really into html and css ๐ so im not an expert
ah i see
can u dm me ur code?
im not an expert as well ๐
yeah one sec
hi does someone here do webscrapping with python
Yeah
could you help me a bit?
my code is too slow to use
so I try 50k login IDs
to get 1 single data
And it is taking a very long time
You're trying to bruteforce?
I think I am having 1000 tries in 5 mins
yeah
Also, I don't believe this is the right section, this is for web development
Hi guys - does anyone have recommendations on streaming video on a web server?
@lime fox is your problem solved?
Hello, am doing project and its an food ordering system. Right now am creating my cart with js and Django. now am storing cart of unregistered user to cookie and cart of registered users to javascript sessionStorage, but django cant comunicate with js sessionStorage. Should i put everythink in cookie ? (am worried about that 4KB size limit)
why can't you store it in sessionStorage? Make an API call from your JS frontend and store it there
wdym ? ehm now its stored in Javascript sessionStorage and i need to get it to backend (django)
yep - you can communicate between your frontend and backend with an API. You can send your JS data as JSON to your backend and do what you want.
Look into DRF (django rest framework) as a starter. It's quite essential!
well i have to finish it in like few days isnt there a other way than learning new framework ?
i know how to do it with cookies but its quite space consuming
the cookie with few products is like 200B
and its limited to 4KB
hi, I want to learn web development with python can someone guide me with a road map where to start
Well i can recommend you this channel: https://www.youtube.com/channel/UC1mxuk7tuQT2D0qTMgKji3w
taught me a lot about django
veryacademy is where to come to learn to code for free. Learn website development, tutorials on Python, Django, PHP, HTML, CSS, JavaScript, Bootstrap, WordPress, MySQL and much more.
This channel is all about teaching you simple actionable code, providing you access to code examples that you can use, for free to develop your knowledge and learn...
and he has videos on more web development stuff
well the issue is you're storing information on the client-side which isn't accessible by the server unless the client makes a request to it (via an API). Sure, you can make cookies, or find a way (if you are using django templates) to access JS variables.
i will prbbly stick to cookies this time, but thanks a lot i will dig into rest
amazon AWS Makes zero sense. why would i pay amazon 15$ a month and thats the cheapest plan for a postgres DB when i can just install postgres in my own instance?
not everyone has:
- good internet ( myself )
- good servers ( myself )
- time
- uptime
- expenses
no i mean i pay $3.5 for an amazon instance. why would i pay 15$ when for a db through them when i can simply just install it in my $3.5 instance, AWS is absurd with their prices as it is anyways
and in a different part of their dashboard, you can have 750 hours of db usage for free. makes no sense
hey, does anybody use or know flask?
I need to put a string to be the source of an image on HTML
do you know how to do thhat?
^^^^^
hey! good to see ya. if you wouldn't mind, could I ask if you use redis w/ django channels? what purpose does it serve? I just got websockets connected from the client and the server, now I'm trying to figure out how to link another client (e.g. admin on the other side of live chat).
<img src="relative path" /> you want to provide the source of an image? It's the relative path from the HTML file.
this tutorial worked fine until now. I'm at part 6, actually 7, but for some reason it doesn't tell me what to put in the polls/views.py vote definition.
https://docs.djangoproject.com/en/3.1/intro/tutorial05/
model = Question
template_name = 'polls/results.html'
def vote(request, question_id):```
Could anybody help me out? What am I missing?
it's not just it
I need this selected text tto be where {{ image }} is
<img src={{image_path}}
in your views,
def my_view():
path_to_image = <path_to_image>
return render_template('your_template.html', image_path=path_to_image)
This is just psuedocode, search up how to pass variables from flask to jinja2 templates.
Hello. I'm making an app using Flask. I've already asked in here but I had not done some things yet. Now I have an app that updates an retrieves information to a database (using SQLalchemy/Flask_SQLalchemy). I have created some thread and catches to control user's requests. However, when I update the database I can see the change, but suddenly (after some minutes) the database resets itself. I've tried fixing it with no success. I guess the problem comes from the database being updated at a GET request instead of a POST request. I searched through the internet and didn't find that doing that is actually bad, but it's the only thing I can guess it may be wrong...
I need it to be that way, so changing that is not in my plans
yes i use redis. what does it do specificly? no idea but i think it has to do with maintaining channel layers and keeping track of who is subscribed to what. but not fully positive. if your not deploying theres a memory channel you can use as well though.
there no specifics as to what its used for in anything ive read. so honestly its kinda just there
<img src="data:image/png;base64,(base64 code)" alt="QR Code"/> what I need is to put all that string (which is in a variable named image64), where is (base code), there's no path
every time the qr code is generated it creates another image and then a respective code to this new image, which is exactly what I need to be place before the "
I'm getting an error for some reason, and I think I knwo it' sfrom the vote def on my views. py, but I don't know what to pulac ethere considering the tutorial seems not to hav eanything for this. Furthtermroe my image doesn;t see to be working, but my stylesheet is. File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 790, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/Users/Bpower/Code_Master/Python/Django/poll-100/polls_100/polls/urls.py", line 2, in <module> from . import views File "/Users/Bpower/Code_Master/Python/Django/poll-100/polls_100/polls/views.py", line 38
still theh same
@sinful barn what theme is that For vscode?
monokai++
Django: user = authenticate(request, username=username, passsword=password) I am trying to do this but the user is returning NONE. Any reason for this?
Hey @toxic flame - thanks for the tip it's certainly got me in the right direction - but I'm getting an error on the site. So I decided to return var.customerNumber to the webpage and this is what gets returned:
<django.db.models.query_utils.DeferredAttribute object at 0x7fbc32380730>
Any idea where I went wrong - Here's a snippet:
def get_context_data(self, **kwargs): wGroup = var.customerNumber context = super().get_context_data(**kwargs) news_data = requests.get('https://sillyurl/api/?page=1&api_key=MYSUPERSECRETAPIKEY&group_id={}'.format(wGroup)) #context['newsdata'] = json.dumps(news_data.json(), #this just displays usual vague error from API # sort_keys=True, # indent=4) context['newsdata'] = wGroup #I'm using as a simple 'print' to the html page return context
you don't actually put the "var" i put
Var has to be an object
Customer.objexts.get()
What's up everyone! Question: I'm using Django for the 1st time to build a simple blog as my 1st project to learn the framework. I'm using the community edition of PyCharm and all was well until I added a main.css file into the app. After that my templates broke and errors out with all the messages pointing to the css... Does the free version of PyCharm support css & if so how do I enable it? Otherwise I do have Visual Studio on my laptop and can use that for my Django projects if I need to but I really like PyCharm...
P.S. The css from Bootstrap is working just fine, errors are coming from local css file...
that is bcos it is not loaded correctly
did u use static files
?
there is nothing wrong with PyCharm
Yes, I created a static directory then a directory inside static and placed the main.css file inside of it...
Yes, I did, and upon further review it was a simple mistake on my part... in the reference {% static '<path>' %} I forgot the closing quotation mark after my path... I'm used to auto-complete making closing parentheses, quotation marks, etc but it doesn't auto-complete in html files & I forgot to close the quotes!
I have zero experience on how to host web apps on a personal linux machine. Is there some good recommended guide? What are some good practices? Give me your wisdom . To be more precise the apps in question are dash plotly apps, nothing too extraordinary.
I'm not sure, but I think the advice is "don't host web apps on your personal machine, especially if you plan to make them publicly available" - unless you mean a Raspberry Pi or something?
I'm ignoring that advice and building a web app that will run on my laptop, use the Flask dev server, sit on a port that's not 80, and be accessed by half a dozen friends who I'll send my IP and the forwarded port to.
eventually i will either use a server service or buy a tpu server
but i wanted to get the first hand experience
thats the reason behind "personal machine"
also thank you for taking your time to answer this
well you can absolutely develop apps on your main PC in, say, Flask
it comes with a little server for development and testing
you mean deploy? i thought it was only local host testing
I'm new to this tbh - my understanding is the "correct" way to do it is to develop on your machine, test with the built-in server also on your own machine only, then deploy to a server that's properly secured against the hazards of the internet
yes the apps are rdy i just wanna deploy them
and i am now reading material and collecting videos to see whats good and whats not good
but i wanted some of your guys experience
anyone here familiar with tensorflow?
I developed and trained a keras model in colab. I want to use it in react.js app. i tried to deploy it in firebase as model.json(after conversion) but when i try to do some predictions, gives me errors related to shapes. the link to the tutorial i tried to do is here https://codelabs.developers.google.com/codelabs/tensorflowjs-firebase-hosting-model#5 .
Maybe there is a better way to use tensorflow(keras) model without deploying it in firebase?
In this codelab, youโll learn how to use the Firebase infrastructure to deploy an ML model so it can be used and consumed on your website using TensorFlow.js
i have 0 experience with web hosting i came here to learn stuff lmao. So i dont know what could go wrong there
you want to deploy a tensorflow model online?
its not clear to me what you are trying to do?
I want to use my model in react app to do sentiment analysis on web. So user enters a twitter account to collect sentiments and visualize them to charts. That's what i am trying to do.
I just want to somehow use the model in react. I read somewhere in stackoverflow that you have to deploy the model to work with it.
All good man. Thanks anyways!
no that means u installed django correctly
anyone know if it's possible to use Server-Sent Events with the Flask development server?
it's not possible with flask-sse
the spaceship is broken ?
to busy of a login?
@sinful barn it's still the same because you didnt pass the variable to your template.
@wicked elbow I'm not a big fan of the background image, I think something simpler would suite the page more.
Also since you're using react, have a look into framer motion. It's a really cool animation library and I've used it to transition seamlessly from login to dashboard (and within that transition I can populate my redux store).
i had to have something, it was honestly way way to plain. it being a social network i thought a network would be a good image. although it could be dulled some little bright
im also not big on animations. never have been. hated flash when it was a thing too
Hey, anyone with free 5 minutes to help me out with a form validation problem that I'm having?
Django: user = authenticate(request, username=username, passsword=password) I am trying to do this but the user is returning NONE. Any reason for this?
you've not literally got passsword=password in your code, right
no I do
wait wdym
@silk trellis
no
I define password before
email = request.POST.get("email")
password = request.POST.get("password")
ah, I thought it might be a simple typo:passsword
hmmm
Ola community, I'm new here, I would like help about Pyrebase, referring to Storage.
I am developing an application in Python with Pysimplegui for the graphics interface, so far so good. I want to erase images that are in Firebase, using the Pyrebase framework, but I can not find anything about it.
it means that authenticate() cannot find a user with such credentials. Question - do you hash your user's passwords?
Hey, does anyone know why I keep getting Field is required as an error in my form fields?
I've been struggling with this problem
Is it something in the model ?
in your model, set the field blank=False to stop required validations within a form.
@molten surge I just started learning Django myself so I'm no expert... I found a couple links that I hope are helpful...
https://docs.djangoproject.com/en/3.1/ref/forms/fields/
https://django.readthedocs.io/en/stable/ref/forms/api.html
https://www.google.com/amp/s/www.geeksforgeeks.org/error_messages-django-form-field-validation/amp/
Thanks!
Thank you!
I fixed my problem. I had to use {{ form.as_p }} , I was trying to insert it directly into the id of the input field
HTML is even worse than my Django so you can imagine, haha
Lol, no problem... I haven't touched html or css in years but now that I'm learning Django I need to brush up on both, with a heavy focus on css and design!
Ever want to see what it looks like when you update your anti-bot infrastructure?
is it forbidden to use django's login() for API calls? I thought all it did was return a Set-Cookie header which sets the client's sessionid.
@api_view(["POST"])
def signup(request):
try:
firstname, surname, email, = request.data["firstname"], request.data["surname"], request.data["email"]
password = request.data["password"]
# checks if email is in use already
if Customer.objects.filter(email=email).exists():
return Response(data="Email is already in-use.", status=status.HTTP_400_BAD_REQUEST)
else:
customer = Customer(first_name=firstname, last_name=surname, email=email, password=make_password(password))
customer.save()
login(request, user=customer)
return Response(data="Signed up!", status=status.HTTP_200_OK)
except KeyError:
return Response(data="Server did not receive user's credentials.", status=status.HTTP_400_BAD_REQUEST)
Doing the above gives me the error:
AssertionError: The `request` argument must be an instance of django.http.HttpRequest`, not `rest_framework.request.Request
So I'm not sure what to do here. Could I just not use login and set the sessionid manually?
why dont you use token auth
if you using frontend framework you have to use token auth if not then its not important to use rest_framework
why would you choose token auth > session auth?
are you using any frontend frameworks?
for one, I just wanted to keep django's login and logout features, but if they only set cookies then I can implement that myself. But another big issue is I read that django channels uses Session Auth, so I switched from token -> session.
@wicked elbow sorry to bombard you with django channels Qs, but what auth are you running on frontend? Session?
yes I'm using react
it cant recognize that youre logged in or not
you have to save user token in the session or local storage or async(for react native) so that by any request frontend will get or send data to backend
the only thing allowing the backend to know whether a user is logged in or not is if a specific cookie is present, in this case, it will be sessionid (from django's session auth). The same goes for token auth.
I'll stick with session auth, I just need to read a few more articles on if I can use login / logout and if not if there are any workarounds. I don't see the use for token auth when Django already has implemented so many methods for it's standard session auth.
django auth is for when you are using django itself not mixed with any frontend
try it yourself authenticate user then login then go in frontend check if your code been changed
templates and views part in django is diff from react
maybe you can do it by sending request to a view in backend part to check if the user is logged in, in django session or not
is there any advantage on using django and node together in the backend? Or would it be better to stick with just one?
theyare diff how you suppose to use them at the same time. like two backend?
yes
im not sure maybe yes but not a good idea
I searched that up and it says you can use a module named redis
damn, so if I change to token auth again I'll have to write a custom authentication middleware for django channels... But yeah, I see what you mean. I can't use login() when my request instance is from DRF, so I can't generate any sessionIds. Such a bummer.
This would work if I had my signup/login pages as Django templates.
I guess Token auth it is, with custom middleware. Just set me back a day or two...
Sounds complicated. Stick with one ๐
alright, thanks to both of you!
rest framework itself has a token auth that its too eazy
yw
and hope you do well with your website!
I know, it's not too hard to implement but I had a lot of logic that I deleted in favor of session auth to avoid making custom middleware, so I have a lot to re-do... damn, should've thought about it ahead of time!
thanks for the help @nimble epoch
and thank you ๐ @uneven berry
np!
true yw
hmm, sorry to come back to it but I found an article which shows that I can use session auth w/ a seperate frontend, maybe the simple answer would be to change from a DRF api view to a normal django view.
why would someone do that?
do what?
can i see the article?
tnx
oh! I'm not getting the same error before, so I might be going down the right road.
HTTP POST /api/login/ 403 [0.02, 127.0.0.1:49814]```
Since the error originally said the `request` had to be a Django request instance, and not a DRF request instance, I just changed it to a regular Django view (instead of DRF's API view) and it's proceeding now, time to add CSRF and see the outcome.
the view is customized, right?
what do you mean by that?
the login view?
yes - it's my own view, i'm not referencing a premade one.
no i didnt mean that but ok got it
but i think in this way handling autheticated user will be harder
in frontend
yeah but its ok
possibly, I don't see how though. Plus if you're using token authentication out of the box you have no sort of CSRF protection, so you could arguably say that this is more secure.
if it works its totally fine
not using token?
yep
aha maybe
but i still think using token auth in these situations are more common and useful. probably they knew something
maybe later youll face some problems
i am too let me know if you found one
we can work together dude
would somebody help me out please:
I'm on part 87 of the Django Poll's tutorial and on the customeize the admin look and feel section on this page:
https://docs.djangoproject.com/en/3.1/intro/tutorial07/
And with this block of code:
{% block title %}{{ title }} | {{ site_title|default:_('Django site admin') }}{% endblock %}
{% block branding %}
<h1 id="site-name"><a href="{% url 'admin:index' %}">{{ site_header|default:_('Polls-100 Administration') }}</a></h1>
{% endblock %}
{% block nav-global %}{% endblock %}```
I'm wondering why I'm getting an error, and why the Admin heaer isn't rendering the Polls 100 Admin header ? What am I doing wrong?
I see abvoe where it says to create the templates/admin folders and then it says to go into the Django site files and copy the code, but where do I place this code? I don't just update it here in the Django site files? I'm confused here....
Thansk. a
you have any job?
no but we can found one you and me
i searched but ....
sike
and of course i think building for yourself and publish it is better than working for someone
have you tried freelancing
no
why
didnt like that jobs lol
but you like money of curse xD
who doesnt????????
where who how
k
what error
Hey @lament sapphire!
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:
[12/Mar/2021 16:32:13] "GET /admin/polls/question/ HTTP/1.1" 200 7852
[12/Mar/2021 16:32:13] "GET /static/admin/js/nav_sidebar.js HTTP/1.1" 304 0
[12/Mar/2021 16:32:13] "GET /static/admin/js/vendor/jquery/jquery.js HTTP/1.1" 304 0
[12/Mar/2021 16:32:13] "GET /static/admin/js/core.js HTTP/1.1" 304 0
[12/Mar/2021 16:32:13] "GET /static/admin/js/actions.js HTTP/1.1" 304 0
[12/Mar/2021 16:32:13] "GET /static/admin/js/admin/RelatedObjectLookups.js HTTP/1.1" 304 0
[12/Mar/2021 16:32:13] "GET /static/admin/js/urlify.js HTTP/1.1" 304 0
[12/Mar/2021 16:32:13] "GET /static/admin/js/vendor/xregexp/xregexp.js HTTP/1.1" 304 0
[12/Mar/2021 16:32:13] "GET /static/admin/js/prepopulate.js HTTP/1.1" 304 0
[12/Mar/2021 16:32:13] "GET /static/admin/js/jquery.init.js HTTP/1.1" 200 347
[12/Mar/2021 16:32:13] "GET /admin/jsi18n/ HTTP/1.1" 200 3187
[12/Mar/2021 16:32:13] "GET /static/admin/img/search.svg HTTP/1.1" 304 0
[12/Mar/2021 16:32:13] "GET /static/admin/img/icon-no.svg HTTP/1.1" 304 0
Not Found: /favicon.ico
----------------------------------------
Exception occurred during processing of request from ('127.0.0.1```
That's only part fo it
I have some problem with Django. I can not see anything on port 8000 from my browser, even though terminal says ```
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
March 12, 2021 - 19:41:11
Django version 3.1.7, using settings 'sportfest.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
favicon.ico is an image just like any other on your server
its that little image you see right next to any tab in your browser
on top
you can either pick random image and save it in the static folder
or put this inside of <head> section of your HTML files:
<link rel="icon" href="data:,">
I can not see anything on port 8000 - do you get any error message
I'm partly blind, I think I found my mistake
ok problem solved
I have nuked it and create a new virtualenv and django app from command line
odd, i cant imagine why virtualenv would cause that
@opaque rivet yes I do hash passwords which is what I was thinking...
I mean django automatically hashes passwords donโt they?
yes, django does hash the passwords. when you call authenticate, the password your provide is called with the function check_password(hashed_password, password) anyways.
so in this case, authenticate cannot find your account.
you've done nothing wrong, if you want to authenticate the password you can do:
check_password(hashed_password, password) where the hashed_password is what you retrieve from the database, and password is the user's input.
Check the docs on this as this is simply from my memory.
Hey guys I'm trying to log individual django apps with the dictformat but I'm unable to do so.
The thing that I want to achieve in the logger key is
"myproject.app1" (app1 being an individual django app) and then setting up handlers etc
But unfortunately I haven't got this to work
Any help would be appreciated ๐
Hm ok Iโll see
hey, could you explain what you're trying to do? I've never heard about it before, maybe I could help ๐
im still running basic auth passing a token and storing it front end. havent messed with auth to much to be honest
do you use JWT?
but i mean, if it works, it work slol
also thanks for your resource Kendal
but i found a nice course on udemy about react + django
gotcha, so token auth. Have you ran into any problems with Django Channels? Their AuthMiddlewareStack (or whatever it's called) requires Session auth.
from what I've discussed, JWTs are frowned upon and you should seek something else. They're more of a short-lived token and not for a long-term authentication of a user.
they are shortlived by default
just like how everyone rants about django being monolithic.... false, it's only like that if you decide to use the default configurations.
yea but you can set your tokens to however long you want
im not using auth through channels. im validating from the user id and matching in the backend. not the best route, but its not the same to mess with through a websocket as it is an http request. i will eventually, but you can ride code to pull the token if you want to verify through token. its stored in the db as well
hey that works as well, and im using knox tokens. whatever they are. im not to security concious in dev honestly
https://james1345.github.io/django-rest-knox/ this is what i use
Basically I want to log each individual apps into separate log files for those specific apps
I looked at the documentation and django basically uses dict format logger defined in the settings. On the project level, it's working but not with separate apps
looking for some help with socketio, ive got few people on the team but we're looking for one more new member, thanks !!
@Zuma#2212 whaaa I'm pretty new to coding but you can even do that? Thats so cool, what language did you use to make it?
Hey guys, I'm currently working on the Gmail API and I got the consent screen and authentication working, but now when I'm trying to call service.users().messages().list(userId='me').execute() it gives me "precondition failed " error, idk what that means
https://dpaste.org/kS3C please help with that error
hey guys can somone help me out with a django issue?
I was wondering if there was an equivalence of a join query in Django.
You can pull data from a 1to1 m2m and foreign key relations, both from the child and the parent. I think thats what your asking. I havent used sql in a while so im not sure what the exact question is
class Meta:
model = Order
fields = "__all__"```
how good is this in terms of validation?
say i want to add a bot catcher how can i do so?
@swift wren what's the issue
so basically, im using UserCreationForm right, i want to get rid of all the help texts
@stiff ferry validation? I dont see any validation there.
like this
Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.
i want to get rid of those help texts
like its because i dont know how to remove them and nothing from the web is helping
@swift wren You can render the individual fields, if that suits better. It's something like this, from memory:
{% for field in form %}
{{ field }}
{% endfor %}
that got rid of the help text but now the form titles are gone
class MyForm(forms.ModelForm):
class Meta:
model = Order
fields = "__all__"
help_texts = {
'field_1':'',
'field_2':''
# and so on
}
Just set all your fields as empty strings
{% for field in form %}
{{ field.label }}
{{ field }}
{% endfor %}
Hi all, i'm planning on making a little portfolio website in Django. Would this be a good project to learn some more python? So far i've just made basic stuff like rock paper scissors etc. If so, does anybody have a suggested course that I could follow along with?
Edit: Just found Corey Schafer's Django tutorial. Looks like a good place to start.
as i know i haven't set any helping text is that done by django?
i was asking how to do so? how good is it compared to the normal forms.Form?
@stiff ferry I'm not sure what you're trying to ask... ModelForm means your form will inherit your model's validation.
do i need to add any other validation though?
what to do if i need to do that that's the question I'm asking @opaque rivet
and is that validation now considered server side or client side validation?
It can be either, completely up to you. Since you're using Django I think yours will probably be server side unless you Javascript to do the validation.
If you need to add additional validation just add a def clean_fieldname(self) to your model form. And do your validation in it.
outside of meta?
i think i get the gist of it
thanks @versed python
also any alternative to jumbotron seems like it is(and might be) discontinued ( i am using bootstrap 5)
I was reading an article about something this made me laugh
Hello everyone! Can sombody help me or give me and idea about this question?I've learnt the python to do this github project but I know the calculations and only thing that I didn't success is how do I visualize the results like in this example.
https://github.com/EmilienDupont/openPitMining
GitHub
EmilienDupont/openPitMining
Open Pit Mining example with Gurobi. Contribute to EmilienDupont/openPitMining development by creating an account on GitHub.
He uses the Gurobi optimization library for optimization but how did he do this interactive webpage which it calculates the bloks according to economic values and produces the bloks from surface to bottom of pit
my question is what should I do to do webpage like this working with python and What should I learnd to do this
thank you
hey can I integrate python web sockets with html
I just used certbot to set my nginx and flask web service for https but now I am getting this error:
301 Moved Permanently
react for frontend, django for backend
@opaque rivet thank you very much for your answer. You know what? I've been posting this question for almost 1 week and only person who ansered it is you.
Could you explain your suggestion more specifically please?
What should I learn or do?
:D, I didn't really explain why you'd want to look into those technologies, so let me explain:
Django will run as a backend API. Now, I'm not familiar with the optimization / algorithm, but the client (React) will send API requests to your Django backend, where you can run your calculations, and return a response. The client will then analyze the response you return and show the blocks however you need.
The choice of backend doesn't really matter. You can use node.js, flask, django - but if you want to bootstrap your project quickly, use Django. It's "batteries-included" so a lot of things are already included, so you won't have to scurry about making your own authentication middlewares.
But the frontend does matter, and React is a good choice for interactivity. It can edit the virtual DOM of the page, giving you real-time updates on the webpage without having to refresh. Also - it has great compatibility with animation libraries (if you want JS animations - look into Framer Motion).
So if you're looking to learn this, you'll need to learn some basic django and then jump into DRF (Django Rest Framework) - this handles your API.
API views are extremely similar to Django views, you'll get the hang of this.
The next thing to learn would be React, making a seperate frontend to hook your API to.
You COULD probably simplify this and do it without React, and just use jQuery in your Django templates. But either way - you're learning JS - and learning React will prove extremely valuable.
oh man! you're awesome! thank you soooooo much. I think it is a little bit complicated huh? I'm 42 yrs old I hope I can learn all of them ๐
by the way May I add you my friend list?
you're the only person who react my question ๐
sure - I wouldn't mind helping you & leading you in the right direction. Shoot me a DM and I'll reply later on as I'm heading out now. I learnt Django / React quite quickly, although it does have its own quirks.
Thank you very much again.
I have these two tables and I want to query them so that the result of the query is the tables joined. AKA query output. How do I do this in Django?
I only know python and I think I'm pretty decent at it. Given that, I want to make a mobile app. Ive broken down my options to Ionic or Flutter. If I go with Ionic I have to learn css/html/javascript. If I go with flutter I have to learn dart. Which option would be the faster for me to learn and implement an app given I'm coming from only python? Anyone with relevant experience that can provide insight here?
I'd recommend Kivy, mainly for it's cross platform support. It's also OOP which is cool too.
Thanks, I think I'm afraid that there is some lack of capability with kivy...but I may be wrong. Maybe a good question to ask is: can I make a soundcloud app with it? In other words can it take an audio file and play it, show the waveform and people can make comments on the waveform at specific points? If kivy can do that, then I should kivy. I know flutter devs might say flutter looks better...but I'm not sold that I need that for this app.
Yea i also think there are some lack in kivy
But i suggest learing react native instead, since python and javascript.... Well won't say they are similar, but they are pretty close
Cross platform too
I just look at kivy apps on google play...they look pretty bad
Second person to recommend that to me...for the same reason. Might be easier for me to go from python to javascript than dart....but I thought dart was similar to javascript? Edit:. Just checked it looks like it's closer to java
yes dart is closer to java and even Cpp
i recommend the react native method too. HTML css can be learnt in a weekend and (js, react and react native) can be done in a month or so
Usually i do react native for cross platforms to save time
But if it's for a real project, it's recomended doing same design and project but using different languages
For andriod: kotlin ( java... But better)
For ios: swift
Since the andriod system is built with java, it is pretty good with java stuff
hey, i'm doing a django course and I wanna put my project files onto github so I can work on them from my laptop. Here's my folder structure:
I have .venv and .vscode in my .gitignore file. Is there anything else I shouldn't push to github? I'm wondering what I should do about the db.sqllite3 file in particular
requirements.txt
you should push the sqlite file
Okay lets give it a shot
it doesn't weigh much uwu
push them to github
db.sqlite3 contains all youe database
when you add models, it gets converted to sql commands
Which web server do you using for django/flask app?
if you don push db.sqlite3 you wont have anything to your database and might lead to errror
I normally use pythonanywhere if its a personal project
professional work. Digital Ocean
@buoyant shuttle apache/nginix?
apache
I pulled my repo down to my other machine and branched it, but I canโt see any changes I make when I start the server and browse to it. Is there any way to see the branched changes before I commit them?
did you commit all your changes previously? did you use the command line of git terminall?
Yeah so committed and pushed all my files to GitHub, cloned them down to my laptop, branched them, but the changes I make to the branched files donโt show when i go to my website. I donโt want to commit changes whenever I want to view the changes within the website. Is there any easier way to see the changes?
yes go to your github repo
you would see a clock icon
click on it it would show the changes
or use githhub gui
ew github gui
React Native is also an option (JS).
A lot of people recommending react native
One of the arguments I like is that flutter is making massive changes with each update now so learning materials might be outdated
I'm torn now. On another level I just like google more than facebook lol...but might not be a good argument
Yeah. I may be wrong but I believe the demand for react native (in terms of jobs) is the greatest - and another bonus it'll bootstrap you to learning React (for the web), a sort of 2-in-1.
I'm not really looking for a job tho...I just want to make my app. My actual career is not related to development. This is more of a passion project
you should look at flutter
much more easier and powerful than java
Flutter / React Native are the main ones. I'd say React Native has much more tutorials / dev support, I am a react fanboy though ๐
Hehe yeah I've seen fanboys of both
there are lot of stuff about flutter too
if you think it is new therefore it has less tutorial you are wrong
i am writing an app now backend django mobile flutter
i think flutter has a big future
if you are react native fanboy you are and oldschool guy bro
i dont like mobile development I'm more of a backend dev uwu
I like working with apis, authentication, etc
yeah but i can say only working in backend is not a good idea
you write some code and you dont know how it will in frontend exactly
it works well in postman :d
Someone told me that in react native there is this thing called expo where you can quickly see updates on your phone when you update the code. Is there something like that in flutter?
yeah there is hot restart feature which is great it is like refreshing in django
when you refresh it updates pixels instantly
If I start flutter how much thought am I going to have to put into knowing the different versions...like 2.0 vs 1.x?
Are some tutorials outdated?
nothing different
only some updates happened in flutter 2 they say "free update for your customer"
I see a lot of memes about people needing to go backwards tho?
now for the code you wrote before also work in web
without doing anything .d
and desktop
ios and android
they are fun stuff bro
Lol
nothing really changed in code
I know the flutter community sounds funny
only null safety came
I kind of like how they get along
It's like everyone is on an experiment a little bit...that's how it seems to me
Alright. Ultimately I like google. I like gmail I like google finance I like tensor flow...I feel like I should just keep the Google train going
Facebook I get to see some people's political opinions that annoy me lol
Bout to hop on the Google train
google makes good stuffs now
I'm excited
Thanks you pushed me over the hump unless I come across something major in the next couple days
Anyone knows some free django hosting for like 2 days ? It's just for some competition and I need it to get running by tomorrow.
uhh heroku??
I know heroku is very bad but I think it will do it for me for day or two
ya im no expert but ive heard heroku is bad for long term and idk about short term
heroku isn't that bad, it has its uses.
Is it to blue? Just trying to get the colors to match up and not be increadibly distracting
pythonanywhere maybe
i like heroku because it makes it easy to deploy simple apps fast, but for something more long term maybe deploying with nginx would be better. another reason why i like heroku is because it provides lots of libraries that are either cheap or free, such as heroku-redis which comes in handy when working with websockets or non-http protocols (i.e. django channels)
Im worried if wkhtmltopdf will work on free django hosting
yea, that's why i do everything,
From full stack to mobile dev, to game dev, desktop apps.
lol
hi. does anyone know how to make a Usermodel in which I can store not only one file but many files in Django ? thanks !
hey - can somebody please help me with this?
my signup API is not creating tokens (AuthToken) for my users:
@api_view(["POST"])
def signup(request):
try:
firstname, surname, email, = request.data["firstname"], request.data["surname"], request.data["email"]
password = request.data["password"]
# checks if email is in use already
if Customer.objects.filter(email=email).exists():
return Response(data={"error": "Email is already in-use."}, status=status.HTTP_400_BAD_REQUEST)
else:
customer = Customer(first_name=firstname, last_name=surname, email=email, password=make_password(password))
customer.save()
token = Token.objects.get(user=customer)
return Response(data={"token": token}, status=status.HTTP_200_OK)
except KeyError:
return Response(data={"error": "Server did not receive user's credentials."}, status=status.HTTP_404_NOT_FOUND)
Here is my signal for creating tokens:
@receiver(post_save, sender=settings.AUTH_USER_MODEL) # receiver is post-save, runs after Customer model is saved.
def create_token(sender, instance, created=False, **kwargs):
if created:
Token.objects.create(user=instance) # assigns token to user
suite = Suite() # instantiates a suite
suite.save() # runs create_suite signal
instance.suite = suite
# once the sender model is created from the first instance of .save(), it will auto-create and link the token.
Strangely it does create tokens when I make an account via manage.py shell, but not an API call. Huh?
I also tested my API with pytest (now that I think of it, I don't know why) to see whether it was a client issue. It's not. Same error.
Specifically the error is here:
token = Token.objects.get(user=customer)
rest_framework.authtoken.models.Token.DoesNotExist: Token matching query does not exist.
well overall the issue is that the signal is not running
Set a model for each file with foreignkey to a main model
Have multiple FileFields within the model.
Flask-socketio
socketio.emit('my response', json, namespace="/test")
why is this sending the message to all connected clients and not only to the one it received from knowing that i didnt assign broadcast=True ?
How do I do this in Django? I have these two tables and I want to query them so that the result of the query is the tables joined. AKA query output.
@jade bison you would likely want to use a Foreign Key that points to an independent User model
Inefficient, but could work.
Pushing database files, password secrets, keys etc is not a good practice.
@austere cloud google you find alot of design like that
@glad patrol cant find any
i am searching for smiliar but they are totally different
I don't know what they are called
Can decide if i like this or not. The image really doesnt make sense. But looks cool. Just want something that looks good honestly
did you used bootstrap?@wicked elbow
Nah thats all my code
The code? Its react code
Ok
And its not up to date on my server yet. Only have localhost code.
How did you make 2 sides? Login and text
Its a flex container. Thats vertically centered.
How did you center if vertically?
<div style="display:flex;flex-direction:row;align-items:center">
<div>this will</div>
<div>be vertically centered</div>
</div>
Im on my phone or id go into more detail to show you
Thanks
hey any web developer out there now ...
Hi, I am using django-filters to query the data base, how can I make the search not case sensitive?. Thanks
Google that exact question, i cant remember specifically off the top of my head. Im more of a front end programmer
Whats up?
hey dude
Can you tell me
if I can integrate my python socket with my html chatroom
I have actually made a chat app with sockets in python
You can use flask or django to implement in sockets yes. You have to run a backend of some sort
well do I need to use flask-socketio
the cors part sucks
Not sure what you mean? I havent had any cors problems in django channels. And im using redis to distribute to my frontend
Hey
finally fixed this crazy error - it seems like Django didn't detect my model sending any signals.
Fixed it by going into <app>.apps and importing the signals when the app is ready:
class ApiConfig(AppConfig):
name = 'api'
def ready(self):
import signals.signals
Also for extra measure went into the app's __init__ and added:
default_app_config = 'api.apps.ApiConfig'
not really sure why, but if anyone can't get their signals to be detected, do this!
I scraped a site ,The site has some img tags and inside taht mg tags, there are src atributes as below
Here , you can see the s ource of that imge is loacted inside src attribute
Butwhen I scrap the same thisng using bs4 and requsts ,
*requests
This shows my the resolution of the image
||***WHY***||
?
Can you send what exactly BS4 shows?
So for what ever reason the top webhook works bot the other dosen't. Is there anything wrong with it?
This is the code:
@app.route('/hnktgo', methods=['POST'])
def botlist():
response = request.json
userid = response["id"]
asyncio.set_event_loop(asyncio.SelectorEventLoop())
asyncio.get_event_loop().run_until_complete(givecoin(int(userid), 1))
return Response(status=200)
@app.route('/trikhg', methods=['POST'])
def top():
response = request.json
userid = response["user"]
asyncio.set_event_loop(asyncio.SelectorEventLoop())
asyncio.get_event_loop().run_until_complete(givecoin(int(userid), 0))
return Response(status=200)
you really shouldn't be mixing asyncio and threading like that
if you're going to be using async with a web framework use an asynchronous web framework like sanic, aiohttp, fastapi etc....
I used it like that because I didn't want to convert a line of code I use for almost all of my files to something different
Do you think it would work if I change it?
Ok
Would that fix the problem?
maybe?
Ok I will try
Django is also async now as well
well its sorta async
What's webassembly?
A low level language executable by browsers in place of JS
Like a virtual machine / os inside the browser?
Native to the browser process
You could switch this code almost verbatim to Sanic:
@app.route('/hnktgo', methods=['POST'])
async def botlist(request):
response = request.json
userid = response["id"]
await givecoin(int(userid), 1)
return empty()
@app.route('/trikhg', methods=['POST'])
async def top(request):
response = request.json
userid = response["user"]
await givecoin(int(userid), 0)
return empty()
What does that mean?
I am not using async anymore
I did some searching but I wasn't able to find anything useful
It didn't work
what didnt work
Changing it to sync
man you really gotta show your code
Ok
@app.route('/hnktgo', methods=['POST'])
def botlist(request):
response = request.json
userid = response["id"]
givecoin(userid, 1)
return empty()
@app.route('/trikhg', methods=['POST'])
def top(request):
response = request.json
userid = response["user"]
givecoin(userid, 0)
return empty()
and is givecoin sync aswell
def givecoin(userid, website):
check(cur, userid)
cur.execute(f"UPDATE users SET golden = golden + 1 WHERE userid = {userid}")
conn.commit()
if website == 1:
cur.execute("UPDATE users SET discordbotlist = %s WHERE userid = %s", (datetime.datetime.utcnow(), userid))
conn.commit()
else:
cur.execute("UPDATE users SET top = %s WHERE userid = %s", (datetime.datetime.utcnow(), userid))
conn.commit()
The log when I fire it:
POST /hnktgo => generated 0 bytes in 13 msecs (HTTP/1.1 200) 2 headers in 78 bytes (0 switches on core 0)
so i assume your db driver is sync aswell
It works whenever I fire it with curl but not the website
Also the prints don't show up on the log
im assuming this is flask?
Yes
I don't think it is an error with the code because it still works, just not with the website
Well I gtg
I will try to figure it out
Thanks
does anybody tried file uploading using django and graphql
@native tide hello, we do not allow help with such topics
I'm concerned about accidentally doing it and curious about how one would stop such an attack
it can't happen by accident really
oh ok cool
also how would one stop someone who is continually sending http requests to a server?
Ban their ip.
so someone could ban a certain ip address from sending requests?
well no
they're still gonna send them
it's just whether or not the server chooses to handle it or not
you can ban them in your firewall if it gets to be to much. Itll just refuse the connection
i mean sure unless you're behind cloudflare in which case you cant do it like that
Hello everyone. I have been a web developer in PHP for the past 9/10 years. I'm now trying to change to Python. I'm wondering what is used now days in Python... It's Django still the number 1 for web development?
Yes Django is No . 1 In Python Web Devlopment But You Can Get Started With Flask which is Another Webframework
when I do
<div v-for="index in 200" :key="index">
<img
src="http://placekitten.com/200/400"
alt="kitty"
/>
</div>
All the images rendered are the same. But I want them to be different. I don't think this is a vue problem but does anyone have a solution to this?
Essentially, I want 200 different pictures to be rendered
When I remove any other product, the one with product_id of 1 always decreases. Any idea how to fix that?
Thanks. I kind of already started playing with Django. I saw Flask, but I identify more with Django.
What is people using for front end? Normally I keep it in Vanilla JS or jQuery
anybody know how to obfuscate code with base64?
hi, there is something confused me i try to use (api) on my project;my project is a Discussion board. i make to files one for (frontend) and the another for (backend) my problem is when i try to make (form)for add a new topic where should i write the code in (backend) or in (frontend) i hope that make sense
You should make an API interface, then display the form on the frontend. Then use this form data and send it as a POST request to your API and do the appropriate database stuff (or whatever else you want to do with the data). @mystic wyvern
Mostly Django If You Want to Make it With python
Okay. Thanks. Do you guys know any good resource to learn Django (other than the documentation)_
?
Tech With Tim Youtube Channel
I like His Vids For Learning Any Python Module
I will take a look
๐
The most difficult thing for me at this moment is to understand if what I'm doing it's the best / most pythonic way of doing things. It works, but... that is all I know ๐
You Can Go Ahed And Install Pycharm That Has PEP-8 Rules
So U can Make it look in the most pythonic way
@warm cape
Okay... I can try to install it, I normally use VSCode
@safe bough if I need help can I send you a pm?
Sure
thanks โค๏ธ
hey
I've been trying to test a Django API which has " auth.authenticate(username=username, password=password) " in it.
As you know Django makes another space for each file in test so there in definetly no connection to your own DB or any data you saved in another file.
My API code is like this:
"""
class LoginView(APIView):
permission_classes = (permissions.AllowAny,)
def post(self, request, format=None):
try:
data = self.request.data
username = data['username']
password = data['password']
print(username)
print(password)
user = auth.authenticate(username=username, password=password)
print(User.objects.all())
print(user)
if user is not None:
auth.login(request, user)
return Response({'success':'user auhtneticated'})
else:
return Response({'error':'user not auhtneticated'})
except:
return Response({'error':'something went wrong at login'})
"""
And I want to test that out with this codes
"""
def test_user_can_login_with_no_data(self):
res = self.client.post(self.login_url)
res_type = list(res.data.keys())[0] # it can be error or success
res_message = list(res.data.values())[0] # it explaines the situation
self.assertEqual(res_type, 'error', res_message)
def test_user_can_login_with_wrong_data(self):
res = self.client.post(self.login_url,self.incorrect_signin_data, format="json")
res_type = list(res.data.keys())[0] # it can be error or success
res_message = list(res.data.values())[0] # it explaines the situation
self.assertEqual(res_type, 'error', res_message)
# athentcate modle doesnt work
def test_user_can_login_with_correct_data(self):
user = User.objects.create(username=self.correct_signin_data['username'], password=self.correct_signin_data['password'])
# print(user)
# import pdb;pdb.set_trace()
print(User.objects.all())
res = self.client.post(self.login_url,self.correct_signin_data, format="json")
res_type = list(res.data.keys())[0] # it can be error or success
res_message = list(res.data.values())[0] # it explaines the situation
self.assertEqual(res_type, 'success', res_message)
"""
all data that is coming from self is OK and working so the problem is the user I'm creating in the test function is not available in the view I'm testing.
Hey everyone, I have a quick question, for some reason, whenever I go to localhost:5000, the div is in the middle, but when I go to 127.0.0.1:5000 the div is on the left?
I am using flask, html and css
that is a strange one, I always assumed localhost just resolves as 127.0.0.1 Can you open the network tab and see if the CSS file it is grabbing is from a different place.
Yeah I found that strange as well, yeah sure i'll do that.
It is grabbing it from the same place
maybe one of them is using cached CSS, try hitting CTRL + F5 to refresh them
mhm, some browsers cache stuff like css etc. as usually it doesn't change.
Yeah, thanks for helping.
CTRL + F5 is a full refresh
Yeah.
ok so im pretty new to python web development
im using cgi bin
wait wrong channel sorry
anyone here
switching to functional based components in react, however im reaching a dead end using useState
18 | return (
19 | // setting checked state to true
> 20 | const [checked, setChecked] = useState(true);
``` here
nvm ive figured it out
Hi! I'm working on my first webapp for my business. I'm brand new to Flask but have been using Python a little while - webapp works brilliantly and will be a gamechanger for us.
I am wondering about storage of customer data, though. any advice appreciated.
currently (I have not deployed the app except for testing with interested parties) passwords are stored SHA256 in an sqlite3 db
do I need to do anything more than that for passwords, and do I need to do anything with personal data (name, address, email, phone number)?
thanks for any help.
@royal tendon Something like blake instead of SHA256 would be more secure: https://docs.python.org/3/library/hashlib.html#hashlib.blake2s
Django 3.1
I'm in a pickle,
I need to > save file in view function with modelForm model from form (hey that rhymes) > redirect to new page > on the new page get filename because pretty much whole website depends on that file, but this is where I'm kinda stuck..
When using request.FILES['file'] after being redirected here from previous view function the csrf token expires I won't have access to that and the Dict FILES[] ends up being empty. Any suggestions ?
For personal data -- you probably shouldn't ask here, how to handle it is likely dictated by law. So you should talk to a laywer
Thank you @manic frost . Will do some research tomorrow but if you or anybody else here think of any little points to add then that would be great (UK based if region helps)
Hey all, I hate to ask a Django vs. Flask question, but I want to make a web-based mobile friendly flashcard app, hopefully with a login system of some sort for persistence. What would be the best framework to use to create that?
i would use django's built in auth system
but you can always use flask and firebase for lower weight
Thanks! if you don't mind my asking, how is 'weight' defined?
So Im using selenium...
whenever I navigate between two pages I use time.sleep(5) to prevent it from running into an error
is there any possible way to immediately execute a block code when the website loads
I've tried using a for loop along the links of this:
wait a minute I just realized some thing
Like amount of files
what is a django app? as in, what is the philosophy behind a django app structure? i understand that you can use it for whatever projects you want, but compared to a react component, what is a django app?
You can do using fastapi/flask/django
It all depends on your aproach
You could do a rest api and cosume that with Javascript
Or you can use django which is easier
for building monolitics web sites
If I was going to create a flashcard app I would definely use FastAPI to create an rest api
then consume it using Vue in the front end
anyone ever use django-imagekit?
I never used but maybe I can help you
