#web-development
2 messages · Page 125 of 1
i reload some stuff on django but css & js stuff aren't actually being updated
i think it was something of ctrl + f5 but i would want some response nbefore i break something
delete browser cached data
itll force the download from the server
ctrl+f5
jesus anyone ever get a react error they just cant find?
why not run ?
why does my flex containers never work?
Its kinda silly question i know but just wanna know that-
When we press ctrl + shift + c in any webapp it shows that web code.. If anybody make that change, would it be run on that particular user???
Won't it be?
if they modify anything in the rendered html, itll only affect their display. but its really not highly important.
Oh got it tnx..
Hi
hello...
Which language should I use to make an e commerce site
why does my flex containers never work?
@wicked elbow never work how
well, i figured it out... had to set my input to a fixed width because its default width was to large. lthough im pretty sure i could have done that with other style settings without the flexbox just figured it would be easier.
Hey, i'm not too sure if this is the right place but i'm wanting to use electron with python to build an app for a game what is the best way to communicate between electron and python?
or is there a better way in general to make a desktop app with python?
if its some simple app you can use tkinter
if you aim to make it a bit more fancier i'm not too sure tkinter is the right tool 😄
I'm kinda already running into trouble lol
my flask app works perfectly fine in browser
but when i import it into electron
none of the CSS or images work
😄
I want to add friend system in django app does anyone know any tutorial or docs???
DATABASE
ID USERID1 USERID2
0 90213 89234
1 12412 90213
What's this??
database structure
Hey @timid spruce!
It looks like you tried to attach file type(s) that we do not allow (.zip). We currently allow the following file types: .3gp, .3g2, .avi, .bmp, .gif, .h264, .jpg, .jpeg, .mkv, .mov, .mp4, .mpeg, .mpg, .png, .tiff, .wmv, .svg, .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.
What has careers got todo with that
yeah what does careers have to do with that im asking it in the web developemnt becuase its about web development🧐
You could start by checking out some python web frameworks like Django and Flask[* Though flask is actually a micro framework]
https://www.djangoproject.com/
ok thanks
does anyone here have experience with Heroku and django?
Using DRF your request needs the Authorization header with value Token <your_token> (Token authentication)
why are you using python 2 😩
guys why not run?
you would need to take over the data serving side of the handling
why is getting null at insert of m2m? https://dpaste.org/XUVu#L109,110,111
nope 😄
i have 1 stupid question
i have a base view that i load header and footer
i pass a form on the footer
but when i extend the page i have to pass the form again every time i extend the page
which seems not very pythonic
how do i fix that
nvm i am dumb 😄
When I go to the page this is on it says "Method Not Allowed"
How do I use a POST request properly
(Python Flask)
def tools():
if request.method == "POST":
return "<h1> Submited </h1>"
return """<form method="POST">
Language <input type="text" name="language">
<input type="submit">
</form>"""```
I have problem with cors headers in Django Rest
have followed https://pypi.org/project/django-cors-headers/
but still when i send get request using AXIOS i have issue with cors
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'api.apps.ApiConfig',
'frontend.apps.FrontendConfig',
'rest_framework',
'corsheaders',
]
i have added middleware
added config to allow all
(for a time being)
and still i get
i have resolved this... my installation and configuration was correct.. however due fact that I'm using anaconda as Venv manager
Conda have django-cors-headers in version 3.4 not 3.6
after changing to normal venv it worked
django-allauth is confusing the shit out of me
i'm trying to get it working with discord oauth, but i have no idea how to get any data from the response
i just want the list of user guilds and the username, nothing else
Hey guys, so I basically have a list of inputs with the same id and name, is there a way using django's request.POST['id'] getting all it's values and looping through them?
Would anyone be able to help me with a Flask issue?
I'm trying to use build a search tool but keep running into a Method Not Allowed on submit request
on django there are needs of csrf token on post requests, not sure about flask.
yeah I got that part at least I think
just initalized a secret key, no more csrf token error
I ran into an issue where I had to put the token within the table
I'm practically using something I built a year ago, so not sure why an error keeps happening
Rather, doing so fixed my issue
hmm not sure what you mean by token in the table
@app.route('/search')
def search():
global data
form = SearchForm()
if form.validate_on_submit():
form.search.data = form.search.data.lower()
if form.search.data in sorted_words:
data = form.search.data
return redirect(url_for('search_r'))
return render_template('search.html', title='Word Search', words=sorted_words, form=form)
I meant form, not table. Sorry about that.
ah ok gotcha, thanks i'll try it
You asked about request.POST[‘id_name’]... couldn’t you iterate over the input list?
ok that didn't seem to work. what I tried was
class SearchForm(FlaskForm):
app.config['SECRET_KEY'] = '62c04aebd965c494be687413770b91cc'
search = StringField('Search', validators=[DataRequired(), Length(min=2, max=20)])
submit = SubmitField('Search')
but the app var doesn't exist here, so still unsure what you meant lol
For index in request.POST[‘id’]:
Do something
My issue resulted in an error related to post method because csrf token wasn’t within the form submitting/posting
Basically it was a variable on the page but not in the form if that makes sense
Yea i tried, but it didn't work
It only shows the first value, the others aren't showing up
This is the last problem I have then I can get paid 😭
Django is aloottt easier, never learned about flask. But will in a few days
can you show me an example of the data structure?
print out request.post['id]
I'm trying to figure out why datatables column titles are misaligned with the row data until i click on the page somewhere.
really?
i thought flask was the lighter easier one
i mean django is heavy obv
but i though flask was much easier than django
Yea tbh they are all the same just that django is alot heavier even if you want to build small stuff
I prefer django over flask though
base32secret = pyotp.random_base32()
print('Secret:', base32secret)
# totp_uri = pyotp.totp.TOTP(base32secret).provisioning_uri(
# "alice@google.com",
# issuer_name="Secure App")
# print(totp_uri)
print('Secret:', base32secret)
totp = pyotp.TOTP(base32secret)
print('OTP code:', totp.now())
if request.method == 'POST' and 'send-verification-code' in request.form and reset_form.validate:
# try:
db = shelve.open('storage.db', 'r')
users_dict = db['Users']
db.close()
for key,value in users_dict.items(): #value is object
email = value.get_email()
first_name = value.get_first_name()
if reset_form.email.data == email: #will check user_dict emails if got such email, it is == as it is in for loop thus checking each email 1 by 1
email_data.append(email)
email_data.append(first_name)
msg = Message('Hello', sender = 'a@gmail.com', recipients = [email_data[0]]) #need put anther square bracket as will have string concatenation error
msg.html = render_template('email.html', postID='reset password', first_name = email_data[1],token = totp.now())
mail.send(msg)
print('Sent successful!')
break```
for the last 4th line, token = totp.now() is there a way to call the one time password instead of the function?
well Im using flask, thus, need set token = 'something' for me to retrieve out
jinja*
but i though flask was much easier than django
@rose field it depends on what you’re building
is more that Django comes with batteries included (templating engine and ORM, for example)
so if you wanna make something that needs these you’ll need equivalents for Flask anyway
can someone tell how to make this kind of a user system?
I m confused whether to use proxy model or AbstractBaseUser.
Seems you can use what's included and dont need additional models
For custom user flags i used AbstractUser
from django.db import models
from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
is_a_special_user = models.BooleanField(default=False)
when i pull data from a database and pass it as json is it picked up as a string? for instance if the data is store is [1,2,3,4] will it return as a list/array?
can someone please help me here
I am stuck with this for a long time
thanks a lot for your time!
what is wrong? what?
result array prints a value btw, it's not empty. and it is a url of the images. I checked
but it just shows nothing.
result = []
if images:
result = map(lambda x: upload_url + x, images)
print(list(result))
return render_template("index.html", form=form, result=result)
html:
<form method="POST" enctype="multipart/form-data">
{{ form.hidden_tag() }}
{{ form.photo }}
{% for error in form.photo.errors %}
<span style="color: red;">{{ error }}</span>
{% endfor %}
{{ form.submit }}
</form>
<br>
{% for image_url in result %}
<img src="{{ image_url }}" />
{% endfor %}
map will return a map object and that is an iterator. In this case, you'll exhaust it when you iterate over it.
So, by creating a list for your print, you'll take all items from the map object and it's exhausted after that. It won't return any more elements.
!e
my_map = map(lambda x: x + 1, [1, 2, 3])
print(list(my_map)) # the results
print(list(my_map)) # empty list
You are not allowed to use that command here. Please use the #bot-commands channel instead.
why am i getting an error saying my path is invalid?
from django.urls import path
from rest_framework import routers
from .api import PostsViewSet, PostsUpdateView
router = routers.DefaultRouter()
router.register('api/web', PostsViewSet, 'web')
urlpatterns = [
router.urls,
path('api/web/update-partial/<int:pk>/', PostsUpdateView.as_view(), 'posts-partial-update')
]
# Error
ERRORS:
?: (urls.E004) Your URL pattern [<URLPattern '^api/web/$' [name='web-list']>, <URLPattern '^api/web\.(?P<format>[a-z0-9]+)/?$' [name='web-list']>, <URLPattern '^api/web/(?P<pk>[^/.]+)/$' [name='web-detail']>, <URLPattern '^api/web/(?P<pk>[^/.]+)\.(?P<format>[a-z0-9]+)/?$' [name='web-detail']>, <URLPattern '^$' [name='api-root']>, <URLPattern '^\.(?P<format>[a-z0-9]+)/?$' [name='api-root']>] is invalid. Ensure that urlpatterns is a list of path() and/or re_path() instances.
nvm... need to move router.urls to the outside and do [] + router.urls
How can I populate a form with values? I found form.populate_obj but I don't get from the docs what do I need to pass and how to use it,
WTForms and Flask
I have a personal markdown on GitHub
That new thing where you can have a summary on your profile
But I can't make links in the readme open in new tab when clicked
Even when target is _blank
Is it possible now?
my static directory that heroku created is empty https://gyazo.com/3741fb1420dd169b4b60370880650ac3?token=177d1f4cd9d324b1723b792ca197f409
is that the reason for not showing the website properly?
using django.
DONT USE HEROKU!
can someone help me with this code because its not working properly and I dont know what to do
Flask
def startminecraftser():
startminecraftserver = request.form.get("startminecraftserver")
if request.form["startminecraftserver"] == "startminecraftserver":
return subprocess.call([r"C:/Users/mrxbo/Desktop/Flasklearn/BuildTools/start.bat"])
HTML
<form method="POST">
<input type="submit" name="startminecraftserver" value="Start Server" style="color:white; font-size:80px;"/>
</form>
what happened?
the POST request isnt working
I forgot to add some of the code that isnt working also
but yea the get request isnt working
it just sends me to the homepage
of my site
How can I populate a form with values? I found form.populate_obj but I don't get from the docs what do I need to pass and how to use it,
WTForms and Flask
This is my main.py ```py
from flask import Flask, render_template
app = Flask(name)
@app.route('/', methods=['GET'])
def index():
return render_template('page_one.html')
@app.route('/page_two', methods=['GET'])
def page_two():
return render_template('page_two.html')
if name == 'main':
app.run()
and this is my page_two.htmlhtml
<!DOCTYPE html>
<html>
<head>
<title>Page 2</title>
</head>
<body>
<!--I want to create a button to redirect me back to Page 1.-->
<button></button>
</body>
</html>
You can simply use an <a href> i think
Maybe it's better to do:
<a href="{{ url_for(<put here your route name>) }}">Btn text </a>
Here for info
https://flask.palletsprojects.com/en/1.1.x/api/#flask.url_for
can someone help me with populating a Flask WTForms with data? I saw I need something like
obj=user but I have no clue what is that
I have a fieldList of selects that I want to fill with data from a database
This Python Flask script outputs "Internal Server Error" can someone help me fix this?
@app.route("/utb09o6y78435wy34tyungggn943yw8ter8w4yfgfpwwp4ytpwbybwgb", methods=["GET", "POST"])
def startminecraftser():
if request.method == "POST":
startminecraftserver = request.form.get("startminecraftserver")
if startminecraftserver == "Start Server":
execfile("C:/Users/bob/Desktop/Flasklearn/BuildTools/start.bat")
HTML script
<form method="POST">
<input type="submit" name="startminecraftserver" value="Start Server" style="color:white; font-size:80px;"/>
</form>
I saw that and don't undestand that 😦
Maybe u have to put the final slash after the url
@app.route("/utb09o6y78435wy34tyungggn943yw8ter8w4yfgfpwwp4ytpwbybwgb/", methods=["GET", "POST"])
I think u have to do something like this:
selectForm = SelectField('name')
form.choices = [list of choices]
Yes it'll be str
well yeah that for choices I mean the selected one 😦
it kinda works
It's a schedule system
and I set it to default load one class
and it works
but I have 3 seperated selects and a submit to load another class
instead
populate a WTForm? Instantiate it like:
form = YourForm(dict_of_data)```
Can u do a single detailed message? 
and it doesn't work, I used del to delete it but when I create the the form again usingdata=data it loads the old data for some reason
that didnt work :/
"internal server error " happened
So I think it's an error of the minecraft server
or failing to run the batch file
that starts the server
there is a pause in the batch script
i could remove that
print your request.POST to see if you're even sending data to your endpoint.
Yeah, somethink like this.. I would find another method to start the server, executing a bat is not a great idea
Maybe there are some libraries to include mc servers in python
That's a big assumption
Firstly the form has no action attribute @pearl tulip
So I doubt any data is even being sent to your endpoint.
Ure right, mb
I'm having trouble using WTForms with Flask, I'm trying to edit the data of a form, after a LOT of trying I found something that works when loading the page, but when I "refresh" it it doesn't work, I'm pulling a schedule from a database,
when loading the site, I set to load specific schedule of someone but I have buttons that reload the site and try to load different schedule, but the problem is it for some reason not updating the page when I'm trying to load a different one
data = {'TwoDTable': template_previousSchedule['TwoDTable'], 'changed': None, 'submitToDB': False}
print('data' + str(data))
template_form['schedule'] = forms.scheduleTableForm(data=data, meta={'csrf' : False})
print("before")
print(f"template_form['schedule'] is:\n{template_form['schedule'].data}")
This returns
data{'TwoDTable': [{'Lesson': 'אנגלית'}, {'Lesson': 'אנגלית'},.......]}
before
template_form['schedule'] is:
{'TwoDTable': [{'Lesson': 'אנגלית'}, {'Lesson': 'ספורט'},.........]}
The problem is data is the correct thing to load but the thing printed after before is incorrect and I don't get why
This is my site: https://prnt.sc/wepfau
the top selects and the first red button is used to refresh the page and try to load the new schedule
Let's see your full view
What do you mean my full view
how do you add action to flask sry im new to web dev :/
your view...
Also you should be seeing an error message which is giving you your 500 error code, which will tell you the problem.
what is my view xD
you are 1 google search away from finding out that information
Hey @echo mesa!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
I dont know where to set the action so i set it to "/utb09o6y78435wy34tyungggn943yw8ter8w4yfgfpwwp4ytpwbybwgb/" and it still gave error 500
I fixed it alread
already
I forgot to put a return 🤦♂️
(RESOLVED)
I did this to solve the issue
def startminecraftserver():
if request.method == 'POST':
if request.form['startmineserver'] == 'Start Server':
return render_template("about.html")
return render_template("minecraftserverconsole.html")```
the rest is ez
i dont really get the get and post thing
the last time i tried it
it didnt work at all
@pearl tulip what the hell is this url
how do I return none if not found? technique = Technique.objects.get_object_or_404(technique_id=data_subtechniques['technique_id'].partition('.')[0])
Hello everyone, i am facing a problem with django and i don't know how to solve it, i will explain the best i can my problem :
i have two classes : tag and media.
I need to define a media with a tag attribute, i defined a foreignkey in the class media to collect the tag value, but since i would like to have different tags, i am asking you if there is a way to give in the admin panel the choice to add as much tags as he wants...
Thank you so much for your help!
@dawn heath You can use .exists(), it is True if an entry exists and False if otherwise.
you mean if add .exists into .get it wont throw apps.api.models.DoesNotExist: Technique matching query does not exist.
some stackoverflows says get_or_404 another filter, and others first
Yo,
deploying my django app to pythonanywhere and I get this
TemplateDoesNotExist at /
blog/home.html, blog/post_list.html
even tho there is already a template at that location
hi guys, I'm reading Django for professionals and I have a question because when I run docker-compose exec web python manage.py startapp users to create an app in a django project called "users" it is copied to my local repository but with owner set to root, not to my user. Why? I ran docker build and docker-compose commands without sudo. In the book it does not say anything about owners. Thank you!
It is a question about docker and I could not find any related channel
@vernal furnace did you collectstatic?
why am I getting slicing rror? https://dpaste.org/Lt4E
@quick cargo @dapper tusk
So here is the image i talked about
What do you think? The api is a HTTP api server, ws = websockets. And all the clients are connected to a websocket, but it can be on a diff port/host
And what is the gateway? It's the websocket server with some http routes?
So you hit the API with a message it performs an other http request to the gateway which performs socket emitting?
litterally can just be another http request
hmm?
ohhh
for us our api for comms is done on the same system as the gateway
and only the API sees this gateway
yeah got it
or litterally any virtual netowork
nice
and why is that better than redis?
you said redis is slow
but, is that faster?
bcs redis is known about the really good performance lol
well we ditched all of our redis called and saved about 200ms of latency per request
dont use redis where it isnt needed
its just adding another layer of calls and processes that you dont necessarily need
ooh got it
and how is python performing with db?
fine?
postgres is fast, asyncpg is fast not really and issue
just use PIL or smth to handle the metadata
asyncpg?
a async driver for postgres
Ahh okay. Thanks man!
can i convert python code into html/php? if so can anyone tell me how?
what do you mean?
like...transpile?
on the frontend?
ye
not really
a
...why do you want to convert it to PHP?
is it important :/
does anyone know if its possible to use an integer to search and get ids in sqlalchemy and flask
I'm trying to figure out why datatables column titles are misaligned with the row data until i click on the page somewhere. Any ideas? I’ll try just about anything at this point.
@cold portal Have you set their width to match in the CSS
Actually, no, I haven’t touched CSS. Using bootstrap4
Interesting that it would correct itself on click
Thanks for the tip. I’ll look into it
I'd just say give the columns an extra class which has a set width
Or have the labels (device info) and the value below it (NSA2600) in the same row & column as eachother
Then give the value column a class of w-100 so it expands to the width of Device Info
@cold portal
What do you mean in the same row & column as each other? I think they are. Both defined in datatables.columns[]
Each column defined has the title in it. I had the title labels set in html but had the same problem.
I’ll see about trying to apply another class with a set width. Setting the width in the column definition didn’t help
Any body help me to make or understanding of web dashboard for embed or welcome message
man, why images so hard to work with in html?
I'm new to web development can anybody help me?
what do you need to know?
is it possible to use gettext to convert digits to their regional variants, e.g. 12345 -> १२३४५
Im trying to show the user picture in Django but not working. already added static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) and i checked the src and its correct but its still not working.
please show the path of the image and the image in the the media_url folder
MEDIA_URL = '/profile_pictures/'```
@gaunt marlin thats it
and actually in the src of img tag its correct but i dont know the problem.
and funny thing that this is the first time
BASE_URL / 'profile_picture' is not how you concat a string O_O
maybe this is my chance this time
bro i know what you saying but this works on BASE_URL
check developer console by pressing f12 go to console and what error it's returning
in its own docs this is written that use it like this
no error just the picture not be shown
then the path is correct
yep
and wait wait of course it returns a 404 error
why you said no error earlier...
ImageField
show the error?
can't you just copy paste the red line in here?
its orange lol
it is i dont know
try to go the url, does it show the image?
you need to post what you have done in your code
first by showing the folder path of MEDIA_ROOT
or paste the url in here to see
ok wait
emmm @gaunt marlin thanks bro and appreciate your time. its working now.
Can anyone give me a good reliable source for learning web development
And also courses for free
to make my own website^^^
does anyone need projects for free
this is not for hire channel
i don't know much free course but if you stuck on what to learn there a career path chart https://github.com/kamranahmedse/developer-roadmap
i think these have some good free course to follow https://github.com/bmorelli25/Become-A-Full-Stack-Web-Developer
don't take the fullstack word yet, but it cover most of the things you will do in web development
in that example, if each of the members of the groups have some extra fields, how to put them?
let's say doctors have a doctor_id, while nurses have a nurse_id
Can someone explain what is the obj in form.populate_obj(obj=user) in WTForms and Flask?
I'm trying to fill a form but nothing works
need urgent help
how can i download a pdf file without storing it in media folder
in django
hey is there a way to save and check if a user is a user when they login ?
Damn you are so beats
is django is easy to learn while i have expirience in using javascript , reactjs and nodejs
i have a django project but it's for some reason not showing the background where im using particles js
i think you should go to settings.py
which database are you using?
sql
go for a method for checking user with userId in your collection
table*
ok
am not sure but i think its like req.body that recieves an req from client to server
i'm using aiohttp web and assigned a dns to my ip, why do i get this error when going to my domain?
are you actually running on 0.0.0.0 and that your fw isnt blocking stuff
nah i disabled any fw
@quick cargo
also when i ping the domain it's assigned to my ip
going on 0.0.0.0/keys or localhost just works fine
i did the port forwarding
Hi all, is anybody aware of how generally the no-code or low-code platforms generally generate the code behind the scenes?
normally is jsut a set of pre-coded bocks that go to a standard interface
guys if i want to change the width of just an text input in kivy, how would i do that
just lego bricks
@quick cargo any ideas?
nope i dont work with kivy, probably better question for #user-interfaces
i asked there no one answers lol
same for a help chat same for general
👍
and web development

Hey guys, so I basically have a list of inputs with the same id and name, ( on the HTML ) is there a way using django's request.POST['id'] getting all it's values and looping through them?
i think u can use context
Im using socketio js on frotnend and socketioflask on backend
when i send a socketio event
it gives em a 400 BAD REQUEST and "Invalid session xxxxxxxx"
why could this be??
then
check your code again..its beacuse of invalid syntax
the code works on localhost?
but not on production
yes
imhosting
in a host provider bc my router cant ip forward
no no
ye
the main server works and socketio too
but
when i send events
"emit"
it dies
with 400 bad error and the message i said
f
r u using nginx something like that
How can I redirect to another page instead of the admin login page in Django?
type another url?
drop socketioflask, make socket server with nodejs and a HTTP api in flask.
bruh
less headache
I mean when you aren't login when you got to /admin/ you get to /admin/login but I want to go to a custom login page
eeh
oh, did you try django doc?
and i need socketio to be on python to access database in sqlalchemt-pfashion way
also app factory and routing
Yeah but I'm not sure which attribute I have to set
Is it the AdminSite.login_template?
got it got it
It doesn't work for the admin page just when you use the @login_required Decorator
hello , i made a config file generator and i want to host it in the web so other ppl can use it . i want users to be able to download the generated file after completing the form . and i want recommendation on how to do it .
tor
I listed it pretty well
It's about parsing & recieving the request correctly
Does someone want to help me with a javascript bug in #help-peanut ?
Post code here
I moved to #help-falafel
Good evening. How do I make an input on the site so that the text is entered there and I can output it in the console
guys help me pls
Okay so I'll put my conceptual question here
Regarding Django.
What's preventing me of using ajax request to get fully rendered html back from Django and inserting it in a div?
This feels much more versatile to me over using include tags...
But feels "hacky" to me...
you can.
but the whole point of Django is that it returns fully rendered pages in the response
if you want to have dynamic content, might as well just write a web API
Question: what do you call a web application that basically manage databases
like a front-end that can send api request to delete, create and edit users?
Bro use websockets
simple web application? 😅

I need help. I want to insert a swf file from my computer and go into the game, but the server loads its swf file. Give advice what
why would you use websockets for that
I understand the point. But after using some other frameworks, namely vue
This seems so much more powerful to be used this way
I can re-render a piece of html with dynamic content
well ajax can be really bad for people with bad internet idk
Well... Who has bad internet these days? I dont want you using my website
😂
How is ajax any different from a rest api internet wise?
What is Computational Thinking? can someone explain this to me where I can understand it.
@vestal hound but i can render just a snippet of html, like a form and then send it over to the page
And update a div with it
But this feels so "hacky" xD
dm me if you have high html knowledge
@gusty sphinx bruh just ask the question
Hello, everyone. Is picking a font even an issue these days? Can I just pick what I want? Last time I was doing web stuff was in the mid 2000s.
more info: I'm looking for a font that is best for keeping those troublesome characters from being confused (e.g. 0, O, - or - I, 1, l); it's like the their, there, they're of character identification for websites.
There httpredirected method and u must import redirect from httprequest
U should start react that's more powerful than vue
Courier New, monospace seems to get the job done
@app.route("/api/profile/edit/<bio>/<uid>/")
def api_profile_edit(bio, uid):
if not current_app.discord.authorized:
return(f"401 - unauthorized | API |", 401)
else:
user = discord.fetch_user()
authid = user.id
if authid == uid:
collection5.update_one({"_id": uid}, {"$set":{"bio":bio}}, upsert=True)
return("200 - ok | API |", 200)
else:
return(f"401 - unauthorized {authid} | API |", 401)```
resp:
```401 - unauthorized 393171225838354433 | API |```
url
```/api/profile/edit/pog/393171225838354433/```, the 393171225838354433 in the resp, is the id of the logged in user
the 393171225838354433 is the id of the user i "say" i am, and its the id i am
i wouldn't use websocket for REST API calls as it usually result in blocking when the traffic high with api calls
can someone please help me here?
thanks!
Which web-development framework would you recommend for a beginner, Flask or Django. Also for the web framework you recommend, where would you say is the best place to learn how to use it. Lastly, for web-development do I have to learn any additional languages like javascript, css, or html for front-end, if so which should I start with.
1.django
2.django docs or programming with mosh's tutorial chapter on it in his 6 hour long course, I learnt from it, and of course, the well written docs
- First master the backend with Django, if python is the only language you know. Then I would say you learn javascript. CSS and HTML aren't "programming languages", they are just tools for presentation and can be learnt comparatively quickly. You'd need practice to improve your presentation though
@plain haven
@twilit needle Thank you lots! After practicing python for a while I wanted to go into web development and didn't know where to start. This helped point me in the right direction
how do you call this and set the value like you do in python?
function something(a=false, b=false) {
}
something(b=True)
cause im just getting errors, ive googled it, but it never mentions the calls to set the variables separately
when you declare the argument in the function it will force you to use it, if you want dynamic arguments use **kwargs instead https://book.pythontips.com/en/latest/args_and_kwargs.html#usage-of-kwargs
im asking about using kwargs in js not python
so something like this will work
function something(**kwargs) {
b = kwargs["b"]
}
something(b=True)
you didn't say js in your question
ah my bad, copyied it from another discord that is js specific
(){} can be anything from C to javascript
i know in python, if you set kwargs in the define then you can set them in the call by doing function(b=true). so didnt know how to do it in js
then in javascript you use
function something(a, ...availableChoices) {
return availableChoices[index];
}
something(b=false);
it's called spread variable https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
Spread syntax (...) allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.
yea, i knew about spreads too. thank you
I am using window.onload() function to run a script after loading on a website in my extension but sometimes it is running and sometimes not. Any reason why?
i would suggest you use document.onload() instead, window.online() required all the css, image,... to finished loading while document.onload() only required the DOM to load
ok thanks
glad to help
I also tried jquery's document.ready same thing happening
does it show up any error in the developer console?
no
maybe the problem is not the template but your script?
does using window.onload or document.onload inside a function effect it's working
ok I'll try outside then Thanks
hi
@staticmethod
def user_join(access_token, userr):
try:
url = Oauth.discord_api_url + f"/guilds/768019392596017164/members/{userr}"
headers = {
"Authorization": "Bearer {}" .format(access_token)
}
user_object = requests.get(url = url, headers = headers)
user_json = user_object.json()
return user_json
i have this function
for discord oauth2
im trying to add people to a server
but im getting a {'message': '401: Unauthorized', 'code': 0} error
plz help
idk if i should really use json there
but i tried
@staticmethod
def user_join(access_token, userr):
try:
url = Oauth.discord_api_url + f"/guilds/768019392596017164/members/{userr}"
headers = {
"Authorization": "Bearer {}" .format(access_token)
}
user_object = requests.get(url = url, headers = headers)
return user_object
as well
and that got the same error
make sure your bot has permissions to do so
it has admin perms
Hello reacently i switched form javascript to python. So if anyone knows how to run a local server on python please let me know!!.
Hello! Can anyone please tell me how do I make a web application wherein I can upload videos using Python and Flask
It's very urgent. Please let me know if anyone has any idea. Thankyou.
What is recommended for a site's backend in python? Can i use simple http server or i should use something else?
you can use it but it will be a hassle to do web functionality, there a few popular backend frameworks like flask, Django, fastapi
Oh
Thanks we want to use an sql server too. How could we connect it to the server and/or site?
We can do it with these framworks or sth else?
sql server as in MS sql server?
I dont know probably mysql or sth.
Django Supports pretty much only SQL with its orm (SQlite, MySQL or Postgres), FastAPI or any async framework i would recommend using postgres only and asyncpg
those framework support connecting to DB too if you wondering
Flask can support pretty much anything cuz its what ever you implement
yeah i meant that
same with async frameworks for that matter but their drivers are very limited and asyncpg is about the only decent one as of right now
So flask is a good one?
depends what you're doing but its a pretty solid choice
Flask will give you a lot of freedom and therefore is really powerfull. Django is more constrained but it makes it harder to make errors.
flask is flexible, django if you want to make something fast, fastapi mostly use to make api(figure)
So Django is easier to use but flask i can do more
Ehh its mixed
I understand now
Maybe we try django first
Django faster to build a website but it's hell to customize and understand all of it
Yea in the end the code you write it what makes the difference.
And what do you think about making my own http server? Is it hard to connect to db?
i wouldnt make your own http server unless your seriously know what you're doing if its for production
That would mean writing a lot of very interesting, critical and hard code. which is a good idea to learn stuff and bad idea to make things that works
security a big thing if you doing production
Been re-writing my http server in Rust for python 😔 Just takes freaking ages to test though
need to add http/2
Yeah i started with http server i never used any framwork before. I like to do it myself. But i dont know if my partner want to run it irl or just for himself in localhost
you are free to reinvent the wheel if you want 🙂
I never used db neither so i dont know how hard is it to connect a db to my http server
if you connect to db from http you have to handle each transaction, re-authenticating,... and a lot more
DB handlers are about 100x harder than writing a http server
i would just use a pre-made driver
handle transaction without it blocking each other will take ages
python has a pretty good selection of drivers for your flavour of db
Don't be afraid or ashamed or whatever to use frameworks, I used to want to do everything by hand up to the point somone told me x86 was a high level language. Being able to re-use someone else's work is amazing and really powerfull.
yes like how i described above writing https server is like reinvent the wheel, it's good but not needed 😄
In the mean time, for study, build you own http server, db driver, language, OS, all of it is really interssing and will allow you to use the premade ones better.
yes better understanding of the framework you will be using
I dont have any problem with frameworks i just personally like to make my own http server i like to understand how it works and like to hardocde things
But i think we will use django or flask first
Btw i have one more question
we will need an sql database i considering mysql prostgresql, mongodb but idk
postgres 100% if you're going with sql
Ok thanks
Something that is working properly and easy to use
if you want really simple just use SQLite
its pre-installed with python
so no external server needs setting up etc...
Oh thanks then
and if we upload to github where we want to work we can share the db's content of sqlite?
What's the purpore of your project ?
Then how could we work with the same content?
Just to make a site with backend and sql
you dont really need to have the same data per say
I dont know if he will want to host it so i wont share anythinglike the databsae
sharing the content via the sqlite file over github can work but it's ugly and will become a hassle when you have a lot of data
its just a test site n localhost so not a maisssive issue to just replicate data
Ok then we will figure out
ok then
thanks guys
You can always just dump the db and share it via mega/whatever
Thanks btw if i use sqlite now later i can swap to other sql server if i want to host? or i can use sqlite for a real site?
You can mostly swap sqlite with other sql databases. You can also host sqlite if needed but i'd recommend postgresql if you want something online.
Thanks
I have coded some projects in both Django and Flask, I have an idea for another django project/extension to one of them and possibly also thinking about learning some basic design for it, but I am not sure how to push myself to learn new things etc yet things that would be within my skill reach, any recommendations?
any idea on how to make the button clear also delete the image from the disk?
also, anyone knows how to save the image as the primary key?
I want install scrapy but i have error. who can help me?
Where is the VPS hosted ? What is your security configuration ? What's the error beyond "it doesnt work" ?
hello
Scoll down the error message box and send again, or make a pastebin with the whole output.
@cloud gulch https://pastebin.com/mG0LQ7kC
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Here's your error Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/ it comes from twisted ( a networking framework )
Looks like you just need to install dependencies
Need to upgrade to Microsoft C ++?
"Microsoft C++ Build Tools"*
Yep, follow the link 🙂
thank
from typing import Optional
from fastapi import FastAPI
from pydantic import BaseModel
class Item(BaseModel):
name: str
description: Optional[str] = None
price: float
tax: Optional[float] = None
app = FastAPI()
@app.post("/items/")
async def create_item(item: Item):
return item
I need a status code, response body and request body
anyway to have flask live reload on save when doing front-end templates ?
Do you use a front-end framework ?
plain html/css
maybe bootstrap if i cba doing the styles and want a quick prototype to show off
Hot reload should work then, Jinja had some weird config bug when used with an app factory
i have app factory layout but don't use any module for it
thanks
actually
hot reload once works on python code changes
not jinja
maybe look at this: https://github.com/pallets/flask/issues/1907
yeah took a look, not sure why I can't get it working
cba messing round with it right now
thanks though @cloud gulch
Hi guys, I'm working in a Live Streaming web, since Django isn't work for it, I have to do the Backend in raw Python, I haven't found information in Google, could you help me.
you know there are other frameworks that exist other than Django
flask can stream a sequence of independent images
Hey! I was wondering if I could get some help with bottle? For some reason I can't connect my css-file to my index.html through static files.
is it an antipattern to make queries inside django models?
@jade pulsar You can use django as the backend, I don't see why it wouldn't work compared to any other backend framework - you're not missing out on any features.
Hi everyone, I'm not specialist and my specialty is not IT related. Just interested in programming, and I learned django in some extent, I created a couple of basic web apps. Recently I started to think that django rest framework is really good, and feel like its doc is even better than dango's. So my question is can I use only django rest framework, create API and then give this stuff to frontend to combine?
for flask
do i use asyncio.sleep or time.sleep?
My code doesent output test when I activate the html button
Flask
@app.route("/", methods=["GET", "POST"])
def controller_left():
if request.method == 'POST':
if request.form['controller_left'] == 'left':
print("test")
return render_template("controller.html")
return render_template("controller.html")
HTML
<input method ="post" type="image" value="left" name="controller_left" src="https://i.imgur.com/I1MmP1U.png" style=" width: 300px; height: 300px;">
can anyone link a good tutorial on how to make a website with python?
yes, that's a common pattern
I started messing around with the frontend development and have a stupid problem. I wanna make a dropdown button, I am using bootstrap, this is the html html <div id="app"> <div class="dropdown"> <button id="methodBtn" class="btn btn-secondary dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="false" aria-expanded="true">Select HTTP method</button> <div class="dropdown-menu" aria-labelledby="methodBtn"> <a class="dropdown-item" href="#">GET</a> <a class="dropdown-item" href="#">POST</a> <a class="dropdown-item" href="#">PUT</a> <a class="dropdown-item" href="#">PATCH</a> <a class="dropdown-item" href="#">DELETE</a> </div> </div> </div>
However on click it doesn't do anything. Would appreciate help
if you wanna make a simple API I don't think django is the best choice. Take a look at https://fastapi.tiangolo.com/
FastAPI framework, high performance, easy to learn, fast to code, ready for production
hi someone speak spanish?
hi
@staticmethod
def user_join(access_token, userr):
try:
url = Oauth.discord_api_url + f"/guilds/768019392596017164/members/{userr}"
headers = {
"Authorization": "Bearer {}" .format(access_token)
}
user_object = requests.get(url = url, headers = headers)
user_json = user_object.json()
return user_json
i have this function
for discord oauth2
im trying to add people to a server
but im getting a {'message': '401: Unauthorized', 'code': 0} error
plz help
idk if i should really use json there
but i tried
@staticmethod
def user_join(access_token, userr):
try:
url = Oauth.discord_api_url + f"/guilds/768019392596017164/members/{userr}"
headers = {
"Authorization": "Bearer {}" .format(access_token)
}
user_object = requests.get(url = url, headers = headers)
return user_object
as well
and that got the same error
Try adding Content-Type to your header
headers = {
f"Authorization": "Bearer {access_token}",
"Content-Type": "application/json"}
it doesnt work
also
someone on another server told me to
headers = {
"Authorization": "Bot {}" .format(token)
}
change it to this
and add a access_token param in the body field
but idk where that is
lol
tried checking the docs ...might be of more help https://discord.com/developers/docs/topics/oauth2#shared-resources-oauth2-urls
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
have anyone done twilio api 1 on 1 video call with django yet? will it be doable to make online 1 on 1 class stream ?https://www.twilio.com/blog/build-video-chat-application-python-javascript-twilio-programmable-video
i think this is the easiest one i can think of without touching all the RTP
im trying to make a thing where you enter a password which then takes you to a place where you can press a button which does something
the thing is I have no idea what I did wrong can someone help
from flask import Flask, render_template, request, flash, url_for, redirect
import subprocess
from subprocess import Popen
app = Flask(__name__)
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0
@app.route("/", methods=["GET", "POST"])
def passw():
if request.method == "POST":
passw = request.form.get("pass")
if passw == "1234abc":
if request.form["arduinocontroller_left"] == "left":
subprocess.call(["C:/Users/mrxbo/Desktop/Controller/ayylmao.bat"], shell=True)
return render_template("controller.html")
return render_template("authent.html")
(python)
posting the error would be more helpful
Error code 500
Here is controller.html
<link rel="stylesheet" href="{{url_for("static", filename="style.css")}}">
<form method="POST">
<input type="image" value="backward" name="arduinocontroller_forward" style="width:150px; height:150px; position:relative; bottom:-150px; " src="https://www.vippng.com/png/full/16-167277_free-stock-photos-red-arrow-pointing-up.png">
<br>
<input type="image" value="forward" name="arduinocontroller_backward" style="transform:rotate(180deg); width:150px; height:150px;" src="https://www.vippng.com/png/full/16-167277_free-stock-photos-red-arrow-pointing-up.png">
<input type="image" value="left" name="arduinocontroller_left" src="https://i.imgur.com/I1MmP1U.png" style=" width: 300px; height: 300px;">
<input type="image" value="right" name="arduinocontroller_right" src="https://i.imgur.com/0gw5yTW.png" style=" width: 300px; height: 300px; position:relative; left: -20px;">
</form>
here is also authent.html
<link rel="stylesheet" href="{{url_for("static", filename="style.css")}}">
<form method="POST" autocomplete ="off">
<h1>==Enter Key==</h1>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<input autocomplete ="off" type="password" name="pass" class="private" style="font-size:40px;">
<br>
<input autocomplete ="off" type="submit" value="Enter" class="paragraph" style="font-size:120px; font-color:white;">
<br>
<h1><a href="./home"> Back to Homepage </a></h1>
</form>
i mean the detailed error(full error stacetrack)
raise ValueError('View function did not return a response')
ValueError: View function did not return a response
192.168.0.151 - - [05/Jan/2021 23:04:06] "GET / HTTP/1.1" 500 -
this one?
yeah that
you need to return a response in your view
what happen if it doesn't go into if statement?
passw = request.form.get("pass")
if passw == "1234abc":
if request.form["arduinocontroller_left"] == "left":
subprocess.call(["C:/Users/mrxbo/Desktop/Controller/ayylmao.bat"], shell=True)
return render_template("controller.html")
return render_template("authent.html")
it will return None
what is not going into an if statement?
when pass != "123abc" and does this ever reach the controller page?
subprocess.call(["C:/Users/mrxbo/Desktop/Controller/ayylmao.bat"], shell=True)
return <-- return what?
yeah probably it ran into that
try printing out those compare variable and see if it satisfied the if condition
so instead i write
for testing?
return"<h1>Test</h1>"```
i haven't touch flask in a long time so i don't know redirect() is a reponse object
redirect supposed to accept url as argument
I see it now....your function probably also only caters for post requests.......
if request.method == "POST": But what happens when it receives a GET request. It has no response to return
just place a return render_template("authent.html") on the same indentation with the if statement
if request.method == POST: ... ... return render_template("authent.html")
I am getting this error in reactjs:
Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
Check the render method of `NavigationBar`.
My all exports and imports are all correct, I dont know why this error is coming i have tried putting export default in from of defining the components but still no luck. Please help.
The imports in NavigationBar:
import React, { Component } from 'react';
import './NavBar.css'
import {Container, Navbar, Nav, NavItem, NavbarBrand,} from 'react-bootstrap'
import { AiFillGithub } from 'react-icons/ai';
import { Affix } from 'rsuite';
The imports in App.js:
import React, { Component } from 'react'
import '@animxyz/react/dist/ReactAnimXyz'
import './App.css'
import NavigationBar from './components/NavBar/NavBar.js'
Please help
can you show code of Navigator Bar Component
import React, { Component } from 'react';
import './NavBar.css'
import {Container, Navbar, Nav, NavItem, NavbarBrand,} from 'react-bootstrap'
import { AiFillGithub } from 'react-icons/ai';
import { Affix } from 'rsuite';
export default class NavigationBar extends Component {
render() {
return(
<Affix>
<Container fluid id="navbar-id">
<Navbar expand = 'lg' sticky="top" className="sticky-nav" data-spy="affix" data-offset-top="197">
<NavbarBrand href = '#' id="logo-name">Invaderssss</NavbarBrand>
<Navbar.Toggler aria-controls="basic-navbar-nav" id="navbar-toggler" className="navbar-dark"/>
<Navbar.Collapse>
<Nav navbar className="ml-auto">
<NavItem className="nav-item">
<Nav.Link href="#" className="nav-link">Home</Nav.Link>
</NavItem>
<NavItem className="nav-item">
<Nav.Link href="#" className="nav-link">How to</Nav.Link>
</NavItem>
<NavItem className="nav-item">
<Nav.Link href="#" className="nav-link">Docs</Nav.Link>
</NavItem>
<NavItem>
<Nav.Link href="#">
<AiFillGithub />
</Nav.Link>
</NavItem>
</Nav>
</Navbar.Collapse>
</Navbar>
</Container>
</Affix>
)
}
}
@stable kite
change this tojs import NavigationBar from './components/NavBar/NavBar.js'this js import NavigationBar from './components/NavBar/NavBar'
No it is the same
try this```js
import React, { Component } from 'react';
import './NavBar.css'
import {Container, Navbar, Nav, NavItem, NavbarBrand} from 'react-bootstrap'
import { AiFillGithub } from 'react-icons/ai';
import { Affix } from 'rsuite';
export class NavigationBar extends Component {
render() {
return(
<Affix>
<Container fluid id="navbar-id">
<Navbar expand = 'lg' sticky="top" className="sticky-nav" data-spy="affix" data-offset-top="197">
<NavbarBrand href = '#' id="logo-name">Invaderssss</NavbarBrand>
<Navbar.Toggler aria-controls="basic-navbar-nav" id="navbar-toggler" className="navbar-dark"/>
<Navbar.Collapse>
<Nav navbar className="ml-auto">
<NavItem className="nav-item">
<Nav.Link href="#" className="nav-link">Home</Nav.Link>
</NavItem>
<NavItem className="nav-item">
<Nav.Link href="#" className="nav-link">How to</Nav.Link>
</NavItem>
<NavItem className="nav-item">
<Nav.Link href="#" className="nav-link">Docs</Nav.Link>
</NavItem>
<NavItem>
<Nav.Link href="#">
<AiFillGithub />
</Nav.Link>
</NavItem>
</Nav>
</Navbar.Collapse>
</Navbar>
</Container>
</Affix>
)
}
}
export default NavigationBar```
It's still the same
try restarting server
alright, wait a min
restarted the server, same : (
are you using create-react-app?
yea
which version?
4.0.1
do I use Flask for back-end development or JavaScript and learn something like next.js pleaseee help!
Which frame work is good for beginners
Flask is a good start
Django is huge so it's overwhelming for beginner
Ok , thank u
Morning! Does anyone out there know why I get this error message?
AttributeError: 'OAuth1Session' object has no attribute 'items'
I am using python 3 and this is my code that has the error:
headers = OAuth1Session(consumer_key, consumer_secret, token, token_secret,
signature_type='auth_header')
guys how i can use the default django page as home page XD?
i just liked the rocket
I'm creating one project a day for 30 days with Flask, to add to my Portfolio. If anyone has any project ideas, please let me know. Thanks!
Yo I need help
@native tide ?
I got some work that I can’t do, cuz I wasn’t taught. I was wondering if anyone could help me
I’d be willing to pay
describe your problem and show some code
Oh html
How does he want the website to look like?
Anything
As far as it’s done
Style, colour
Fonts
Style should be like dark@theme
Alot of dark shaded colors black brown
Ah hmm
Wait the due is yesterday
I’d pay for anyone who can get this completed
Yup he was given 2 more days cuz of his illness
Ah i see i see
Hope he will get better
Thanks
So can you help out?
I don’t have much money but I’d pay
@past cipher you can do one project a day? That's extremely efficient
Yeah, currently on day 3
I really enjoy Flask, and my prev projects have been really long
like CMS, eCommerce stores etc
so now doing basic shit like sharing lists between business groups, video streamers etc
it seems like a lot of work, but lots of my code is already created, like Auth, Profiles etc
i'm just trying to have a lot of shit on my Portfolio so I can get an interview
I'm confident once I get some interviews, I will get the job
I could talk the back legs off a donkey 🤣
anyoen do django?"
yes @hazy jungle
Is anyone interested in building a web front-end for an open source community project?
Hey guys,
I need some help regarding requests lib in python..
I am having an internal website using sockets and other resources, now I want to proxy my request from another server and render that website keeping the connection alive.. how to do that?
So the url won't be changed/exposed and the website would be shown..
Has anyone worked on this? Or can somebody guide me for some resources?
Flask Umm i got def named home and a home_post the thing is if 2 users need to use it it gives an error assertionerror: view function mapping is overwriting an existing endpoint function: redirect so what do i do now?
HELP
pls help
@past cipher
{% extends 'base.html' %}
{%block content %}
{% for post in posts %}
<article class="media content-section">
<img class="rounded-circle article-img" src="{{ post.author.profile.image.url}}" alt="">
<div class="media-body">
<div class="article-metadata">
<a class="mr-2" href="#">{{ post.author }}</a>
<small class="text-muted">{{ post.date_posted|date:"F d, Y" }}</small>
</div>
<h2><a class="article-title" href="{% url 'post-detail' post.id %}">{{ post.title }}</a></h2>
<p class="article-content">{{ post.content }}</p>
</div>
</article>
{% endfor %}
{% if is_paginated %}
{% if page_obj.has_previous %}
<a class='btn btn-outline-info mb-4' href="?page=1">First</a>
<a class='btn btn-outline-info mb-4' href="?page={{ page_obj.previous_page_number }}">Previous</a>
{% endif %}
{% for num in page_obj.paginator.page_range %}
{% if page_obj.number == num %}
<a class='btn btn-info mb-4' href="?page={{ num }}">{{ num }}</a>
{% elif num > page_obj.number|add: '-3' and num < page_obj.number|add: '-3' %}
<a class='btn btn-outline-info mb-4' href="?page={{ page_obj.previous_page_number }}">num</a>
{% endif %}
{% endfor %}
{% if page_obj.has_next %}
<a class='btn btn-outline-info mb-4' href="?page={{ page_obj.next_page_number }}">Next</a>
<a class='btn btn-outline-info mb-4' href="?page={{ page_obj.previous.num_pages }}">Last</a>
{% endif %}
{% endif %}
{% endblock content %}
guys
i learning pagination in django
and i run through a syntax error
in this line : {% if page_obj.number == num %}
and i get the message that says : add requires 2 arguments, 1 provided
any solution?
what project?
Anyone knows how I could format JSON text to highlight syntax correctly with JS ?
use something like https://highlightjs.org/
or maybe https://github.com/codemirror/codemirror if you need an embeddable code editor
seems good, thx! @indigo kettle
👍
nice! You got that set up quick
it's not difficult to use, only problem I had was on default it only highlights text that's already there so I had to read some docs
I am having a weird issue -- i am using an open source app -- been working fine, but now web interface becomes unresponsive at some point.
Uses flask, mmrpc, zmq, redis, angular -- mmrpc RPC timeout is the issue --- looking for a little steering/guidance in what direction I should be looking
Thanks
even w3 schools gets a bunch of JS errors, this makes me feel better 😄
@native tide I'm using Django as Backend but only for the users and data, in the other hand, Django isn't good for livestreaming and what I need to do is to capture the video and applying a Machine Learning algorithm for detection, all that in real time
I was looking for some information and everyone I read said Django isn't good for that
django has websocket support through channels. I haven't used it so I can't help much with it
So the Big Companies such Spotify and Netflix use C++ and Python for livestreaming
but sounds like something you might want to use
And Flask isn't good for big apps
https://realpython.com/getting-started-with-django-channels/
realpython usually has pretty good tutorials in my experience so maybe give this a look
Thanks bro, I'll take a look
also maybe check out https://fastapi.tiangolo.com/advanced/websockets/ if django ain't suiting your needs
FastAPI framework, high performance, easy to learn, fast to code, ready for production
I've looked information so far without succes
@indigo kettle @lucid vine thanks bros
good luck!
why did they say that?
I'd like to know that too, what would one be looking for in a framework for real-time tasks like livestreaming?
so hey goys does someone know or have some paper about calling ML model in php script
you can you any of them, the other one you not using can help with string quote in a string
Quick Django question, I created a "firstapp" and so I added it to the settings.py in the INSTALLED_APPS section, however when I save it it tell me that there are no module named "firstappdjango"... any idea why the name changed? I checked a few places and I can't figure out what I'm doing wrong.
show your INSTALLED_APPS
# Application definition
INSTALLED_APPS = [
'firstapp'
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
@safe sorrel you're missing a , after firstapp
ModuleNotFoundError: No module named 'firstappdjango'
so when you have two strings next to each other Python concatenates them
i.e. 'left' 'right' is the same as 'leftright'
yw
I need to align this messagebox on the right of the webpage, what should I do?
right next to the friends tab
how should I do it?
put it in the same div as friends div and float left
oh ok, thank you
you mean like on the website?
can anyone help me learn about foreign keys, how to set them, im seriously confused about them... for example
class Messages:
from = models.CharField(max_length=200)
message = Models.TextField()
class User:
...
messages = models.ForeignKey(Messages, on_delete=models.cascade)
``` how are they linked? i dont understand the relationship... one user, can have multiple messages, but how is it known which message belongs to which user?
and the documentation sucks
or is the link backwards, Messages needs an owner and linked the the User table
not the right place to ask that question, this is development, not scraping
my bad
from what i can tell scraping from flickr is against ToS so most people arent gonna be able to help you in here anyways
there actually no database ORM of 1 to many(only on design UML), the way you declare above is many User can have the same message (many-to-one)
yeah just realized. I'll redirect to other site that allows it.
the only way i can think of is reverse relation but that easily cause conflict
i swapped it to
class Messages(models.Model):
owner = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True)
username = models.CharField(max_length=200, null=False, blank=False)
message = models.TextField(null=False, blank=False)
class Profile(models.Model):
...
``` so each owner can have many messages
yes
when you declare foreign key you have to think in reverse with ORM
it's the concept of foreign key
one-to-many is only on graph
but how do i set that in create? i just pass the owner id to the messages? which links it the proflie based on that id?
yes you have to set id of the user
if you look at most message data it has a column user_id
usually in a request you can get request.user
yea, but it if person b was sending a message to person a then b wouldnt have access to user a other then from the form being filled out. thats what confuses me
technically, the message writer and the recipient would both need to be linked
when a person want to send message they need to click on the receiver first to know which one(which mean it already included sender/receiver id and name)
ya, but i can post a value to it just like any other query right? nothing fancy on the back-end i have to do right?
can someone help me 
depends? what do you need?
So
i'm trying to make a discord bot that recieves messages
I'm trying to run flask server and discord.py at the same time
but they don't work together
@native tide ask in #discord-bots they will probably know more about it then web dev
i dont know anything about flask or discord.py, but someone might know there as well. if your running both from the same server and not communicate it shouldnt be an issue, just run them in separate cmd lines. if you want them to communicate, discord.py would know more about that then anyone that only knows flask. just offering you help
discord.py itself is just one of python package, you can implement it in flask like normal module
maybe look into discord.py code to see which function you need to import into flask
Oh
I just went past it
and have new bug 😭
raise TypeError(
TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement.
172.18.0.1 - - [07/Jan/2021 09:13:33] "POST /webhook HTTP/1.1" 500 -
[2021-01-07 09:13:33,217] INFO in _internal: 172.18.0.1 - - [07/Jan/2021 09:13:33] "POST /webhook HTTP/1.1" 500 -
172.18.0.1 - - [07/Jan/2021 09:13:49] "GET /webhook HTTP/1.1" 405 -
[2021-01-07 09:13:49,136] INFO in _internal: 172.18.0.1 - - [07/Jan/2021 09:13:49] "GET /webhook HTTP/1.1" 405 -
172.18.0.1 - - [07/Jan/2021 09:14:33] "GET /webhook HTTP/1.1" 405 -
[2021-01-07 09:14:33,376] INFO in _internal: 172.18.0.1 - - [07/Jan/2021 09:14:33] "GET /webhook HTTP/1.1" 405 -```
hey erryone
well the error told you where you were wrong
app.py", line 2097 a view need to return a response
Anyone pretty good with django?
I don't have a line 2097 lol
from threading import Thread
app = Flask('')
@app.route('/')
def main():
return "Your bot is alive!"
@app.route("/webhook", methods=["POST"])
def webhook():
if request.method == 'POST':
print(request.json)
x = request.json["user"]
print(x)
def run():
app.run(host="0.0.0.0", port=8080)
def keep_alive():
server = Thread(target=run)
server.start()```
this is all I have
lol
yeah i read that wrong
Can you help? @gaunt marlin
def webhook(): <- this function need to return a response
yeah
how 
it's an url function right?
Nope
@app.route("/webhook", methods=["POST"]) <-
wait what?
apparently yes, I haven't worked with flask before :/
I'm not sure but maybe you need a return statement for the webhook function, because you're only checking the request method without doing any response
172.18.0.1 - - [07/Jan/2021 09:13:49] "GET /webhook HTTP/1.1" 405 -
[2021-01-07 09:13:49,136] INFO in _internal: 172.18.0.1 - - [07/Jan/2021 09:13:49] "GET /webhook HTTP/1.1" 405 -
172.18.0.1 - - [07/Jan/2021 09:14:33] "GET /webhook HTTP/1.1" 405 -
[2021-01-07 09:14:33,376] INFO in _internal: 172.18.0.1 - - [07/Jan/2021 09:14:33] "GET /webhook HTTP/1.1" 405 -
this part of the error is normal because you are only checking for post requests, you look like yout tried typing in a url so you get a get request error, your code only checks for post requests
anyone know how to filter multiple fields in django?
lmao that is a while, i dont think ever seen the post
are you talking about the admin or others?
no, i set a to and from field in my model, i want to filter the results when the to or from filed contain the user, so for instance, me and you are talking, the would make you user 1 and me user 2. i want to see both sides of the message, so i need to see both to you from me and from me to you. if you understand what im saying. when i query 2 it should look for 2 in both to and from not just to and not just from.
i don't understand what you just typed
please shorten the description without too much repeating words
are you making like a chat application?
or an invoice system?
how do i search in multiple fields for the same result. filter only accepts one query. i need SELECT * FROM table WHERE sender or recipient = userid
messages system similar to email, but much simpler
oh that is easy use Q for OR statement https://books.agiliq.com/projects/django-orm-cookbook/en/latest/or_query.html
ah ok, funny thing i actually looked at the page, just looked like a lot to take in at once
it worked, thank you
alright, now we are getting somewhere, ive linked tables using ForeignKey and then serialized them with the usernames from profile. and it worked correctly
this project looks huge, ive built 7 complete back ends for it to run, 7 actions, 7 reducers, and like 30 components. so much code.
can someone please help me here? thanks a lot!
https://stackoverflow.com/questions/65610907/django-rest-framework-put-and-delete-generic-view
@wicked elbow hey
personally i do them all separately in different viewsets. each having their own url paths. im not sure what everyone else does
whats up?
from flask import *
from discord.ext import commands
bot = commands.Bot(command_prefix=".")
app = Flask(__name__)
@bot.event
async def on_ready():
print("Bot started!")
@app.route('/webhook', methods=['POST'])
def webhook():
if request.method == 'POST':
print(request.json)
return 'success', 200
else:
abort(400)
app.run(host='0.0.0.0', port=8080)
bot.run("xxx") ```
so
I was trying again
but only 1 of them runs
idk what to do 😭
do them in seperate programs. and just have them communicate via ports.
communicate via ports?
well ports isnt the correct term, but for instance, i communicate to my server by making post or get requests. imagine a website pulling items from a database. id call a get request to http://localhost:8000/api to pull the data. then to create a new message to a database id send a put request to http://localhost:8000/api/add. thats what youd do if you needed your discord bot to save stuff to a database on your server. id assume youd use request in python. but i dont know specifics for your case
"over HTTP" would be appropriate
Hi there! 🙂
Anyone with GraphQL experience.... Why do some articles recommend that instead of throwing application errors, you return them as a response?
Ariadne recommends that: https://ariadnegraphql.org/docs/error-messaging
I find it highly inconvenient: many unions, extra code, and importantly, API users will be able to ignore errors.
so.. .why?
guys who here knows HTML?
Can I us e HTTP_REFERER as a success url?
I guess I could try oassing next but as I am using LoginMixing not sure how to do that
for example -->Page with the Mixin -->Login Page --> Back to page with mixin
Would like to get data from a csv file one row at a time every time getCSVData() is called through the JS file. Unfortunately I only get the first value on repeat.
<script>
const xtab = [];
const ytab = [];
function getData() {
//const time = {{csvtable_time}};
const price = {{csvtable_price}};
return price;
}
Plotly.plot('chart',[{
y:[getData()],
type:'line'
}]);
var cnt = 0;
setInterval(function(){
Plotly.extendTraces('chart',{ y:[[getData()]]}, [0]);
cnt++;
if(cnt > 500) {
Plotly.relayout('chart',{
xaxis: {
range: [cnt-500,cnt]
}
});
}
},1000);
Does someone know how I can solve this?
python file:
@app.route('/dashboard/<string:currency>', methods=['GET','POST'])
def show_plot(currency):
time, price = getCSVData()
return render_template('chart.html', title=namescurrencies[currency], csvtable_time=time, csvtable_price=price)
def getCSVData():
with open('ltc.csv','r') as f:
csvdata = [row.strip('\n').split(',') for row in f][len(xtab)+1]
time, price = str(csvdata[0]), float(csvdata[4])
xtab.append(time)
ytab.append(price)
return time, price
I'm not the best at Javascript, but from what I can see, your getCSVData() won't remember where it left off the second time you call it. It'll always start from the beginning.
I'm also not the best programmer, but one of the things you can do is keep track of the offset in the Javascript. So your javascript calls getCSVData(1), getCSVData(2), etc.
But that gets REALLY expensive REALLY fast, because now getCSVData() has to read everything and jump to the line you want.
Are you able to read the entire CSV, return it as a JSON object and let Javascript handle the rows one by one?
What do you recomend to display documentation for our API?
We're using a less common framework so no automated documentation really works
Very new to Django here and having issues with creating an app:
1- python3 manage.py startapp firstapp - ok
2- add app in INSTALLED_APPS in settings.py - ok
3- add app in urls.py:
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('firstapp/', include('firstapp.urls')),
path('admin/', admin.site.urls),
]
Gives me the following error: ModuleNotFoundError: No module named 'firstapp.urls'
I believe that normally I should get that error and even be able to run python3 manage.py migrate
**normally I shouldn't get that error
hey im curious
do you guys know how flask sqlalchemy handles the boolean values
because in my actual db, it's stored as tiny int
and i know tiny int is either a 0 or 1 value
so does the orm actually know to use 0 or 1 values?
and I guess if I'm doing conditionals based on this boolean value I need to use 0 and 1s as the constraint
instead of True or False?
@admin_bp.route('/dashboard', methods=['GET'])
def dashboard():
return render_template('/admin/dashboard.html', user=User().query.first())
@admin_bp.route('/dashboard/products', methods=['GET'])
def products():
return render_template('/admin/products.html', user=User().query.first())
Does anyone know an easier way to pass through user to all admin routes? Tryna clean up some code, and wondering if I an make this easier
There is about 12 different routes inside Admin
im not sure i understand your question
are you looking to find out how to restrict views based on position title?
oh I see you're using blueprints, I'm unfamiliar with those and how they work, though I do know their purpose
i do stuff like this
@login_required
@require_title(['Supervisor', 'Trainer', 'CEO'])```
using the login_required
flask login module
Basically, I have around 12 @ admin routes. Each time, I have to pass through user=User().query.first(). I wanted to know if there is a way I can write one line of code, and pass through User to every Admin route
True/False == 0/1
in alchemy
look at the flask login module, specifically the login_required call
what that does is basically restrict routes based on user title
so you just make your view and restricted based on titles
I understand that
But that is not what I need
I need access to the user variable in Jinja
oh sorry then
whay do i get this error in django
Can someone recommend a page that has good and friendly looking .png vectors?
Ping me
Hello! I have some problem with my flask application, when i use gunicorn with meinheld worker. I have tried to do the job with eventlet worker, and it works, but does anyone knows, that will this change cause any significant performance downgrade? And are they actually do the same thing?
eventlet will be more performant than a standard threaded worker
and I have read, that "gevent is inspired by eventlet but features a more consistent API, simpler implementation and better performance." (on it's pypi site). So wich one should I use?
Wouldn't it be extra expensive to jsonify it? And also, the csv file is being updated every 20mins so I also need to write a code that only adds the code that it did not add so far
Javascript is making me cry
Personally, I think file operations (opening/closing files) for x number of lines is going to be more expensive. The more lines you have, the more times you'll have to open/close that file. Opening/reading it once and manipulating it in memory would be faster in comparison as the number of lines increase.
Thanks for the tip! Really appreciate it 🙂
It's just that I cannot figure out whether it's expensive or not yet because it isn't working 😛
File operations are traditionally expensive.
I mean, it almost works. I only have one value in my plot now
Good to know!!
@native tide have you considered using a database rather than using a CSV? The only reason i suggest that is because if you can keep track of what your javascript already has loaded, you can query for additional info
example: if your data has an incremental primary key (a number that keeps going up), then your javascript can have a loop that will load everything after x
Yeah, I considered that but the storage space was a limiting factor. Didn't want to upgrade as it's just for a school project. Currently working on data analytics but showing a nice plot on a local website has definitely been the most time consuming part as I'm basically javascript illiterate
or if you track the time of your entries and the time of your query
@native tide i think a sqlite3 shouldn't take up too much space
but i mean, lol, yeah, there are lots of ways to optomize it, but if you need your chart to update every 20 minutes, then maybe you can make a new CSV every 20 minutes
I mean, I have CSV files of 50MB... so I doubt whether sqlite3 can handle that
i think you would be surprised at what sqlite3 can do 😄
it's not a pushover
it's not the greatest if you have a million hits at a time
but if it's a local thing and you have like, maybe 100 people at a time just reading, it's not too bad
Hahaha it's ok, I tried postgresql before but it had a storage limit of 10k rows so that was quite a bummer
Nah it's literally just one person or two reading it
It should be really basic
are you sure? because i don't know any known row limits in postgresql
I used the Heroku plugin
if heroku has a limit, that's a different problem
if you're reading it locally, maybe you can host it locally?
ahh I see, thanks for explaining that. Yeah so is it easy to host it locally if you're working on the same database with multiple people?
only if they're on your local network 😄 i don't know if your project constraints are
There are no constraints really. It just sounds like a fuss as your computer has to stay on the entire time. Hence I tried hosting it by Heroku
if it's for a local project, i don't even configure a httpd. if you're using something like django or flask, you can just boot up a development server
But I do like your way of thinking. I might actually consider refactoring this. But my main focus now is to get more than one point in a chart at this point 😛
I'm using flask! A beginner, didn't know that feature existed! The more you I know 🙂
I'm sorry to ask but do you happen to have any experience with charts in javascript?
not me, sorry. Javascript isn't my strength either.
@native tide but if you are interested in data visualization, you might consider looking at python libraries like panda
Yeah so the thing is, I'm using pandas for data analytics. I just save the x and y values in a CSV which I want to plot in a chart on a local website/user interface
Hence I need to know Javascript as well as the data comes in in real-time
wait
if you already have the data from pandas, wouldn't it be easier to just pass it along?
instead of saving it as a CSV, save it as a JSON
instead of reading the CSV line by line, just pass the entire JSON
But JSON is significantly larger than a CSV right?
no, that's true
but what i'm saying is, rather than getting python to cough up the CSV
just leave the file and let the httpd server the CSV directly
it looks like you don't even need all the fields in the CSV
I have no experience with that. Is it easy to use?
you can save a nice, complete CSV, but consider also saving a shortened one with just 2 fields
because you only need two fields
This is just a test file! Will have 2 columns eventually. This file is just 20 lines 🙂
no, i mean, your file from before, was 50mb you said?
does that contain all the columns or only the two columns?
Yeah but that's with a lot of other data given by an API as well. Hmmm I get what you're trying to say, I just don't know how to go about it rn
I just want to make it work and then refactor haha
Nothing except the data scraping and data analytics works (just the user interface is not working)
- flask should be able to just serve the contents of a file.
- the smaller that file is, the less you have to send over to the javascript, the less the javascript has to load
rather than processing your "big" CSV every time you need to load, make a pre-processed one saved somewhere that we can reference whenever we want. 🤔
that should get your file size a lot smaller
Exactly, so from these big CSVs, I'll make small ones with just two columns
yes 🙂 just a couple more processing lines underneath where you save the big CSV