#web-development
2 messages ยท Page 144 of 1
can you explain what you mean
return render(request, "main/home.html", {}) do you mean to add this/
Let me see your forms html
{% block content %}
<!-- This is how I edit custom things on top of the base HTML page. -->
<h1>HOME PAGE</h1>
<html>
<body>
<span>Hello, {{request.user}}</span>
<span> <a href="logoutpage"> Logout </a></span>
<br><br><br>
<form method="POST" action="">
{% csrf_token %}
<input type="text" name="stock_type" placeholder="Stock please..." class="username_class"><br>
<input class="submit" type="submit" name="UserCreate"><br><br>
</form>
<h2> OPEN ${{ open_data }}</h2>
<h2> CLOSE {{ close_data }}</h2>
<h2> HIGH {{ high_data }}</h2>
<h2> LOW {{ low_data }}</h2>
</body>
</html>
{% endblock %}
So when you are submitting this form the info are being sent to the same url of the page you're at because action is empty
In your urls file create a new path to the view yeetman
And puth that path in action
but yeetman is simply a function
why would I need to add a path?
it's not a wepage
web
And how do you trigger that "function"
hey guys, i want to know how i can make bootstrap cards move on their own. so basically i have these cards right, and im using django to have a for loop and the amount of things Django returns is th amount of cards that are created right. so basically, if my database has 3 items, Django is going to create 3 cards, but right now it will only be created by going down. how can i set parameters to where the cards are pushed. because i want to first: check if the cards are approaching the bottom of the screen and then secondly: check if the cards are overflowing to the right. how can i add those 2 parameters to the the html so that the card divs can be placed appropriately to the resolution of the window
can you please ping me if you have a input, thank you
You can simply put the content of the second view in the first one in your case
like nested?
Nono
Yes just remove it
ok
I removed it
@login_required(login_url='/loginpage')
def home(request):
stock_has_been_selected = False
if request.method =='POST':
stock_type = request.POST.get('stock_type')
#Code for open, simplifed and cut down to 8 decimal places and no brackets.
if stock_has_been_selected == True:
my_share = share.Share('TSLA')
symbol_data = None
data = my_share.get_historical(share.PERIOD_TYPE_DAY,0,share.FREQUENCY_TYPE_DAY, 1)
open_price = str(data['open'])
open_price = (open_price.replace('[', '').replace(']', '')[0:8])
close_price = str(data['close'])
close_price = (close_price.replace('[', '').replace(']', '')[0:8])
high_price = str(data['high'])
high_price = (high_price.replace('[', '').replace(']', '')[0:8])
low_data = str(data['low'])
low_data = (low_data.replace('[', '').replace(']', '')[0:8])
context= {
'open_data': open_price,
'close_data': close_price,
'high_data': high_price,
'low_data': low_data,
}
return render(request, "main/home.html", context)
return render(request, "main/home.html", {})
this is what we are working with now
Try submitting now and I'll be right back in abt 15 min
could anybody help me with a design question?
my user connects to my server via websocket and receives intraday stock information. I want short-term storage of stock prices and other information - cached data for the day. is redis suitable for this?
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
!kindling
Kindling Projects
The Kindling projects page on Ned Batchelder's website contains a list of projects and ideas programmers can tackle to build their skills and knowledge.
Q) What do y'all think about Serverless Flask? Is it a good implementation?
Hi guys! I was wondering if either of you could point me in the right direction as my current project isn't in my area of expertise.
I store my (anime)series' ratings on an online database (and have access to their API) -I need to re-rate most of the series as most of my tastes have changed over the past 3 years.
I wanted to build an web/or any other interface to help me rate these at speed (using my keyboard only). I was initially thinking of doing this using pygame? Since that's the only GUI library that I have somewhat experience with.
But I was wondering if you guys knew of any other "easier" or elegant way I could get this interface setup quickly.
My main area of comfort in Python is data science, so this just feels quite daunting to me :S
Would you say its quicker to loop over 10,000 rows than delete 10,000 rows from a database ?
the row contains two columns: ID, Item
The problem I'm facing is user can create a product, and sell items. they could add 10,000 items for example. When they update the items, I need to compare the new items vs the old items, and update the items inside the db
i'm stuck on whether to just delete all the rows, and then add the new items
or compare the two lists, and then add rows to the table that don't exist already
check the log
i've heard good things about it. sure, go for it if you like devops ๐
thats not the full error
i've not used it with pygame, but you could do this quite simply with javascript/html. You could make an API call loading a series, listen to key presses (1,2,3,4,5) for stars, and once the user clicks a button, make an API call back to your server to update the row in the database. Then just repeat ๐
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
ModuleNotFoundError: No module named 'django_project.wsgi'
?
thats your error
thanks
I have an issue linking my react app to my AWS DRF API while fetching data : on chrome, cors is allowed and data fetched, but on firefox, I have a CORS failed, can't find jack on the internet, does anyone have an idea?
all cors settings have been written in settings.py
I got a new error using heroku ERROR: Could not find a version that satisfies the requirement ltgraph==0.17 (from -r /tmp/build_0d89645f/requirements.txt (line 1)) (from versions: none) remote: ERROR: No matching distribution found for ltgraph==0.17 (from -r /tmp/build_0d89645f/requirements.txt (line 1)) remote: ! Push rejected, failed to compile Python app.
what are your allowed origins? did you specify it as *?
Yes I did
๐ค , what's the exact error in the server / client sonsole?
and on chromium
I don't understand French ๐ฅด , but I guess it's saying there is no same origin header from CORS?
Sorry this is in French but I am sure you can identify which error it is in english
yes correct
by the way, I am on "Strict mode" for Firefox, could it be the issue?
not sure - but that error is due to your CORS enforcing the same origin policy, the origin of that request is not included in the CORS settings. (which is strange, as you've specified the settings are fine).
Yes, considering it is working on chrome and edge, this is quite strange indeed
thanks for your help ! ๐
hmm... I sense that may be an issue that trips CORS, since they're different protocols & therefore different origins.
you could try use ngrok to quickly get https for your site (if it's running on localhost) then retry
React app is running on my machine (localhost) and the DRF API is running on aws ubuntu server
I will check on aws how to get https protocol for my instance
it will be your frontend which will have to utilize https, i'd recommend ngrok for that. I'll admit that's a strange error though ๐ฅด
I will reset firefox settings and try again, might be the issue too
will try ngrok as well, thanks for your precious time !
Ok found the error ! in my firefox settings : "activate https only" was ticked, I switched to "Do not activate" and now it works like clockwise. Phew....
when i run my flask app, request.values.get immediately returns None in the console, so i get a keyerror when it tries to retrieve the value of None in the dictionary
from flask import Flask, render_template, url_for, redirect, request
app = Flask(__name__)
d = {
"ๆ": {
"eng": "I, me",
"pin": "ng4"
},
"ไฝ ": {
"eng": "you",
"pin": "nyi4"
}
}
@app.route("/", methods=["GET"])
def search():
hanterm = request.values.get("term")
print(hanterm)
# if request.method == "GET":
# return render_template(
# "results.html",
# title=hanterm,
# postdata=d[hanterm],
# )
return render_template("index.html", title="Search")
if __name__ == '__main__':
app.run(debug=True)
my html form:```html
<form method="GET" action="{{ url_for('search') }}">
<fieldset class="form-group">
<legend class="border-bottom mb-4">Search term:</legend>
<div class="form-group">
<input type="text" placeholder="Type here" name="term">
</div>
</fieldset>
<div class="form-group">
<input type="submit" value="Search" name="submit">
</div>
</form>
good find! good luck with your project ๐
Hello, I need some help. I get this error: `ImportError: cannot import name 'pathlib' from 'django.urls'
and I actually can't find pathilib in directory. I reinstall django but doesn't help
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('flowers/', include('flowers.urls')),
path('admin/', admin.site.urls),```
any idea?
yea
I kwno where was a problem
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<a class="navbar-brand" href="/">My Website</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbar">
<span class="navbar-toggler-icon">
</span>
</button>
<div class="collapse navbar-collapse" id="navbar">
<div class="navbar-nav">
<a class="nav-item nav-link" id="featured" href="/featured">Featured</a>
<a class="nav-item nav-link" id="sign-up" href="/sign-up">Sign Up</a>
<a class="nav-item nav-link" id="login" href="/login">Login</a>
<a class="nav-item nav-link" id="logout" href="/logout">Logout</a>
</div>
</div>
</nav>```
hi! im using flask and i have this bootstrap navbar. i wish to make it so that the part of the website you are currently on gets highlighted on the navbar.
on bootstrap's website, it says to do this:
but im confused on what to do
do i need to add front end code to add the attribute automatically
im using jinja btw
Doing a live video on django deployment from scratch, anyone interested ?
[flask]
I really don't understand the db.session thing.
I wrote this method for my model
would this work in my case?
def set_customs_state_to_successful(self):
self.declared_to_customs = DeclaredToCustoms.Succesful
db.session.commit()
looks like the build crashed when installing dependencies, are you using a requirements.txt file?
absolutely!
maybe something like:
{% if condition %}
<a class="nav-item nav-link active" id="featured" href="/featured">Featured</a>
{% else %}
<a class="nav-item nav-link" id="featured" href="/featured">Featured</a>
{% endif %}
yes thats what i was thinking
thanks
i was wondering if there was a more efficient way
or something
i wonder if i can do:
ideally this could be implemented using a little bit of javascript, such as getting all anchor tags in the navbar, grouping them into some sort of array in javascript with a dataset of the url maybe, then compare the window.location. with the dataset of each one and highlight the one that matches
<a class="nav-item nav-link{{ ' active' if cond else '' }}" id="featured" href="/featured">Featured</a>
is that valid
lemme see
i dont think that will u might get a parsing error
because from my experience with template language i have to use and endif
I have a question about selenium
how can i write like that
wdym
code format
like it is in a box
bot my messages is normal
but*
'''py
something
'''
if you're not pasting python code then put the file extension of the code you're writing
the character is `
it should be in the top left of your keyboard
how can I take images input and store them sqlite db in flask
thats actually pretty cool ngl
how do i make the short error (text below "404 not found") display on one line?
@errors.errorhandler(404)
def page_not_found(e):
error_parts = str(e).split(": ")
return render_template(
"error.html",
error_short=error_parts[0],
error_long=error_parts[1]
)
{% extends "base.html" %}
{% block title %}Error{% endblock %}
{% block content %}
<br>
<h1 align="center">{{error_short}}</h1>
<h4 align="center">{{error_long}}</h4>
{% endblock %}```
Yes I am using requirements.txt
It's a web framework
Ah ok
It is hell to deal with when unchained ๐
is there a way to set a custom error page for only some routes in flask?
@native tide You can set it on a blueprint.
is it possible to get the raw querystring values (as bytes, not str) from an aiohttp request
without reparsing it
I basically have a URL-encoded binary blob, and it's being interpreted as unicode
I can only find this on it https://github.com/aio-libs/yarl/issues/425
which may be the most unhelpful github issue I've ever seen
Hello everyone, i am using pre_save signal to change the path of the files that saved into my database, and i am having a problem : here is my code if someone have an idea on how to fix it.i worked soo much on it but i am blocking please some help...
https://del.dog/hiwowyning
the error i got is : can't set attribute
''' models.py '''
class Media(models.Model):
'''Defining the entries'''
title = models.CharF
what line?
what do you mean please?
actually, what is the full error trace
the code i put is here just to explain what i did!
well the error i got it on my debug mode
but can we juste do a setter on the "media" class to update the url attribute ?
of a ImageField ?
hmmm, I'm not really sure. I haven't used django that much
is there something like
Traceback (most recent call last):
File "Z:\code\pytracker\pytracker\src\app.py", line 33, in announce
peers = await peer_list.get_peers(peer, info_hash)
File "Z:\code\pytracker\pytracker\src\storage.py", line 79, in get_peers
if not (peer.info_hash == info_hash):
AttributeError: Cannot set attribute
in the logs?
It will look slightly different, but it tells what the error means
how can i got the logs? (i am not too much used to use django since i use it just for the django-admin panel) all the logs i can have is from my docker
maybe i have to execute a command on the docker of admin?
What's your error message?
My guess would be that the error lies in the setattr functions (which I would avoid using, by the way) - but we're going to need the error message.
where can i see the error message, because my runserver didn't return any error
i only got it with the interface on the debug mode
and my message error is "can't set attribute"
oh, I found your error, here it is:
setattr(instance.picture,"url",'media/{}'.format(instance.picture.url))
and
setattr(instance.picture,"url",'media/{}'.format(instance.picture.url))
Firstly, I would not use setattr. The first line is equal to saying:
instance.picture.url = media/{}'.format(instance.picture.url) which is better in terms of readability.
the url of your picture is read-only, you cannot set it.
so how can i set it? the problem is my media are in the folder media/.... and when i set it on the settings.py, so to save in the database the url as media/... not only the_path_to_picture that's why i am trying to do it like that
do you think there is a way to update the "url" on my database
I don't know what you're trying to do. I would give instance a new picture and then use that url for whatever you're using it for...
I will explain my problem, maybe there is a simple solution than doing it with 2 signals haha!
my problem is that i save my medias on the media/... folder i defined on the settings by MEDIA_URL = '/media/' , so everytime my Imagefield save a new picture it stores it to media/path_specified_in_Imagefield, but i would like to save the data on my database with directly the true path to my pictures and by that i mean media/path_to_picture
I don't really work with media files that much, but could you change your picture's name to its url? Pretty sure the name is not read-only like url. That way your files will have their urls as their names - with some trimming down of the path that is
also I don't understand why you'd want to do that in the first place, doing:
setattr(instance.picture,"url",'media/{}'.format(instance.picture.url))
would give your picture the wrong url and serve nothing in benefit. Just change the name of the picture instead and don't worry about it.
Any beginner friendly tutorials I can watch or listen to?
man... learning Celery and about RabbitMQ is really cool - I've been down a rabbit-hole today. It's got me wanting to write articles on it
I learned from Youtube videos. Any decent tutorial should give you a good baseline.
@chilly falcon justdjango.com
Also look into courses for django in edx
Cs50 web goes into django as well
yep i was learning from yt but i want some kind of road map . where i could know what to learn first like project base.....
ok bro i will search those things thank
wtf
does anyone have a solution for this problem?
"This file is empty" in github , I was trying to upload my django project
@chilly falcon https://m.youtube.com/playlist?list=PL-osiE80TeTtoQCKZ03TU5fNfx2UY6U4p based on my experience with his playlist on Flask, I'd highly recommend Corey Schafer. Will start his Django tutorials soon.
Thank you
Can someone help me set up the NGINX configuration for websockets? I have a server already set up for WSGI, but I need to change this to accept websocket connections.
can anyone tell me diffrence in this two?
def signIn(request):
return render(request, 'signin.html')
def signIn(response):
return render(response, 'signin.html')
How do y'all prefer to write tests for your Flask/Django applications?
depends whether it can be localised tests in the code or whether its unit tests via postman etc...
i did not used test till now i am new and learning
i saw different ytber are using request and respose in there views
hey guys, i want to know how i can make bootstrap cards move on their own. so basically i have these cards right, and im using django to have a for loop and the amount of things Django returns is th amount of cards that are created right. so basically, if my database has 3 items, Django is going to create 3 cards, but right now it will only be created by going down. how can i set parameters to where the cards are pushed. because i want to first: check if the cards are approaching the bottom of the screen and then secondly: check if the cards are overflowing to the right. how can i add those 2 parameters to the the html so that the card divs can be placed appropriately to the resolution of the window
can you please ping me if you have a input, thank you
I think, maybe writing some custom css, to handle that can help
for django use pytest, i usually use pytest with unittest ๐
same for flask, i guess
What's the testing methodology?
Do you run all get/post requests with mock-data?
Do you check the response codes only or do you also check if the desired output is received? If yes, do you call an instance of the function that converts input to output, in the test to check if the response matches
yeah, I'd test my models / classes and test that the output is what I expected, you would repeat this until you think you've covered most bases with your models.
same thing goes for API endpoints, just test everything
hi! i have this style code in base.css
i've imported it here in my <head> for base.html
but it doesnt seem to apply
if i add the CSS inline with <style> it works, but not if i <link> it
cz you are not really linking to the CSS file
you should add the full destination
or
ok
oh
{{ url_for('static', filename='style.css') }}
found that in flask docs
thanks
tf
still doesnt work
this is my file structure
not sure how you do it with flask
i figured it out
<link rel="stylesheet" href="{{ url_for('static', filename='css/base.css') }}" />
also, this <h3> doesnt seem to be affected by my CSS
if i change it to an <h1> it works as expected
body { background: #2a2b2a; }
h1, h2, h3, h4, h5, h6 { color: white; }```
this is my CSS
Hey guys
I have an integer field in my model with choices as:
COLLABORATORS_ROLES = ( ('', '-'), (0, 'Author'), (1, 'Co-Author'), (2, 'Editor'), (3, 'Peer Reviewer') )
Currently when I serialize my model, it returns the integer value of the roles (again since it's an integer) but is there a way to get the value like 'Author' instead of integer?
to serailize, I'm using the django.core.seralizers.serialize
it's always going to save within the field as an integer. however you can just use the value in the integerfield and parse it to return the author you want in your view
parse it how?
Sorry I'm a bit confused on the topic
i.e. you have a dictionary {integer: author}, you can use the integer returned to get the author you want
Hey, I'm trying to create a database in flask, by importing db in the shell then calling db.create_all(), but it doesn't create any file in my directory
I can introduce items manually, like this, but after I quit the shell the item isn't there anymore
Pycharm with material theme
Ohh niceee
You still need help?
Ok, take care
Did you fix your issue?
yeah, I copied some code from github and it worked, idk why tho
well the db was created, but it only worked in that specific session, if I closed shell and tried calling Item.query.all() I wouldn't get anything
and the file.db wasn't created either
So i guess it was in memory then
If you didn't have actual db file in case you use sqlite as your db
not in the browser
but
if you're running in a non-browser environment
e.g. Node on the backend
it's defo possible
I think majority of browsers provide same environment/api
Usually there's no specific stuff that you should care about i guess
Because js is usually used with some kind of framework at least in recent 2-3 years
Do you guys know how to fix this problem in heroku "Server Error(500)". I am using django
There's error in your django application
Run it locally and see what error is
Or check logs on heroku if there's any
Basically django will return 500 if anything went wrong in backend (usually if exception was raised)
ok I will try
I think it is a standard for entire web, any 400 error is client side error and every 500 means problem is on server side, zero can be any number
yep there is a problem in the web
not loading static files
C:\code\python\django_project\env\lib\site-packages\whitenoise\base.py:115: UserWarning: No directory at: C:\code\python\django_project\django_project\staticfiles\
warnings.warn(u"No directory at: {}".format(root))```
It cannot find directory, double check your path first, you may have a typo in dir name
Do you have this line?
os.path.join(BASE_DIR, 'static'),
)```
nope
Try it
still the same
I googled a bit and seems to be popular, try this https://stackoverflow.com/questions/53694341/heroku-django-deploy-why-am-i-getting-an-error-500-with-successful-deploy-and-s
I will try, thanks ๐
I would suggest you to google this, i am not master with heroku so this way it will be faster for you i think
Hi, I'm using django and I'd like to know how to reproduce this form: https://paladinsdecks.com/nc/decks/new-deck/androxus/
Especially the card selector. I can do the other fields, but the card selector I've no idea how to do it, even though I've already googled how to make this.
This is behavior i want. thanks for helping.
Create and find decks for Paladins, a hero first person shooter developed by Hi-Rez Studios. Browse champions, decks and even cards to find the best loadout for every champion!
are you by any chance running in production mode?
yes
If it's in production mode Django wont server static files as by design thats left to something like Nginx or Apache to serve
as python is inherently slow at serving static content.
so it should not be this?
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
im not sure about the context on this one
its not anything todo with your code
it's todo with the fact that it's designed for deployment not development
rip, well time to switch to flask
when in debug mode for development the testing server will serve content
flask wont serve those files anyway
if you're just debugging use the debug / developing use the debug mode
in your settings.py DEBUG = True
if this is for deploying your app then the tutorial is taking you down the standard reverse proxy route with nginx protecting your python workers and serving static content
Why? ๐
django and heroku is hard men ๐ฆ
Maybe this would help though
Flask is harder to develop apps with
I should probably study more cuz I haven't mastered django yet ๐ฉ 
Hello There,
So I was making a dashboard but I want to list all discord emojis to choose one from them. How I can implement this stuff, I have seen this same thing on many websites
its tough deploying anywhere for the first time, even if django has all these tools that make it easy. have you heard about gunicorn yet?
if you want an easy way to serve static files in production, look into whitenoise
Yep but I dont know the use gunicorn and whitenoise
gunicorn looks for an application variable, so the most common way i run a WSGI django project is by doing gunicorn <my-project>.wsgi
and to be fair, i googled every error and managed to work things out
and when configuring whitenoise, add the middleware to settings.py:
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
...
]
and this is what i use
STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage'
greeting everyone, i want to know something I am really confused at it it is (api) please I want it in the simplest concept .
@mystic wyvern lets say you have a SQL database full of all sorts of data
ok
you cant just access it by messing around, if you want to access it you have to write a sql command. sounds fair?
you can automate this by using flask, for example
you can write some code in python that will access the database and do whatever you want
but lets say someone else doesnt know any python or SQL
how would they get something from the database? well they could talk to you
if i tell you to get me a picture of a dog from a database, you could do that using flask, django, sql, etc. right?
i dont even need to know python, as long as you can take care of it for me
and you can "do your thing" and return to me the picture of a dog
i don't have to know anything that you are doing as long as i know how to talk to you
that how i like to think an api works
and if you can provide me with consistent pictures of dogs, then i can rely on you to build a dog website, for example
so if a user were to visit my website, i would "ask" you to give me dog pictures, and you would return pictures of dogs for my to display
did this clear anything up? @mystic wyvern
to some extent yes
ok cool, this is how i like to imagine api's work
i think that was clear enough
keep in mind an api can work with other things. have you used javascript before?
ok :)
yeh
I am currently learning it
so you may or may not know that javascript supports game controllers as devices
all those features that javascript provides for the game controll is part of an API
the API can access each button press, and many other properties for you to access
@mystic wyvern Api is basically an interface through which you can manipulate code written by someone else through your code. It can be
set of functions/methods
rest api
Or something else
@wooden ruin I appreciate that for you, thank you a lot
that's like how libraries doing?
yep, or you can make your own api
makes it useful when developing the backend and frontend independently
if an api is well documented, then its easy to use and understand
Code:```py
def get_all_accounts(payload):
"""
Responds to a GET request to /api/v1/accounts
Reads all accounts from the database
:return: JSON representing accounts or 403 if invalid token / insufficient permissions
"""
...
return [_account_to_json(acc) for acc in data]```swagger.yml```yml
/accounts:
get:
operationId: accounts.get_all_accounts
tags:
- "Accounts"
summary: Read all accounts from database
description: Read all accounts from database
parameters:
- name: payload
in: body
description: Auth token
required: True
schema:
type: object
properties:
token:
type: "string"
responses:
# ...
Curl request: py
curl -X GET 127.0.0.1:5000/api/v1/accounts -H "Content-Type: application/json" -d "{"token": "token"}"Error:py
TypeError: get_all_accounts() missing 1 required positional argument: 'payload'```why isn't the payload parameter getting passed to the function?
what is replacereducer or what it does ?
It's redux store's api, i'm not sure but i guess replaceReducer accept a new reducer as argument and replaces the older reducer which is registered as rootReducer.
@naive sparrow @wooden ruin thanks for you guys โคโค
you can't sent data through GET request, change method to POST @rigid loom
I already have a post though
Which is for creating a new account
So I guess I'd have to move that?
You can't sent request body along with get request
does anyone know why my websocket isn't firing the onmessage function?
// js
const ws = new WebSocket("ws://127.0.0.1:8000/datastream/")
ws.onmessage = (payload) => {
const data = payload.data
console.log("data received")
console.log(data)
}
The websocket is accepted by my server, and I send back a response (w/ key "text")
# consumers.py
def websocket_connect(self, payload):
self.send({
"type": "websocket.accept",
"text": db.get(all_keys=True)
})
But my JS onmessage function isn't recognizing it. Can I not send data payloads when accepting websockets? I guess the connection is not yet established completely so I won't be able to send data like that?
@opaque rivet did you include websocket cdn
Check console if there's any errors or warnings
no, I'm using django channels but my websockets are connecting fine. I think the issue is that you just can't send a payload when accepting a websocket connection.
Sorry can't help with Django, i'm javascript dev :)
gotcha, I'll just have to read about them a bit more, I think I'm onto a workaround though, I'll see if it works ~5mins
ws.onopen = () => {
ws.send(websocketEnum.Initialize)
}
ok works now :),
- websocket request is sent to server,
- server sends a response accepting it,
- client sends a request saying "I'm ready"
- backend sends required data
def websocket_receive(self, payload):
if payload['text'] == 'initialize':
self.send({
"type": "websocket.send",
"text": json.dumps(db.get(all_keys=True))
})
thanks for the help ๐
from my experience you can only send certain things. if i ever need to send JSON back to the websocket, i just use JSON.stringify in javascript, then just use json.loads in the consumer. are you using WebsocketConsumer for your class?
yes, using SyncConsumer
but it leads me to another question
for RESTful APIs, you can have multiple functions in one (e.g. handling GET, POST etc.) - is it the same with websockets? it seems like each websocket endpoint can only do one function, unless my frontend is sending some sort of status message like "update", "initialize", etc. does that make sense? how is it done usuaully?
since we are dealing with non-http here, it's difficult to imitate other methods. look into socket.io if you want to have more custom events such as emit. as for now, my go-to is to have 1 consumer method that receives any messages, looks for a status in the body and redirect to the appropriate function. it's not the ideal setup but it keeps things semi-organized, and i can always split the websocket into 2 separate routes if i need to
ok cool, websockets are looking nice so far ๐
definitely going to use em for future projects
absolutely! also, look into django signals as well. when paired with django channels, it's a really cool and powerful combo :)
mhm, working on redis-specific signals atm and hopefully I'll be able to send frequent updates from the server
hmm so on the topic of signals... for example on post_save (or similar), would you send a signal within a channel group to send an update to every client in that group?
yep, to me it's a great usage for broadcasting events
so if a new user is registered you can display it live
so new users can kind of see how "active" it is? if that makes sense
it would also be a good idea in terms of web gaming or, more importantly, database verification
saves time instead of processing everything in one view per request
ah I see. I haven't yet learnt about channel layers / groups, and I was trying to listen to redis updates within the syncConsumer itself ๐คฆโโ๏ธ , but I think channel layers is what I need.
essentially just need the signal to push data to the client via the websocket, to all clients connected to the "channel". will channel layers solve this?
channel layers allow you to group your consumers, such as with chat rooms: if youre in a chat room, you can't see the messsages of another one. for this one you won't even need channel layers. or, you can put every user into 1 big channel layer and broadcast to that layer whenever you recieve the signal
unless, you are grouping your clients somehow, maybe based on authorization/access or any factors really
all my clients should be grouped together in one pot.
so by my understanding, I can register all the clients to a channel layer and then broadcast data to all of them at once?
yep, using the self.channel_layer.group_send method
it's going to need a workaround, though, because you need a staticmethod to connect if you're using django signals
def get_user_updates(sender, instance, **kwargs):
try:
name = instance.first_name + " " + instance.last_name
i = UserConsumer.connected_users[0]
async_to_sync(i.channel_layer.group_send)(
i.name,
{
"type": "message",
"message": name + " has registered for an account!"
}
)
except: pass
this was my implementation of this
i wont be using the django signals, but something similar (for redis). I'll just need to broadcast based off a conditional:
if i_need_to_update_client:
layer.broadcast...
^ something like this
big thanks for the help!! I was trying to implement channel layers without knowing what they were, I really appreciate the explanation ๐
no problem! i know this stuff was difficult for me when i first started, so i know how it feels
as a last note before i have to go, do note that the redis signal function you might be implementing can't really know whether to send it or not, such as if no users are connected. it's best to keep track who and which users are active, and I store them in a list, and remove them fromthe list when the client disconnects. that way i have all my users in a list ready to go, and i can message any one of them should i need too
can someone help me to why this isnt working <button type="button" href="/dashboard/{{ guild['id'] }}" class="btn btn-success pull-right">Go To Dashboard</button>
its not rerouting it to that link
nope
here is whole thing @wooden ruin
{% block body %}
<section id="main">
<div class="container">
<div class="row">
<div class="col-md-9">
<div class="panel panel-default col-md-offset-3">
<div class="panel-heading main-color-bg">
<h3 class="panel-title">PLEASE SELECT A SERVER</h3>
</div>
<div class="panel-body">
<div class="well well-lg">
{% for guild in render_guild %}
<h4>
<img class="img-responsive" style="display:inline-block; height:30px; margin-top-5px" src="https://cdn.discordapp.com/icons/{{ guild['id'] }}/{{ guild['icon'] }}.png" />
{{ guild['name'] }}
<button type="button" href="/dashboard/{{ guild['id'] }}" class="btn btn-success pull-right">Go To Dashboard</button>
</h4>
{% endfor %}
</div>
</div>
</div>
</div>
</div>
</div>
</section>
{% endblock %}```
anyone aware of something that can load twittesrs bookmarks into something one constrolls oneself?
guys can someone help me set up a virtual environment?
It seems that I can't define a template, despite having the right location of my html template. I have my index.html file in msg/templates/msg/index.html
this is the code I am using ```py
def index(request):
return render(request, 'index.html')
It says that index.html cannot be found
Isnโt it located in msg directory?
msg/index.html
This is the path you gave
yeah
Render will look into templates directory, but you added a msg directory. Try it with msg/index.html to see what it says
it still can't find index.html
TemplateDoesNotExist at /index/
msg/index.html
That's weird
It's looking here for my templates
AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\admin\templates\msg\index.html
That's one of the places it looked for the tempalte
template*
which onej
@opaque inlet what is your project tree ? Is template located in your app?
Following django doc (https://docs.djangoproject.com/en/3.1/topics/http/shortcuts/#django.shortcuts.render)
It should be msg/index.html
But since you created a directory
Should it be msg/msg/index.html?
I don't believe so
I went to the directory that django was looking for and I don't see a msg app there
Yeah, my templates aren't there
Maybe those could be the alternative templates that it would be looking for?
I believe django is also the right version
3.1.6
ok I fixed it
So basically, I defined DIRS and had the path to my templates folder
and it returned the index.html file that I was looking for
where are you giving the context in your flask/django app?
I figured out that problem but I have a different problem how do I get a guild with an id in my flask app
I am making it so the dashboard has myip/dashboard?code=accesscode&id=guildid
but I cant figure out how to get the guild stuff
if you are able to get a guild's id within the function, then all u have to do is query your database for the guilds id
so something like SELECT * FROM guilds WHERE id = 1 or something like that
ok so I have to make a database with guild info
yes, assuming you want to store the info of each guild
I already have a database but I mean a table
yep
yes
I already have that but it doesnt have the guild name in there
so I will make a different section with the guilds name and some other info in there
start by planning out your table - plan out every field per row, and what kind of fields they will be. then you can query a guild by its id, name, etc.
I am using mongodb so I can edit it but yeah I want, id, name, amount of users, and maybe who the owner is
you would likely want to create a user table then and use a foreign key in the guild table
wdym
So I have an existing game engine package I've written for blackjack and want to use it to supply the logic for a javascript/css-based web interface, would flask be a good package to learn for this purpose?
I might do customizable rock paper scissors first because I have an engine written for that too
some guy told me to get help here
it has no issues, i just want to somehow compare "test" to a string with an if statement but idk how
@serene plover if test == "something":
ik but like
wow flask is neato
print(test) is
<div class="ac-logo"></div>
</div>]```
what kind of comparison do you want to perform specifically
test is not a string btw
it's a ResultSet
i want to compare test to
[<div class="title-wrap"> <div class="ac-logo"></div> </div>]
with an if statement
that seems like a strange thing to compare to. What are you really trying to determine?
so like if the contents of the link has that html code:
why?
that's not something you would generally do
rn im trying to compare the contents of the given link to that html code
and accordingly
and its part of a simple small program
it's not easy
to do that with BS4
because
that's actually a BS4 object
that represents some HTML
it's not raw HTML
I mean
you could (though I don't remember the API)
presumably .html or something
then compare it to a string
but that's p weird
if its hard with bs4 i can try using other scraping modules
but still i dont know how to compare the url contents to an html code
do you understand why I say it's weird
or what I meant by this
in django auth_user of what type of user??
i mean auth_user table in django databases??
How do you guys save global variables in flask. I have used a dictionary to keep values that was inputted and the dictionary always omit some dictionary keys whenever it is deployed
in development, it's fine but when lots of people access it, it gets an error. I think it's because there's a lot of people accessing the same dictionary.
What would be an alternative of a global variable that doesn't get errors whenever it is being modified by different web browsers?
How to store images in SQLite db with flask SQL alchemy
user database instead of global variable
don't try to save global variables, in multi-core deployments different instances of flask will not know about each other; you should be saving data into a database
how to add preloader to a webpage that will run until the page is loaded
it's django's User model (the default model for your users)
Hey, i need complex help
Can someone?
i have this ```py
def add_values():
file = open("templates/index_graph.html","a")
file.write("<body>\n")
for name,key in difference.items():
file.write(f"<tr><td>{name}</td><td> {key} </td>")
file.write("\n</body>\n")
return render_template("index_graph.html")
why>:
do file.close() after all of the changes
oh
okay, now it works but it shows only one for cycle
site
@opaque rivet why?
what is the output of difference.items()
its dict
dict_items([('Stano', 0), ('Aligator', 0), ('Kmasko', 0), ('Teetou', 0), ('Tajmoti', 0)])
this
I don't see the problem here, it's doing exactly what you want it to do.
for name,key in difference.items():
file.write(f"<tr><td>{name}</td><td> {key} </td>")
gives you
Stano
0
Aligator
0
Kmasko
0
Teetou
0
Tajmoti
0```(removed the html here)
yea
and the reason you only see one cycle out of the 3 times you tried, is because you're wrapping it in <body> tags. Each HTML document can only have one pair of <body> tags.
don't you think it would be easier using jinja2 templates right now?
how what? using jinja2 templates? It would be much more readable & you should definitely use them, they give you more flexibility.
you don't want to have to be opening html files and writing stuff to the end of the file
that's not going to work in the long run
why>?
what if you want to edit something at the top of your file? are you going to append huge chunks of HTML in your python views?
with jinja2 templates you can have for loops, conditionals, and you can extend other templates... Overall it means you write much less HTML, and it allows you to easily communicate with your view
thanks
guys can someone help me set up my django sever
How to preserve value of radio button on the page, after the form is submitted using flask?
<form onSubmit={e => e.preventDefault()}>...</form>
add some JS in there to stop page refresh. I'm sure there's a flask-specific way of doing it though, check SO
Anyone know why my query to a GraphQL api using Graphene isn't working ? https://stackoverflow.com/questions/66847760/translating-nested-query-from-graphql-to-graphene-not-working
why does my modal not show its contents?
dbc.Modal(
[
dbc.ModalHeader("Header"),
dbc.ModalBody("This is a modal "),
dbc.ModalFooter(
dbc.Button(
"Close", id="close-centered", className="ml-auto"
)
),
],
id="modal",
is_open=True,
centered=True)
need some css help
want to put these panels inside of a container so they go side by side
instead of all stacked on top of each other
something like this
ahh thanks, let me try out both of those
Hey I am looking into deployment my first Flask app, if I choose to use PostgresQL do I need to host it on a different server from where I host the Flask app?
thank you this worked! i completely forgot about css grid existance
You can use heroku
they give u a free postgresql database
and free 500 hrs worth of hosting time every month
you can run them on the same server just fine
often most thinks like this will run them together unless your a large company scaling across multiple servers
it was pretty beginner friendly for me.
https://www.youtube.com/watch?v=Li0Abz-KT78 this video might help
In this video I'll show you how to push your Flask App to Heroku for Webhosting for free!
Webhosting apps can be tricky, but it doesn't have to be. In this video we'll install the gunicorn web server, create a requirements.txt file and a Procfile, set up git version control, install the free Heroku toolbelt, and then push our app to Heroku for...
this kind of goes here but also is database
collectionfound = await collection.find_one(ping_cmm)
RuntimeError: Task <Task pending name='Task-40' coro=<ASGIHTTPConnection.handle_request() running at /opt/virtualenvs/python3/lib/python3.8/site-packages/quart/asgi.py:72> cb=[_wait.<locals>._on_completion() at /usr/lib/python3.8/asyncio/tasks.py:518] created at /opt/virtualenvs/python3/lib/python3.8/site-packages/quart/asgi.py:28> got Future <Future pending cb=[_chain_future.<locals>._call_check_cancel() at /usr/lib/python3.8/asyncio/futures.py:360]> attached to a different loop```
I am getting that error with this code
```@app.route('/dashboard', methods=['GET'])
async def dashboard():
id = request.args.get('id')
collection = app.db["main"]
guild_id = id
ping_cmm = {"_id":guild_id}
collectionfound = await collection.find_one(ping_cmm)
name = collectionfound["name"]
return await render_template('dashboard2.html', gname=name, gid=id)```
and here is where I set up app.db
```app = Quart(__name__)
mongo_url = os.environ.get("MONGO_URL")
cluster = motor.motor_asyncio.AsyncIOMotorClient(mongo_url)
app.db = cluster["discorddatabase"]```
are you running your bot and webserver together by any chance 
no
seperate
idk I just imported quart
okay, in that case you're using the debug server
i gotta check Quart RQ, if it's doing what i remember it does then i have an idea
Are you just running the file like you would normally
e.g.
python app.py?
yes
import motor
from motor import motor_asyncio
import os
import dns
from routes.discord_oauth import DiscordOauth
app = Quart(__name__)
mongo_url = os.environ.get("MONGO_URL")
cluster = motor.motor_asyncio.AsyncIOMotorClient(mongo_url)
app.db = cluster["discorddatabase"]
@app.route('/')
async def home():
return redirect(url_for("login"))
# Route for index page
# Provides user login capabilities
@app.route('/login', methods=['GET'])
async def login():
return redirect(DiscordOauth.login_url)
# Route for dashboard
@app.route('/selectserver', methods=['GET'])
async def selectserver():
code = request.args.get('code')
access_token = DiscordOauth.get_access_token(code)
user_object = DiscordOauth.get_user(access_token)
user_guild_object = DiscordOauth.get_user_current_guild(access_token)
id, avatar, username, usertag = user_object.get('id'), user_object.get('avatar'), user_object.get('username'), \
user_object.get('discriminator')
return await render_template('dashboard.html', render_user_avatar=f'https://cdn.discordapp.com/avatars/{id}/{avatar}.png',
render_username=f'{username}#{usertag}', render_guild=user_guild_object, code=code)
@app.route('/dashboard', methods=['GET'])
async def dashboard():
id = request.args.get('id')
collection = app.db["main"]
guild_id = id
ping_cmm = {"_id":guild_id}
collectionfound = await collection.find_one(ping_cmm)
name = collectionfound["name"]
return await render_template('dashboard2.html', gname=name, gid=id)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080, debug=True)
theres just the whole file
what you can do that might work
is import asyncio
get a event loop at the top of your file just after the imports
e.g.
loop = asyncio.get_event_loop()
then pass app.run() loop=loop
so that it forces quart to use the given event loop rather than what it does by default which is create a new one
ok
that should? fix it, otherwise you might need to give motor a explict loop kwarg
ok now I am not getting that error
but now it is showing that nonetype object is not subscriptable but its not none
send the stack trace
can you send the full error aswell
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/quart/app.py", line 1862, in handle_request
return await self.full_dispatch_request(request_context)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/quart/app.py", line 1887, in full_dispatch_request
result = await self.handle_user_exception(error)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/quart/app.py", line 1104, in handle_user_exception
raise error
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/quart/app.py", line 1885, in full_dispatch_request
result = await self.dispatch_request(request_context)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/quart/app.py", line 1933, in dispatch_request
return await handler(**request_.view_args)
File "app.py", line 48, in dashboard
name = collectionfound["name"]
TypeError: 'NoneType' object is not subscriptable```
actually wait
your guild_id in that code is gonna be a string rather than a int
so your find_one is going to return none because mongo does str != int
ok one sec
not massively experienced but whats up
it still is none
async def dashboard():
id = request.args.get('id')
collection = app.db["main"]
guild_id = int(id)
ping_cmm = {"_id":guild_id}
collectionfound = await collection.find_one(ping_cmm)
name = collectionfound["name"]
return await render_template('dashboard2.html', gname=name, gid=id)```
what's the url you're requesting?
I need help, i made a method inside a component, that makses a http rquest via fetch, and edits the data . But i want to return what i edited inside the fetch method
grabsEachSubmission(index){
let miniState
fetch("/reddit/api/stocks-hot-wallstreetbets")
.then((response)=> {
if (!response.ok) {
alert("Something went wrong with http requests, try refresh the page")
}
else{
return response.json()
}
})
.then((data)=>{
miniState = {
index: index,
text: data[index].title,
author: data[index].author,
upvotes: data[index].upvotes,
comments: data[index].comments,
upVotesRatio: data[index].up_votes_ratio,
url: data[index].url,
dateCreated: data[index].date_created,
timeCreated: data[index].time_created,
length: data.length,
jsonData: data
}
})
}
``` this is the function
i want to return miniState, but when i call the function it says undefined(that was when i returned it) how do i return miniState then?
It's not quite that simple because it's a promise
handleSubmission(){
const props = this.state
const obj = this.state.jsonData
const array = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
// const keys = Object.keys(obj)
if (this.state.text === "Loading Making Api call") {
alert("Loading")
}
else{
console.log(this.state)
}
return(
<React.Fragment>
{array.map( (x,index)=>
console.log(this.grabsEachSubmission(index))
)}
</React.Fragment>
)
}
``` this is the function that conosle logs the other function
so your grabEachSubmission is gonna return before the request comes back
it might be worth looking at this article https://jasonwatmore.com/post/2020/01/27/react-fetch-http-get-request-examples which gives a bunch of examples
ty
but Tl;DR you basically need to update the react state after the promise has resolved
whats the problem here ?
how would I make it so there is an update button and whatever is in this box gets updated in my database
I need to build a status field in my model(DJANGO), however I can't decide whether to use a Charfield(Uneditable), foreignkey. It just needs to display one of three options depending upon a query query from the database. Any recommendations?
How to display graph on my website?
Check the Django Docs, I think they have something on it
you might have to import column and Integer
@native tide render matplotlib graphs or use d3.js
Use async? ๐ค
I am trying to work with bs4 and I want to retrieve the number after </span> how can I do that?
Can you send me a piece of that html?
Would try to help you
easiest method is just make the soup and then soup.text which will remove the tag and then let you strip off that $ if it doesnt already
It doesn't strip that, so yeah, should be the easiest way
it normally depends on the tags, but yeah i wouldnt expect it to strip an inline tag like that
would go against the behavior of html
Guess you can also remove that span from dom
html = "<div class='price-large'><span class='symbol'>$</span>57,917.91</div>"
soup = BeautifulSoup(html, features="html.parser")
soup.select_one(".symbol").decompose()
print(soup.find("div").text) #>>> 57,917.91
@quick cargo Can you help me a bit if you're not busy?
whats up?
How should i go about implementing authentication in my frontend and backend?
User login, but basically it would be an api auth too ๐
Because you need to access application api from frontend
Hmm, well i think the best sort of setup for that would probably be Oauth2
as it makes sure you follow a fairly secure setup and minimizes the risk of something going wrong
its basically the concept of
user sends a request with a given auth method, this can be username and password in cases
server validates this data
and returns a Token
and any interactions the user does go through the token
that token automatically expires after a given time unless it's renewed
I don't really want to use oauth because it looks complex though.
what framework / lib are you using for your backend?
I work with laravel and use django occasionally
Django has a really good Oauth lib pre made
that does all of the hard work for you
I imagine laravel will as well because it's the Django of PHP lol
thank you ๐
thank you! ๐
https://new-django-oauth2.readthedocs.io/en/latest/getting_started.html is the Django oauth2 stuff
nice lib overall and makes it very easy
if you want something a little simpler you can go with the sort of default user name and password type deal but generally i recommend against it because it can be less secure
Im not sure tbh
Generally the python framework eco system seems to not like doing that for what ever reason idk
I know you can decorate your view with middlewares tho
request is an HttpRequest object. view_func is the Python function that Django is about to use
So i'm just curious if there's such feature
that hook appears to be invoked just before a given view is invoked and gives you all the context for that
other than that idk
Btw did you try vue or any other js framework?
I don't like jsx because there's no directives and stuff that vue has
Otherwise i think i would use react though
Angular is also nice but i didn't like rxjs ๐
hey, i'm using flask and I'm having trouble returning json data to an ajax call without changing the page. when I return the json it just displays as text on the page. code screenshots to follow...
any help would be greatly appreciated, ive tried using different methods of returning the json but i cant get it working
i believe you can just return the dict as normal instead of jsonify now
that still has the exact same result ๐ฆ
can you send a SS of the headers it's returning
yep
this is all its returning
so its like the json isnt being returned correctly its just being dumped as text
hmm
and ajax cant handle this using JSON.parse() ?
oh well looking at your ajax code it seems you're just reading the JSON as a string anyway
so it makes sense that it's displaying it like that
you need to do let foo = JSON.parse(text) to convert it to a JSON object
thanks, one sec ill try that
I am running this function on loop but every time it gives the same value is their any way I can refresh the request or something like that to update the value?
sorry what do I need to pass in as the argument to parse @quick cargo ? using the response argument from the anonymous function doesn't change anything and im not sure what else I can use
you need to parse the response text
note that if you're just displaying this to some html element it's gonna look like text not json
hello guys, Im a python beginner and im interested in learning Django for making Webapps but I also heard about Flask. Does someone know if Django and flask are made for different purposes ?
they both achieve the same goal just in diffrent ways
Django is what you would call a Full Framework meaning it has all the batteries included like Middleware, auth, database ORM etc...
use json.loads({})
Flask is what's called a micro framework, so it doesnt ahve so much of the bells and whistles
Flask is considered more flexible in terms of working style while Django is very opinionated
one should touch flask once when he is beginner and 2nd when he is fimiliar with full design , componets require to leverage flask full power
I mean start at which ever you want
json.loads is giving me an error for trying to use a dict, is it meant to only take a string?
literally doesnt matter which one you pick, both will teach you things
flask/fastapi is good to start
ignore the comment, i think he miss interpreted your question
In response to this:
He's trying to load the json string from JS not Python, jsonify is flask's json response handler
what's your code and what 'isnt working'
do you mean that it's still looking like a string?
yeah so my intention is to take the response and use it with javascript to modify text on the page, but instead flask is just sending me to a blank page with the json printed out as plaintext
what does console.log(text) do
same result
you should note that anything which isnt a direct JSON response from the server wont have the browser lint it
your browser will only pretty print json like that if it's the direct response
what you have going on is dynamic where the main webpage is HTML so the browser is going to display it like HTML
if you're just trying to display the returned json then it is going to look like text because the browser isnt going to pretty print it like you would expect from a direct JSON response
can you send a SS of your terminal with what it prints
yeah sure, and i dont want to display the returned json at all i just want to store it as a variable
have you tried postman for api testing ?
never heard of it, what's is it?
api tester
basically Curl but with electron
ill have a look at it
the console doesnt seem to even be printing the response so im not sure what thats about
these are the only server logs
i love postman
makes working with api so much easier and later implementing in code
I am new to #Django-rest-Framework. I am trying to create a public POST api and on display it should also have the HTML form like it does with the class based views.
Here is my view.
@api_view(['POST'])
@permission_classes([permissions.AllowAny, ])
@authentication_classes([])
@renderer_classes([JSONRenderer, BrowsableAPIRenderer])
def lead_create(request):
serializer = LeadSerializer(data=request.data)
if serializer.is_valid():
try:
serializer.save()
except Exception as e:
return Response(
str(e),
status=status.HTTP_400_BAD_REQUEST
)
return Response(
{'message': 'Lead Successfully Saved'},
status=status.HTTP_201_CREATED
)
My problem is the output is something like below:
https://i.stack.imgur.com/OKlUs.png
Why am I not getting the HTMLForm even when i have added the 'BrowsableAPIRenderer' renderer class
yup it's great ๐
YOU have define post method and using get method
@native tide how to use post in the browser, In the browser this is how you view the apis
use js to send a post request
DRF has its own ui for viewing apis, although the request is working fine. It is the ui where i need something different
sorry don't know much about DRF, but in above problem you are using get request but have defined post
After writing my first website with Django, I am looking into learning Node for a potential job. Only basic JS knowledge so far, but not new to programming. My idea was to create a tinder clone as my first project, but I am unsure about the technology to use.
MERN/MEAN/MEVN stack sound like what I should be heading for, with MERN>MEAN as Angular to me seems like it has a high learning curve. Not sure about Vue.
I am also unsure about the advantages of Mongo - being somewhat experienced in Postgre, PERN also seems like an alternative.
Also thinking about using Firebase, but I am unsure about GDPR regulations (and Tinder-Data is intimate data, so I guess GDPR applies more heavily?). For my Django Project I used Heroku and AWS S3 for deployment.
Thanks for your time
can someone reply to this please?
So probably the price just didn't update?
yeah it just keeps showing the same price but if i rerun the program it updates
Well, that's strange, could you show the whole program?
sure
from discord.ext import commands, tasks
from discord.utils import get
import cryptocompare
import sys
import os
from bs4 import BeautifulSoup
import requests
import re
print(cryptocompare.get_price('BTC', 'USD'))
TOKEN = ''
PREFIX = '!BTC'
SERVER_MSG = '[BTC] '
# web scrape
async def retrieve_btc():
URL = 'https://www.coindesk.com/price/bitcoin'
with requests.get(URL) as page:
soup = BeautifulSoup(page.content, 'html.parser')
results = soup.find(id='__next')
job_elems = results.find_all('div', class_='price-large') #btc price
job_elems = str(job_elems[0])
job_elems = job_elems.replace('<', '>')
job_elems = job_elems.split('>')
#print(job_elems)
BTC_VALUE = str(job_elems[4] + job_elems[6])
print(BTC_VALUE)
page.close()
page.cookies.clear()
return BTC_VALUE
#with open('token.txt', 'r') as f:
# TOKEN = f.read()
client = commands.Bot(command_prefix = PREFIX)
@tasks.loop(seconds = 60)
async def update_crypto():
btc_price = await retrieve_btc()
act = discord.Activity(name = f'{btc_price}', type = discord.ActivityType.watching)
await client.change_presence(status = discord.Status.online, activity = act) #24hr return
#print(server_msg + "Bot Activity Updated")
# changing the bot nickname
guilds = client.guilds
for guild in guilds:
members = guild.members
for member in members:
if member.name == client.user.name:
await member.edit(nick = btc_price) #change the BTC price to the price
@client.event
async def on_ready():
print(SERVER_MSG + 'The Bot is Online!')
update_crypto.start()
print(SERVER_MSG + 'Starting....')
client.run(TOKEN, reconnect = True)
print(SERVER_MSG + 'Bot Ended')```
@serene prawn
Can you actually check if that function is being called?
maybe that website is doing some caching though
Can't you use some public api for that?...
most of them are paid
Try to user cache-control header maybe?
I cant figure out how to get rid of something out of a disctionary I get from a discordoauth object
someone helped me get this code
sharedguilds.pop(next(i for i, guild in enumerate(sharedguilds) if guild['id'] == strid))
but it doesnt remove anything from the dictionary
here is an example of one of the servers in the dictionary
{'id': '805225643734204416', 'name': ':sun_with_face:SunnySide:sun_with_face:', 'icon': '72288469be9cabeaff946a07fbeea98f', 'owner': True, 'permissions': 2147483647, 'features': ['WELCOME_SCREEN_ENABLED', 'PREVIEW_ENABLED', 'NEWS', 'MEMBER_VERIFICATION_GATE_ENABLED', 'COMMUNITY', 'INVITE_SPLASH', 'ANIMATED_ICON'], 'permissions_new': '8589934591'}
here is my full code
@app.route('/selectserver', methods=['GET'])
async def selectserver():
code = request.args.get('code')
access_token = DiscordOauth.get_access_token(code)
user_object = DiscordOauth.get_user(access_token)
user_guild_object = DiscordOauth.get_user_current_guild(access_token)
print(user_guild_object)
botguilds = []
userguilds = []
sharedguilds = user_guild_object
collection = app.db["main"]
for document in await collection.find().to_list(None):
guildid = document["_id"]
guildid = int(guildid)
botguilds.append(guildid)
for guild in user_guild_object:
guildid = guild['id']
guildid = int(guildid)
strid = str(guildid)
if guildid in botguilds:
pass
else:
sharedguilds.pop(next(i for i, guild in enumerate(sharedguilds) if guild['id'] == strid))
print(botguilds)
print(userguilds)
print(sharedguilds)
id, avatar, username, usertag = user_object.get('id'), user_object.get('avatar'), user_object.get('username'), \
user_object.get('discriminator')
return await render_template('dashboard.html', render_user_avatar=f'https://cdn.discordapp.com/avatars/{id}/{avatar}.png',
render_username=f'{username}#{usertag}', render_guild=sharedguilds, code=code)```
I am trying to get it so it only shows the shared servers on my dashboard
but right now it still shows all of them
got a free api, thanks a lot for your help ๐
hi! i want to make a button that adds a new <entry> on the page. how would i do this in flask? do i need to use JS or can i use jinja?
my backend is written in flask
If you want to persist that data then you would have to save it on your backend
If you just want to add the element then just do that with js
If you're pretty new to js then learn how to insert new elements into dom
You can either use native js or jquery but for anything more complex I would use js framework ๐
You can
There's also vue and angular
They are more like frameworks when react is a library
But react and angular have better typescript support
isnt typescript only useful backend
also
arent those JS libraries way better if you use JS backend
oh
It doesn't really matter
Plus typescript can be useful anywhere
Use bootstrap if you like it
There should be a react library with bootstrap components or you can just do that with classes
so all i need to do is add react to my <head> and i can use it
Try create-react-app
shey guys sorry again, back with another question
function callback (x, index){
var text
function handleTextProp(index){
const xhr = new XMLHttpRequest();
xhr.open("GET", "/reddit/api/stocks-hot-wallstreetbets?format=json")
xhr.onload = () => {
const data = JSON.parse(xhr.response)
text = data[index].title
}
xhr.send()
}
console.log(text,index)
return(
<React.Fragment>
{handleTextProp(index)}
<Submission text="placeholder" key={index}/>
</React.Fragment>
)
}
``` how do i make "text" variable public. When i make my get request and assign it to test, its only avaliable within that scope, once i move out of the onload event listener it isnt
how would i make text, a global variable like global in python
Making request to yahoo website, after some point I get this error: {code: "internal-error", description: "offset and size is over threshold"} code: "internal-error" description: "offset and size is over threshold" result: null
IEX cloud is a great API for that sort of thing, the rate limiting is quite loose so you can get away with making a request every minute on the free plan.
if you're using React, the frontend is independent of your backend. You'll just use Flask as an API and have your React app as a SPA (single page application - this means that your server just renders 1 page and all of the future rendering of components is done by the client) - unless you use server side rendering but that's a bit more complex.
by doing create-react-app you will make a new folder where you can create your frontend.
oh ok
how do i access my state inside onload event listener of xhr?
at XMLHttpRequest.xhr.onload (DemoBox.js:157)```
also, you still have to write HTML with React, so bootstrap is can still be used - but you can also use UI libraries (ant design / chakra UI) to speed up your frontend development.
if you don't know JS you should learn it before learning react.
state of what?
are you trying to doXMLHttpRequest.xhr.onload.state?
want to accss my component state
handleSubmission(){
const props = this.state
const obj = this.state.jsonData
const array = [1,2,3]
// const keys = Object.keys(obj)
if (this.state.text === "Loading Making Api call") {
alert("Loading")
}
else{
console.log(this.state)
}
function callback (x, index){
var text
function handleTextProp(index){
const xhr = new XMLHttpRequest();
xhr.open("GET", "/reddit/api/stocks-hot-wallstreetbets?format=json")
xhr.onload = () => {
const data = JSON.parse(xhr.response)
text = data[index].title
console.log(this.state) // gives error
}
xhr.send()
}
console.log(this.state, index,"test") // can access state
return(
<React.Fragment>
{handleTextProp(index)}
<Submission text="hello" key={index}/>
</React.Fragment>
)
}
return(
<React.Fragment>
{array.map(callback, this)}
</React.Fragment>
)
part that matters
function callback (x, index){
var text
function handleTextProp(index){
const xhr = new XMLHttpRequest();
xhr.open("GET", "/reddit/api/stocks-hot-wallstreetbets?format=json")
xhr.onload = () => {
const data = JSON.parse(xhr.response)
text = data[index].title
console.log(this.state) // gives error
}
xhr.send()
}
console.log(this.state, index,"test") // can access state
return(
<React.Fragment>
{handleTextProp(index)}
<Submission text="hello" key={index}/>
</React.Fragment>
)
}
return(
<React.Fragment>
{array.map(callback, this)}
</React.Fragment>
)
In django, I'm trying to get one model in one app to be a foreign key for another model in another app, both of course in the same project. i can do this with User, but any app i make, i cant' sibling import? I've tried making the project a package but this is honestly like why in the world would django talk about reusable apps if you can't reuse them in such a manner>
Only just seen you message. That is helpful to know Thanks ๐
new to flask, trying to build a basic web app that does media conversion and uploads to cloud. getting 404's as well as home() needs more than one argument but 0 passed can you help debug this plz? atm just trying to upload files to s3 storage nothing too fancy
Hey @daring cairn!
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:
def __init__(self, hash_name):
self.hash_name = hash_name
@app.route('/')
def index(self):
return render_template('index.html')
def hash_username_fname_sname(fname, sname, username):
to_hash = "{}{}{}".format(fname.lower(), sname.lower(), username.lower())
hashed_name = hashlib.md5(to_hash).hexdigest()
return hashed_name
@app.route('/signup', methods=['post'])
def signup(self):
fname = request.form['fname']
sname = request.form['sname']
username = request.form['username']
self.hash_name = self.hash_username_fname_sname(fname, sname, username)
if request.method == 'POST':
password = request.form['password']
table.put_item(
Item={
'first_name': fname,
'surname': sname,
'username': username,
'password': password,
'hash_key': self.hash_name
}
)
msg = "Registration Complete. Please Login to your account !"
return render_template('signin.html', msg=msg)
return render_template('index.html')
@app.route('/login')
def login(self):
return render_template('login.html')```
def check(self):
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
table = dynamodb.Table('rdy-user-credentials-table')
response = table.query(
KeyConditionExpression=Key('username').eq(username)
)
items = response['Items']
name = items[0]['username']
print(items[0]['password'])
if password == items[0]['password']:
return render_template("upload.html")
return render_template("signin.html")
@app.route('/')
def home(self):
return render_template("upload.html")
@app.route('/upload', methods=['post'])
def upload(self):
if request.method == 'POST':
img = request.files['file']
if img:
filename = secure_filename(img.filename)
img.save(filename)
s3.upload_file(
Bucket=BUCKET_NAME,
Filename=filename,
Key=self.hash_name
)
msg = "Upload Done ! "
return render_template("file_upload_to_s3.html", msg=msg)
if __name__ == "__main__":
app.run(debug=True)```
i introduced the class method and the error just happened
TypeError: index() takes exactly 1 argument (0 given)
did you bind your callback function in your component's constructor?
just curious if i should know how to make make things by hand in css and html or is it ok just to use bootstrap or something else. tks
Hi all, does anyone have experience with uploading Django on Godaddy VPS?
Hello, I wanted to know how I could clone a site like https://speedsheet.io/s/python I know little bit of Python, Django and HTML/CSS.
@velvet crystal I think HTML is for front-end and Python for back-end, so you would need both.
in the manage.py powershell i am creating new objects using the .objects.create command and it shows ive created them when i run .objects.all() however when i go onto the actual website i cant see that they have been created
does anyone know why this is?
hey guys
I am running into CORS issues
i feel like i've tried somewhat everything
headings, flask-cors, tried running it on windows and linux
now that everything is on my linux computer i get 0 response back and it's not giving me a cors error but i feel sus about that. My last option is a proxy i suppose
if anyone has any good understanding to help me out, PLEASE DM ME. I'll show you my code
i am new to this, and could use all the help i can get
I'm using Flask and react. using the fetch api to call
here is my stockoveflow post
does anybody know how to make a voting bot for online polls like polldaddy
@twilit thorn After you created the db objects did you run object.save()?
Hi, does anyone know where I can host a Flask app online for free? I heard of Heroku and Netlify, do they work? Do they require any credit card details
I am writing a calculator flask app to calculate current draw for certain devices. Each has a set value but could change as updates to the devices occur (more or less current). I wrote a desktop version of this app and used a json file for all the values based on their settings (each device has about 5 different settings that determines the current draw).
I would like this easily editable by either a normal person or a simple IT person.
My question is, should I stick with json as my โdatabaseโ or move over to something like SQLite?
Pythonanywhere, AWS for a while, maybe check noip
Is Pythonanywhere free? Do I need a domain?
It is free for one site. They make the domain for you. Say you used you screenname, it would be www.donald@pythonanywhere.com or something like that
It is great for testing
If I have a raspberry pi at home, would it be better if I hosted it there? Would there be any security risks? Such as ddos, my home network being hacked, etc?
Not production
If you used a pi, check out noip. It helps set up a domain and add a layer of security
And if you are afraid of being hacked, plug it in at the library ๐
Thanks! Do alternatives such as heroku or netlify work? I have seen people use those for hosting side projects
No idea.
I bug my sys admin at work with these questions
I am apparently on the IT deptโs watchlist
Because โlinux bad!โ And I know what a raspberry pi is and the furthest extent to the knowledge my IT manager has is by watching Mr. Robot
I am not too smart in networking. I know the basics. I am more a desktop guy myself.
My IT dept keeps making us watch videos from Kevin Mitnick's company and he shows how he can hack a mac to get the keychain password through an email. He never shows HOW he does it though (code or anything). I am not looking to hack people but i find the concept fascinating and want to see the methods used.......... yea, maybe i should be on the watch list
anytime someone at work leaves their computer open when they walk away, I open notepad and type "Thanks for the info"
I even got my IT manager one time. That was awesome
for him, i wrote "now I have the keys to the kingdom!"
@daring cairn have you tried adding <string:self> to the URL decorator so that it is like @app.route ('/<string:self>'). But why are you passing self? You don't seem to be using it in that function.
I want to have Javascript web clients connect to a Python server and send files and data from client to server and same for the reverse. How may I go about this?
does anyone know why i have been gettign this error i went inactive and left my site for 2 months then the header was messed up and theres this error
im not really good with web development i started in january
may I see your code?
get rid of the intergrety and try again
oh
thanks
it worked but idk why it suddenly stopped
before i left the site it was fine
the website stopped?
not like stopped but the navbar went really ugly
and had none of the bootstrap
also I suggest force reloading with empty cache
is it possible to make the navbar one file with html
instead of putting it on the top of every pages code
it would make it easier to edit but im not sure if i can do it with html
you wouldn't want to do that what I would do is make an index with all of your basic stuff like navbar and text stuff and then use that as the base of your website
does that make sense?
not really to me
liek do u mean for the mains ite
because it has multiple pages
this is the main page
here what exactly are you working on? is this for school or for someone else or just personal
just for fun
its jsut a site im showing my friends and making it for fun
Dope I have been doing Web dev since I was 12 do you want me to become your tutor I could teach you all of this stuff
this is what i mean by maybe having the navbar as one file so if it breaks i dont have to edit the pages
if you want
ive been messing with sites and jsut code stuff since 2018
but i started actual knowing how to do it in 2020
in 2018 and 2019 i didnt understand it so im not really good
I could teach you how to write this and so you could start doing web dev for other people in like 3-6 months
if you want you can
i dont really know php good
im better with html stuff
ok do you want to dm me?
alr
ill dm
A site is made up of one or more pages
Think of it like book title (site) vs chapter title (page)
Not exactly. But you can do something even better than that if you use Jinja2 templates for your HTML.
what does child and sibling meaning in css when refering to selectors?
The child combinator (>) is placed between two CSS selectors. It matches only those elements matched by the second selector that are the direct children of elements matched by the first.
The general sibling combinator (~) separates two selectors and matches all iterations of the second element, that are following the first element (though not necessarily immediately), and are children of the same parent element.
<section>
<div>
<time></time>
</div>
<img>
<a></a>
</section>
section time (descendant) selects time
section > time (direct descendant) selects nothing
div > time selects time
div + a (immediate sibling) selects nothing
div ~ a (sibling) selects a
img + a selects a
Django
class Category(models.Model):
bid= models.ManytoManyField(Listing)
category= models.CharField()
---------------------------------------------------
What should my query be for getting all the objects related to a manytomany field that is bid in the above example
before the edit it didn't make sense lol
you mean like...Category.bid.all()?
...if i do that will i get all the objects of Listing table?
i want listing but from category
like if i want to get all the listing that are in a category
but your model called Listing
@native tide i was able to do it
i jsut made the html file a php one and left my original code and put at the top a php include
then included the nav bar
lemme try that just a sec
@native tide congratulations. Though I have no idea about PHP only Jinja2
@vestal hound i love you !! it worked !!
yeah im not really good with php either
yw ๐
yeah wassup
can somebody reply to this please?
hi, i have python and django interview tomorrow. which topics should i consider as most important? and which are common question?
What request are you sending?
lead-create/ is the endpoint that executes this fbv @serene prawn
Try the example here: https://github.com/imagineai/create-django-app
how can i send a post request on browser
do you know django-rest-framework?
A bit, yes
do you know about renderer_classes?