#web-development
2 messages · Page 206 of 1
not rlly, firebase has an API
and an admin-sdk so you can easily use the database from python without much hassle
So u a raising database through it
Well, let's assume it is similar to usage of managed databases then
That's definitely not a good idea and I think specifically advised against. 😄
Although you can fake one to get back up to speed in your migrations after DB changes.
Yeah I zeroed them out then faked them back in to fix it .
I thought I’d have to scrap my tables at one point , not a massive issue as it was pre production but I’d already populated a lot of data during my tests I couldn’t be bothered to do again 🤣
I was transferring a paper reporting system to a web portal for work
There is framework agnostic solution btw
https://flywaydb.org/
Version control for your database. Robust schema evolution across all your environments. With ease, pleasure, and plain SQL.
Noice.
I think Prisma is the favorite for JS based stuff anyhow.
My JS starts and ends at frontend
There are other things wished being learned
Curious to know perhaps though
Considering widespread usage of js...
Who knows, perhaps I ll need to join developing js backend one day in a future
I just think it helps knowing how it works at a global level more than being proficient with it - backend-wise.
I am eyeing golang to try in a future when my learning queue would be free
It has some quirks though
After python, js, it is quite uncomfortable
I thought one of the good things about Go is it's ease of use like Python
Static compiled and ultra strict in best practices
It enforces its own vision to how code should be
Yes, it is easy to learn syntax. But its philosophies... Urgh. Quite far from python/js freedom
Go is rising now bro
Go has been popular because of goroutines
That doesn't have anything to do with its philosphy
Go has been known to make many unpopular decisions
I can just about get some js elements to work atm . It’s my next learning pipeline , because My users experience is limited because of it
I want to add a feature to a web app that will allow them to click and drag on an image and when they do, a box is added around the click and drag area
how would I implement this in javascript
ok, lets say that i am using windows 10 and is an internal server, lets forguet the https server only http
You'd probably have to do it all manually using a canvas.
(drawing box)
which means you'd have to add a setInterval(render, 1) for drawing frames.
or something.
I'm sure there's a library that does it too
help with flask and iframe
i have to show a pdf file in a iframe (if there is an other option please let me know)
<iframe src = "static/Report.pdf" class = "embeded-responsive-item" allowfullscreen></iframe>
it display the pdf windows but very very small, how can i set the width to make the view bigger?
width="750" height="500" do not works
thanks for the advice
how big is the parent div?
if that question is for me then the parent div is using whide screen and autoadjust when resize
Tried changing the size using the inspector?
oh, I see. You need to specify a unit. i.e. 750px
750px, also do not work with that
¯_(ツ)_/¯
ok, with the inspector: the iframe have only the src, do not shows the class also the allowfullscreen
<iframe src="Report.pdf">document</iframe>
What source did you put?
haaaa!! css could fix the problem
i think i had foud the problem, ill fix it
thanks any way
aria-role="presentation"
``` I believe
I was considering aria-hidden=true
that might be more intended for things that are toggleable
Will it be hidden from screen reader navigation ?
it says this :
The presentation role is used to remove semantic meaning from an element and any of its related child elements.
I would have thought so anyway
accessibility is hard 😦
question:
in flask, i have a form with 3 buttons, how do i tell to the webpage to "activate" the button Ok in case i hit enter instead click Ok?
sounds like you need JS listener onKeyDown
You use the form tabindex
Ah that's wrong
You want a <button type="submit"
how that would help though?
Oh I assumed activate meant the same as click
My assumption could we wrong as well, communication is hard 🙂
form ButtonSave tab index = 1 ok
correct this code plz
folder
|-templates
|-static
|-img
|-bg.jpg
main.py
<header class="masthead" style="background-image: url('{{ url_for('static', filename='img/home-bg.jpg') }} ')">
Hello, I am using flask and I am running some code but it showing my old flask code when I deleted that code. But it shows the same web page
use ctrl + c in terminal then re run the code
Hi everyone, This is a Django question. it seems like a small problem but not getting how to resolve it
so this is my main url file for including app
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'', include('home.urls')), # home page index
This is my home url file
from django.urls import re_path as url
from . import views
urlpatterns = [
url(r'^index/', views.index, name='index'),
This only works if i put
index/ in the pattern otherwise it dont
and the working url is
http://localhost:8000/index/
How can i make my url open same if i do
http://localhost:8000/
from django.urls import re_path as url
from . import views
urlpatterns = [
url(r'^index/', views.index, name='index'),
url(r'', views.index, name='index'),
how about this
or to make regex that matches empty and index at the same time
For some reasons it works for home page but my other urls stops working
it would always redirect me to the home page
regardless of any valid url i put
it didn't give me any warning either
I am doing it as
core/urls.py
urlpatterns = [
path("admin/", admin.site.urls),
path("worker", include("worker.urls")),
path("", include("home.urls")),
]
workers/urls.py
from . import views
from django.urls import path
urlpatterns = [
# ex: /polls/5/
path("/ping", views.get_ping, name="ping"),
path("/install", views.install_vpn_server, name="install"),
path("/status", views.get_status, name="get_status"),
path("/configs", views.get_configs, name="get_configs"),
path("/stdout", views.get_stdout, name="get_stdout"),
]
home/urls.py
from . import views
from django.urls import path
urlpatterns = [
# ex: /polls/5/
path("", views.get_home, name="get_home"),
]
works fine
which app opens when you do http://localhost:8000/ only
uh, I don't need index page, it is rest API
but it would be easy to change in my case
that's the case, you aren't using regular expressions either
yeah
all my parameters go in Query Parameters and POST Data fields
I don't really need any complex url patterns
i hate the fact that i can't comprehend what could be the wrong here
empty string should have been enough
and if i don't put index/
it starts giving me /%2F
extra slash on its own
Lol, this worked
url(r'^/^', views.index, name='index'),
url(r'', views.index, name='index'),
url(r'^index/', views.index, name='index'),
and i have no idea why would i have do it like this
@inland oak
i actually amended i dont need index in the url at all
url(r'^/^', views.index, name='index'),
url(r'', views.index, name='index'),
Thanks for the chat mate
it looks like my mind works better if i have someone with me to talk about ti xD
strange that you need both of them
how about try deleting one of them
In software engineering, rubber duck debugging is a method of debugging code by articulating a problem in spoken or written natural language. The name is a reference to a story in the book The Pragmatic Programmer in which a programmer would carry around a rubber duck and debug their code by forcing themselves to explain it, line-by-line, to the...
yea i need both of them, tried deleting the one with ^/^ it doesn't work for other urls then
if i delete the '' then it doesn't work for the home page
Hahaha, but rubber wont reply me back
lets augment it with AI bot then
in order to have sophisticated enough duck
https://tvcdn.fancaps.net/733563.jpg
Hmm, that's a good idea and i think someon would have done it already
can some one give me a django verbos name and why is it used
@inland oak
url(r'^$', views.index, name='index'),
This worked even better
xD
was that worth searching and trying for 2 hours?
perfection is made out of details
Guys I need ur help
Don't ask to ask, just ask your question and someone will help if they can
the thing was (LOL ) we just bought shared hosting on hostinger
they told u cant deploy django app on shared hosting u need an vps so we bought a vps can u tell me how can i deploy my django application plz?
can u guide me asap
i have some more clients xD
Oh maybe get a refund then?
Sorry I don't do voice chat
Hi, you should get pythonanywhere server or Linode to host your python django app @dusk portal
can VC if you want
bro i wanna deploy at hostinger vps
i mean, a vps is a vps
If you look at the article, you'll see it doesn't matter. It's just about deploying on a linux server.
It's just the best, simplest tutorial I've found.
as a beginner which language should i learn for backend web development ? any personal suggestions ?
Python is a great start. Easy to understand and get the basics of programming in general.
Hey! I've made a line following robot with python on a raspberry pi and I'm wondering how could I allow someone to call the robot on a webpage so it starts that code? Would flask allow me to do that?
how do you run this? is the program ran on the pi or as a computer program?
The program is running on the pi as python file
if you could run the program like a server on the pi i think it would be possible
ok thanks
You're asking on a Python server, what do you expect us to say ;)
Yeah, Flask is a good option
can someone help with this error please => AttributeError: 'tuple' object has no attribute 'values'
You're trying to access the values attribute of a tuple.
!e
x = (1, 2, 3)
print(x.values)
@manic frost :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | AttributeError: 'tuple' object has no attribute 'values'
the code => class OccupierSerializer(serializers.ModelSerializer):
token = serializers.SerializerMethodField()
email = serializers.EmailField(
required=True,
validators = [UniqueValidator(queryset=Occupier.objects.all())]
)
username = serializers.CharField(
required=True,
max_length=30,
validators = [UniqueValidator(queryset=Occupier.objects.all())]
)
occupation = serializers.CharField(
required=True,
max_length = 30,
)
password = serializers.CharField(
required=True,
min_length=8,
write_only = True
)
class Meta:
model = Occupier
fields = (
'token',
'username',
'password',
'occupation',
'email'
)
def create(self,validated_data):
password = validated_date.pop('password', None)
instance = self.Meta.model(**validated_data)
if password is not None:
instance.set_password(password)
instance.save()
return instance
def get_token(self,obj):
jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
payload = jwt_payload_handler(obj)
return token
Try to use the formatting here to make that easier to read.
I also don't see where you're trying to access values.
Somebody Here good with api´s
Better to just ask the question.
i need a spotify api where someone can select a song and then the spotify code is sent to me
spotify has an api
how do i update my python version from 3.9 to 3.10?
This is not the correct place to ask your question. Anyways, simply just go to https://www.python.org/, hover over downloads and click python 3.10.1. Then run the installer and choose "update"
thanks
A Good question in django models what is the difference between (ForeignKey and OneToOneField) in the two following models ```py
class RelationShips(models.Model):
user = models.Foreignkey(User,on_delete=models.CASCADE)
friends = ManyToManyField()
Category = ManyToManyField()
ClassRelationShips(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
friends = //
Category = //
Like all such questions, it depends what you're trying to do. I would generally say that Django is complex and powerful, Flask is quicker and easier for simple projects
How to make a a button in flask that when pressed runs a function?
Anybody know how to prevent duplicate static files being created in Django?
trying to present a random image from a folder but my static references dont include the duplicate files with weird extra nu,bers
i feel like its something to do with this:
STATICFILES_STORAGE = 'storage.whitenoise.CompressedManifestStaticFilesStorage'
a duplicate is being created when i run collectstatic . Not a problem when im explicitly naming the path/file in normal use, but if i pick a random name from the list it isnt lining up as the duplicate doesnt exist in my original static folder
Just dont ever use WhiteNoise
it makes the website loading forever even for one person
Got it thanks .
Are these duplicate static files normal behaviour ?
I save my files in static , when I run collect static they get copied to staticfiles with duplicates
This is from settings.py
STATIC_URL = '/static/'
STATICFILES_STORAGE = 'storage.CompressedManifestStaticFilesStorage'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
This is my folder tree
im saving into static\practice_manager
trying to figure a way out on how to ref that list in my view without the extras
where
yeah
worked?
now what?
error static is undefined
folder name
ok
Hey @native tide!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
Hey guys, Nice to see all you awesome people. Im looking for a python framework to build an ecommerce site! Idealy, one that allows users to submit their own picture so that we can print it onto something. Any suggestions on said framework?
check where you've included css
can you view developer tools
and see what resources are failing to load?
open it with F12 and hit refresh
they should show up red
can i add more than one ml model in flask
Hey @native tide!
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:
how can I send my ids from model , and brand vehicle to vehicleviewset in order to create a fk insert via api? https://dpaste.org/HVzF
don't create _id, it is created automatically
just request .pk value from your object
I would recommend using DRF https://www.django-rest-framework.org/
Django, API, REST, Home
it gives you quite DRY serializers to transform django model objects into jsons and back, including deserializers for easy revert operation
hi
any idea of how to solve this problem of the websocket??
websocket._exceptions.WebSocketConnectionClosedException: Connection to remote host was lost.
I would start with making simple REST API POST end point at backend server
and trying to fetch data from it in order to find if i have no CORS problems
Then I would try to use Chrome Dev Tools and to check networking requests and any other debug information in order to find more detailed error
Also I would attach myself to backend console in debug mode and try to see any more detailed information
ok
Hello guys, please I need help, I have been on it for days. Please help me
!rule 8
8. Do not help with ongoing exams. When helping with homework, help people learn how to do the assignment without doing it for them.
Don't ask to spoonfeed you whole homework
Ask specific questions for particular small stuff, right after you tried to find the answer on your own
I have tried, I have the question here https://stackoverflow.com/questions/70361115/django-orm-for-loop-to-get-queryset
I am trying to use for loop to get list of author with the number of books writing and author with the title of book wrote.
Here is my models.py
class Author(models.Model):
name = models.CharFi...
and just read here https://pythondiscord.com/pages/resources/guides/asking-good-questions/
A guide for how to ask good questions in our community.
Okay.
for a in Author.all():
books = a.book_set.order_by('author')
print(books)
this is straightly the worst possibly way to do that
you just requested Authors from SQL database
and then you make repeated SQL request for each author
that makes intensive amount of requests to SQL and heavy slow down
you need to request necessary data in one request
author_list = Author.objects.order_by("book").count() you need to chain your request
with . until you make it accessing the right information you need
something like...
GetAllAuthors.JoinWithBooks(Where Book author matches author ID).AndGiveMeAllOfThem.WhileGroupingBooksToCountThemASNumberForTheEachAuthor
at the line above would be silly pseudocode example of what you need to write
Eh. I could write the answer in raw SQL, but ORM makes me confused how to write even simple stuff like that 🤔
ORM gives possibility to write raw SQL requests though
Thanks for this.
u a welcome. Basically you have two choices
Reading carefully how to make ORM queries to fit the situation: https://docs.djangoproject.com/en/4.0/topics/db/queries/
Tbh it is really hard to do without knowing raw SQL
I think it would be easier to go second choice
Second choice: writing Raw SQL request, which will smth like
ORM.makeRawQuery("SELECT Author.Name, Count(Book) FROM Authors \
Join BOOKS on Author.ID == Book.iD
Group By Book")
In order to do that all you need..
https://sqlbolt.com/ to go through this interactive course to find how to do that
SQLBolt provides a set of interactive lessons and exercises to help you learn SQL
he just needs to complete homework. He does not need safety, sensitization or any other security measure
however he has some knowledge for future
Hello guys, I have a question. Would you say python would be a good choice to write a web app that would go onto websites and make a summary of the posts of said website that I can review/read?
Yep.
You can look into Beautiful Soup.
Humm that's interesting I'll look into this and JS and weight the pros and cons of each languages for that , thanks !
any django queryeter here ?
Wat.
good evening. A question for python-django experts: Because I have no knowledge in building rest apis - is it possible to fetch api data in python and request this data with react frontend? Main purpose of this would be to destructure to simplify access and also resell the gathered data
Yea, sure it is.
Maybe there are exceptions, but you can really use any front-end framework to plug in to any backend API.
but is it smart to build an api on top of another
How is it one on top of another?
React requesting data from a python API is just one API.
im requesting an api with django, destructuring it and build my own with the provided data
and provide this data to react
Why not just fetch the data from the front-end initially?
mainly for reselling purposes and also because I have huge datasets and figured out it could help to destructure it
But yea I don't see why you couldn't do that.
right now when i request i just get bulk of json data and it would be nice to make it available as single components
Go for it. It's not a problem.
You're still just dealing with one API between your FE and BE
yes I just thought of issues with speed
Oh, well you just asked if it's possible. What issue with speed are you expecting?
I was just brainstorming 😄
You'll have to test it and see.
It will of course increase time to get the data if you go from FE to BE to API and back again.
But how much time it increases is going to be dependent on multiple factors.
What database does django default use?
I don't think there is one setup by default, but if there is, I would guess SQLite
There is
You can access users by the admin/
route
I use that for most of my project
s
Considering the fact that most of my projects are on the smaller side of the scale
I think there's a glitch with discord when if you type one letter even. It says you are typing
class InvoiceForm(ModelForm):
class Meta:
model = Ledger
fields = (
#'branch_name',
'vendor_name',
#'account_no',
#'transaction_type',
'invoice_date',
'invoice_no',
'transaction_amount',
)
#vendor_name = forms.ModelChoiceField(queryset=Vendor.objects.values_list('vendor_name', flat = True))
widgets = {
'invoice_date': DateInput(),
'vendor_name':forms.ModelChoiceField(Queryset = Account.objects.values_list('vendor_name')),
'invoice_no':forms.TextInput(attrs={'class': 'form-control', 'placeholder':'Invoice Number'}),
'transaction_amount':forms.TextInput(attrs={'class': 'form-control', 'placeholder':'Amount'}),
}
Anybody know how to get choices from a query into my form?
I did it through widgets before but now its not working
A secret key is required to use CSRF. Flask where can i send my key
config file SECRET_KEY = 'the random string'
`app = Flask(name)
db = SQLAlchemy (app)
bcrypt= Bcrypt(app)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
app.config['SECRET_KEY'] = 'SekretnyKlucz'
`
this>?
but no working
i must paste
this key
but where
havent used flask in a while but dont think it matters - as long as its not in a function or trapped behind a loop
Is there a really good Django tutorial out there? The official docs seem to be a little convoluted for my tastes...
Django Girls Tutorial is great.
I tried looking in to a Django Girls tutorial (since I am looking for a good beginner friendly tutorial) but wasn't able to find much. Any link you could provide ?
First google link? https://tutorial.djangogirls.org/en/
i hosted my django app on heroku but the thing is that heroku's postgres db always resets when new commits are made
because of which old data gets lost
how should i fix this
Host your DB where it doesn't reset?
Is that a heroku limitation for a free tier or something?
i am not sure but it saves all photos just till the time i dont make any new commit
then all photos are lost
No clue, sorry.
Where are you saving the photo files?
My hunch - I assume you are using an ImageField in Django. The database doesn't actually store the files just a reference to where they are uploaded. If this to a local filesystem then this is your issue. When a new commit (and therefore a deploy) happens within heroku, it will spin up a completely fresh dyno (which will have a fresh local file system) so your database doesn't know where they are. In fact they would have been deleted when heroku destroyed the old dyno.
Assuming the above is correct, I would recommend changing your Media Storage and associated settings to use S3 or similar (the django-storages library helps here), I would also recommend switching over your static settings so these are served more performantly.
token = serializers.SerializerMethodField()
email = serializers.EmailField(
required=True,
validators = [UniqueValidator(queryset=Occupier.objects.all())]
)
username = serializers.CharField(
required=True,
max_length=30,
validators = [UniqueValidator(queryset=Occupier.objects.all())]
)
occupation = serializers.CharField(
required=True,
max_length = 30,
)
password = serializers.CharField(
required=True,
min_length=8,
write_only = True
)
class Meta:
model = Occupier
fields = (
'token',
'username',
'password',
'occupation',
'email'
)
def create(self,validated_data):
password = validated_date.pop('password', None)
instance = self.Meta.model(**validated_data)
if password is not None:
instance.set_password(password)
instance.save()
return instance
def get_token(self,obj):
jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
payload = jwt_payload_handler(obj)
return token```
So it looks like in a recent Django update, the WSGIRequest class was modified to remove, among other things, the is_ajax attribute.
Does anyone know what was put in its place to replace it? I have a contact form that is now breaking due to this update.
I’m working on a flask app that interfaces with another 3rd party api that the user logs into with oauth. My plan was to use something like Flask-KVSession to store the oauth token in a serverside session instead of a client session, but looking through the change log and code it appears that the library uses pickle to serialize the session data before storing (https://github.com/mbr/flask-kvsession/blob/83238b74d4e4d2ffbdfd65c1c0a00ceb4bdfd9fa/flask_kvsession/__init__.py#L128). My understanding is that pickle is vulnerable to exploits in this case because the data is coming from an untrusted source. How can I work around this to just serialize the data to json. If I subclass this class and override the serialization_method property will that work? Or is it enough to just dump the data to a json string myself before setting it in the session?
flask_kvsession/__init__.py line 128
serialization_method = pickle```
Flask-Session does the same thing and uses pickle for serialization
This is a css problem .
When I removed a materialize css I’m using the forms appear .
541t…. 🥶
Well, if anyone is interested, I figured out the question I was asking about earlier. As of Django 3.1, the request.is_ajax method was apparently deprecated. Now that I am using 4.0, it appears to be completely unsupported altogether. Now, Django has pushed the responsibility of AJAX detection onto the dev. Here are the Django 3.1 release notes verbatim:
"The HttpRequest.is_ajax() method is deprecated as it relied on a jQuery-specific way of signifying AJAX calls, while current usage tends to use the JavaScript Fetch API. Depending on your use case, you can either write your own AJAX detection method, or use the new HttpRequest.accepts() method if your code depends on the client Accept HTTP header."
Maybe I’m thinking of this wrong, if the pickled data is saved to the database and then read back out, it’s not editable by the client like if you were using client sessions and pickling the data
What do most people use for authentication / authorization in flask APIs?
Okta or something? Right now I’m messing around with LDAP and it’s hard
Im guessing this is the place to talk about this.... I want to make a program that fetches me new facebook posts of a particuler person. Any advice on the framework to use? Im very new and building this will be how I learn.
Here's a simple example using Requests and BeautifulSoup (ignore the paid services that come later). https://earthweb.com/how-to-scrape-a-facebook-group-with-python/
@golden boneAwesome, thanks!
Flask-Login I guess, haven't tried it but have seen tons of tutorials
Postgresql for data storage
Awe
I’m messing around with LDAP right now but I’ll just use normal SQL for logins later
Cookies for temporal storage of authenticated state
Cookies verified by encryption line verifying state by secret key
JWT cookies basically
In flask people have it named session I think
I’m trying to replicate the Shell4j vulnerability for education rn
anybody run a tailwind build recently? half of the classes are missing for me, and h1 tags arent rendering bold (New project)
Heading elements are unstyled by default - just saw on the site .
The tutorials I’m following completely omit that point
from flask import Flask
from threading import Thread
app = Flask(__name__)
@app.route('/')
def main():
return {"hello": "everything is ok"}
def run():
app.run(host="0.0.0.0",port=8080)
def a():
server = Thread(target=run)
server.start()
Showing invalid identifier error?
i have a
TexPassword = PasswordField('Password:')
i set the value
Form.TexPassword.data = 'SomeEncryptedText'
display the form
{{ Form.TexPassword(class="form-control") }}
but i get an empty TexPassword in the web page instead asteriscs
what have i miss?
i wanna render <reason> in a page but after reendering the page its not visible cause the browser is thinking that <reason> is a tag but it is not, instead i wanna render it like <reason> in the html page
escape html
https://www.freeformatter.com/html-escape.html
<reason>
A free online tool to escape or unescape HTML documents and files
thanks
great
I have this signal to dispatch an event when a new message is created ```py
@receiver(post_save, sender=Message)
def new_message(sender, instance, created, **kwargs):
channel_layer = get_channel_layer()
if created:
chat_group = instance.channel.chat_group
for member in chat_group.members:
async_to_sync(channel_layer.send)(
f"User-{member.user.id}",
{
"type": "chat_message_create",
"payload": MessageSerializer(instance).data,
},
)
this is the `consumers.py`py
import json
from channels.generic.websocket import WebsocketConsumer
from api.serializers import UserSerializer
class ChatConsumer(WebsocketConsumer):
def connect(self):
user = self.scope["user"]
self.channel_name = f"User-{user.id}"
self.send(text_data=json.dumps(UserSerializer(user).data))
def disconnect(self, close_code):
pass
def chat_message_create(self, event):
print("Created")
self.send(text_data=json.dumps(event["payload"]))``` and when I create a new message in the admin panel the signal gets called but it does not get dispatched through the websocket, and any debug prints in `ChatConsumer.chat_message_create` won't even get printed.
Thanks in advanced
how do you get variables from client side js
to python server
mdn
Yes, it has django now
It is also a very nice resource for html, css, js or node.js
using flask btw
POST requests data json payloads (typically used in forms)
and GET/POST requests query parameters
also sticky cookies technically carry data between clientside/serverside too
Hello! Does anyone have a tutorial on how to handle authentification with Django (backend) and React (frontend)?
Django, API, REST, Authentication
if to use out of the box solution
or you can apply your custom authentification with JWT tokens
https://pyjwt.readthedocs.io/en/latest/ and stick it to cookie.
In login request you attach cookie in return
and when user tries to visit auth only resources, you try to read the cookie
and use library to verify it, if everything is good, then user is identified
Thanks 
regarding filters.SearchFilter in django, is it possible to include object ID in search_fields?
I have a django+react application which is hosted using nginx and gunicorn. Although the page load is working properly and server has good amount of CPU ,RAM and memory but the queries are taking a long time to respond when there is a some traffic on the website. Can anyone help how to cache or change some configurations in nginx or gunicorn so that it could be handled?
what queries take a long time? Maybe try to optimize these queries (like build an index, or only query for data that you'll use), or cache the results of those queries if you can with something like redis or something
maybe ask in #data-science-and-ml
ok, but also , does increasing workers or threads in gunicorn affect the time taken to send data to the user?
hi can anyone help me wtith JQ
i want to replace the body of my webpage with the "new" data from an ajax post , but i do not want to include a div with an id of navBarID
success: function (data) {
$("body").html(data);```
that is what i have now atm, it just replaces the whole body with the whole of the html code which messes up other parts of my code, so i wanna just replace everything except the div with id navNarID
success: function (data) {
var responseDataNav = $('body : (#navBarID)',data).html();
$("body").html(responseDataNav);```
i have done this which seems to work. however im not sure if the nacvbar is still being replaced
as my problem stands, when i replace the whole body, my navbar dropdown function stops working, this doesnt happen when i replace ONLY the relevant thing (table) that i want updated visually , i canot do that way as the response (data) has some extra lines of html code which is needed , hence why ive been stuck replacing the whole body
Are these type of queries safe againts sql injection? I tried escaping the values with the markupsafe module, but that changes the data type and to markup and I don't think I can use that in my queries. Maybe I can convert the result to string but idk if it the value will stay escaped xd
doesnt whatever you're using provide a method to avoid sql injection
I am using the mysql-connector-python module. There I use a method called cursor from the connect class. That method gives me a cursor object that has a execute method. Sorry I now see that my image is garbage, I'll make a new screenshot oops hehe
someone please help => from .views import RegisterAPIView
ImportError: cannot import name 'RegisterAPIView' from partially initialized module 'Occupier.views' (most likely due to a circular import) (/Users/samuelihuoma/Desktop/occupy/backend/Occupier/views.py)
is there any way to access kubernetes cluster through django
That sounds pretty strange
By any chance you have no idea what k8s is, right?
Anyway, that's possible of course, but what would be the point? 🤔
Oh right. There is a point. To raise temporal instances of smth for particular users for example
k8s tutorial works in this way i think
yeah that should be fine
well what I want to do is build a machine learning web app, but since ML takes so much computing power, I just want to host the model on k8s and then access the cluster to make computations for the algorithm
I don't want to deploy the whole application in a cluster
just the model
I know you can host a model on k8s, but I have no idea how to make calls to it so that I can access the model, make predictions, and return results
through django, I can do this through the command line of the google cloud platform
Nice, thanks
treat k8s as one big VPS server (that secretly has actually a lot of VPS servers behind it), that has exposed only particular ports of load balancers to running containers of applications
essentially not really a big difference from regular server
So as long as your application can be wrapped to docker container and running statelessly with it, k8s is your friend
yeah so I'm going to wrap the model in a docker container, but the question is, how can I send requests to the container in order to generate predictions
the only examples I've seen have used curl in the google cloud command line
Any requests / beautifulsoup4 experts around? Trying to figure out why I can't touch zara or hm, always getting the access denied no matter the header I use.
why whan i loading an img with a clear background with PIL it load it up like it has white background ?
this is the code:
from PIL import Image
s= Image.new("RGB",(255,255),color=(255,0,255))
s.paste(Image.open("h.png"),(0,0))
s.show()
h.png is the img with no background
<@&831776746206265384> !rule 5
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
you don't have consent of web site owners, don't you
It's per TOS / research purposes
I have no problem deleting the question, but keep in mind that an open web benefits all
can i get some help with that ?
bots like that make unauthorized high load to web sites
and gather data belonging to web site owners without their consent
In the same way that closing it behind stuff like url shorteners is against everyone's benefit
You do like Zara a lot, don't you? :))
hello hello
we generally don't allow helping with webscraping projects, unless the site specifically permits it in its ToS
first time hearing about it
so, please do not discuss your project here
sure, no problem
It's not a project, was just curious how a website can block access w/ the right user agent
Which I don't think is a breaking-the-law question tbh.
some people don't find an issue in racism, and don't think that it breaks any law. But it breaks.
let's move on to some other topic please
I'm in awe, learning and all 🙂
mybe u can help me ?
Indeed. Question, last few months I worked on a web site.
I made two different versions of its interface
could you evaluate which one is better?
I am a bit incomfortable to drop link to public, I'll write url to DM if not a problem
it is relativelly small web site out of just three pages.
this doesn't seem too related to web development 😅, please re-ask your question in one of the help channels (see #❓|how-to-get-help if you're unfamiliar with how they work)
Is Django even useful if I like writing custom queries and deserializing them to Python objects?
can someone help with this please ? => raise TypeError('view must be a callable or a list/tuple in the case of include().')
TypeError: view must be a callable or a list/tuple in the case of include().
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('rest_framework.urls')),
path('api/', include('Occupy.urls', namespace='home')),
path("api/","Occupier.authentication")
]
Guys is it possible to learn to make a native app in a month
for someone who has an understanding of programming
and some beginner experience with django, ccs, html, fastapi
trying to get to grips with tailwind, how do i make my sidenav the whole page and overlay. its currently just popping in above r below text
you might be able to help, since you're the tailwind guru
usually I'd say set it as absolute position, 100vw height, and width based on breakpoints possibly
but there are lots of ways to do it, many i'm sure better than mine haha
Thats a link to a rough idea on a way to do that with tailwind
Where would i crowbar that into?```
<div class="min-h-screen w-full relative">
<input id="my-drawer-3" type="checkbox" class="drawer-toggle">
<div class="drawer-side fill screen w-full border-8">
<label for="my-drawer-3" class="drawer-overlay screen w-full"></label>
<ul class="p-4 overflow-y-visible menu h-full w-80 bg-base-100 fill screen">
<li>
<a>Home</a>
</li>
<li>
<a>Practices</a>
</li>
</ul>
</div>
</div>
This is what im going for but need it as a pop out menu, ive looked online for an hour
i should mention - im using daisyui for tailwind
only because i couldnt find anything that does what i need in standard
Not sure on DaisyUI, I've never used add ons with tailwind, But as far as placement I can't help much there because it really depends on the rest of the html hierarchy. as far as making it a pop out I'd imagine you'd use JS or what not to do that
unless something like Diasy or your frontend framework if you have one has that functionality
Might https://headlessui.dev/ have what you want?
HeadlessUI is great
My site actually has a pop out already , but I’m using like 3 diff css frameworks and it’s messing up js and even some django form types and not loading them.
So I have to replace my css with something lol
But I would think its better to do it more from scratch so you know you can before offloading it
Sounds like you've fallen prey to what I'm now calling too tall of a stack
it can be tempting to load in a ton of extra libraries and frameworks but unless theyre really needed and make things better for that exact project you'll want to use a few as possible in general
exactly, i have bootstrap, materialize and materialize md. and a load of random js cdn and scripts.
desperately trying to consolidate
most of them i loaded in for a single button lol
Personally my base stack is just html / css / js / vue / tailwind
edit: also Vite
my first django project, and already deployed to end users - oops
i only add things on past that if i need them
the actual project is super stable, but its like a jenga tower, if i touch something......
I mean is that stable though? haha
let me check it out!
touche .
I for sure need to do some reconstruction to the ui after removing libraries.
One of the elements that screws up after deleting materialize is is my nav bar hence the query
this stuff is cool but i dont know how to use react....i think i need to learn
Are you using a JS framework?
in my actual project im using a couple of jquery cdns, but mostly putting in random js - which i also dont really know
i've hit a ceiling i think, i'll learn js properly next
Oh, then yeah, Headless UI won't work.
its an internal site just for crud operations to a mysql. It got as fancy as a couple of collapsibles....... and then i needed a graph, and then i designed it for mobile with a bottom nav and notification badge, and then i wanted fancy buttons....
its all my own fault
ew, Jquery? @daring isle wash your hands
1. jQuery is a legacy library. Standardized features like querySelector, CSS animations, and fetch make many of its features obsolete.
2. Using jQuery over standard features is a waste of bandwidth.
3. Because jQuery is so bloated, using jQuery often means using jQuery for everything, which means you learn less about standard web development.
4. jQuery has fallen out of fashion, and full frameworks (React, Angular, Vue) are more popular.
5. With modern frameworks you declare a state and your UI reflects your state. Rather than with jQuery having to manage both the state and the UI all at the same time.
6. jQuery's cross-browser support can be substituted with the few polyfills you actually need. This also makes it easier to update when features become better supported.
7. If you really just want a shorthand for querySelectorAll, consider bling dot js```
I blame the youtube algorithm and plead ignorance
😩
It's ok bb, we love you
it's still useful, but if you like writing queries, then I would recommend just using something like NodeJS
@app.route('/check/<string:subid>')
def gifts(subid):
q = Detail.query.filter_by(subid=subid).all()
return render_template('check.html', q=q)
I created a function that allow all child object can be returned with <p>{{ q.name }}</p> however, when I opened the site, nothing showed up, how can i fix it?
its just <p></p>
<p>{{ q.name.__repr__() }}</p>
it returns Undefined 😅
err, None?
do i need to "convert" my django project to rest if i want to use react in it?
<html>
<p>Undefined</p>
</html>
Hi, I'm running a Flask site with Nginx and Supervisor (to run in background). Lately, I've been having issues with the web server recognizing changes to any of the Python, HTML, CSS, or JS files.
Whenever I work on my site on my machine, I run it using the debug option on localhost. Everything works perfectly fine, and I see it in real time. But whenever I push it to my remote server, the website does not process any of the changes made to it. For example, I've recently created a new route within Flask. On the live server, those webpages are "not found".
And yes, I'm reloading everything correctly.sudo systemctl restart nginx sudo supervisorctl reloadIf it helps, I think the problem has started ever since I've added an SSL certificate to my site. No idea if it correlates at all, but it helps me figure out what changed to make it not work.
Thanks in advance for helping me!
it depends on how you are wishing to attach react into it
but in general I would recommend converting to rest, as it is the best and easiest approach IMO
some people would disagree with me though
btw, if you plan to have a lot of endpoints (more than 20-30?), there could be a point for graphql approach instead of rest.
How to add margin b/w previous next
like previous on left and next on right
Not true
REST and GraphQL have their trade-offs, for example it's easier to fetch relations using graphql but REST is more mature and has many problems already solved for you, e.g. permissions, authentication, etc
Relations? I thought relations were more more about using Neo4j graph database?
Both approaches are great and you can expose both REST and GraphQL API in your app
Relational data, e.g. fetching posts of a specific user
How to deploy my ml model in flask
All right, so you spoke about SQL normal databases too
Well, both rest and graphql are storage agnostic, so you can use any persistence method
I thought that GraphQL allows to make more customized data request in one request as a main thing
which allows to remove a lot of REST endpoints and having them all united into one
Yep! When using rest you'd have to create a ui-specific endpoint that will fetch nested data, for example you might want to fetch user, his posts and all comments for these posts
With graphql you can just write a query for that, but with rest it's either making 3 calls - to fetch users, his posts and post comments or making a specific endpoint that would return everything in one go
and in some cases just user and his posts
or in some cases user and his comments, and e.t.c.
With graphQL is is DRYed into one endpoint, potentially just less code to have for all of it
It's not necessarily more dry but you just don't have to make multiple http calls and join that data on your frontend
Which is great too. Than less http calls, then faster it happens. Most of the delays from all those requests
There's a JSON:API but i'd rather use graphql 😅
https://jsonapi.org/
Ideally you should learn both, imo it's easier to write mutations using rest rather than graphql
Plus if you expect people using your api programmatically it's in most cases easier to do using rest
and json:api stands here as a third approach, similar to graphql?
rest is only single endpoint purpose approach?
or it can include jsonapi approach
json:api is built on top of rest and makes it easier to fetch relational data, but it's easier to use graphql for that
where i add ipynb file in flask static or templates
so.. json:api is mutant-hybrid between rest and graphql then?
reply
Kinda, you can look at the spec and see 😅
thanks. Curious explanations 😁
that's why I had trouble to find it 🤔
i was confused to search it at the right, while it is at the left
completely no idea. You did not provide any code, just rendered result
so let me assume that you just have an image then
then removing it is just a matter of using photoshop or even simple paint program
https://photopea.com here is online photoshop program for you
Photopea Online Photo Editor lets you edit photos, apply effects, filters, add text, crop or resize pictures. Do Online Photo Editing in your browser for free!
HI I am trying to implement copy to clipboard in my Django app and when I did so am able to copy only a single word from the starting of sentence please some help me regarding this
main.js
console.log(copyBtns);
copyBtns.forEach((btn) =>
btn.addEventListener("click", () => {
const value = btn;
console.log(value);
})
);```
{{ post.date_posted|date:"F d, Y" }}
<button class="btn btn-outline-primary ctrl-btn" post_data = {{ post.content|cut:' ' }}>copy</button>
</div>```
<button class="btn btn-outline-primary ctrl-btn" post_data="Eratexpetendadefinitionemideos.Sempersuscipiteumut,eumexnemorecopiosae.Namprobatuspertinaciaeu!Noaliivoluptuaabhorreantnec,teproimpeditconcludaturque,inseamalistorquatosdisputationi!Namtealiinobisponderum,eifugitaccusamuspro." conguesalutandiexeam!meianprimaconsulatu,eratdetractoeuquo?vimeaesseutinamefficiantur,atnosterdicunt.="">copy</button>
when I try to print this some of the data is missing please help me with this
const value = btn.getAttribute('post_data')
I only get
"Eratexpetendadefinitionemideos.Sempersuscipiteumut,eumexnemorecopiosae.Namprobatuspertinaciaeu!Noaliivoluptuaabhorreantnec,teproimpeditconcludaturque,inseamalistorquatosdisputationi!Namtealiinobisponderum,eifugitaccusamuspro."
rest of the data is missing please some one help me with this
how do i show an image in flask ?
<img src="path to image"> (I remember flask has some sort of variable that leads to folder with static assets)
yes
why is it look like this ?
in the py code ?
lemme check your html code first
this is the code :
@app.route("/img/<path>")
def img(path):
return f'<img src="{path}">'
(flask)
it runs on replit btw
hmm
Well, then you gonna have use absolute path to load the image
do you know how i do that with os ?
like going to: localhost:8000/img/gg.png wouldn't work
I have never done it in replit sadly ¯_(ツ)_/¯
i gtg-
ok
it means got to go btw
Pls zoom it
i cant
Hmm
here is me
Ok I help
where do u need to help?
Listen did u make a index.html?
no
i dont know why its not showing the img
lokk
so you will allow a template injection
i dont know what is template injection
If you already know the possible paths make a white list
i dont it will always change
allowedPath = ["img1.png", "img2.png"]
if not path in allowedPath:
return "Path not allowed"
hmm
this server is for my discord bot
?
i want to show images on the server cause discord.py embed dos not support files only urls
so make a directory into the web root called /img and then put into that all images you need
you mean a folder ?
like a file folder
yes
ok but than what
then you will be able to see the images
the discord bot and the server and the images are in the same folders
but
whan i run the server
i need to show me the img
but
it shows a small icon
if the size icon is as small as icon size it's ok
not like this
you see this ?
this is not my img
idk what is this
and its really small
this is the hole website
it need to show an img but it shows me this
?
it's not an image
ok
with the same folder with the server
it's xss vulnerable too
People will be able to execute html and xss on your site
im trying to login in my DRF api thru postman and it even says that my user exists but when i try and login i get => {
"message": "Invalid credentials, try again"
}
idc
you should know something of web security before of make web application
cause its just for my bot
#authentication_classes = ()
#permission_classes = ()
serializer_class = LoginSerializer
def post(self,request):
email = request.data.get('email',None)
password = request.data.get('password',None)
occupier = authenticate(username=email, password=password)
if occupier:
serializer = self.serializer_class(occupier)
return response.Response(serializer.data, status=status.HTTP_200_OK)
return response.Response({"message":"Invalid credentials, try again"}, status=status.HTTP_401_UNAUTHORIZED)```
still if you was running that on your pc XSS attacks aren't able to attack the server
while SSTI are able to attack the server
Is there a great tutorial that describes how to use Django’s templates with a client side framework?
I really miss the ergonomics of server side rendering. But definitely see the benefits of a client JS framework.
Hello Im using this svg: https://pastebin.com/xL0ixf2w
Im getting an error: error on line 38 at column 26: Comment not terminated
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.
ig ill just use a png
what if to try using something more native to frontend frameworks for that
Next.js for React, Nuxt.js for Vue.js and e.t.c.
i believe you can plug in vue to your html files
like regular js
react too if i remember correctly
that way you can still use django to render your templates but have some parts of your app be reactive i guess
I'm trying to use selenium to get the text of this svg element, but self.driver.find_element(By.CSS_SELECTOR, self.level_path).text doesn't work
https://imgur.com/RQFRJJY
it just returns an empty text
it gets the svg element, but idk how to get the title
I guess I’m asking if using Sever Side rendering with Django is somewhat mutually exclusive from using a client framework
I mean I can imagine it’s possible. But is it an uphill battle
Your app can provide both server-side rendering(if we're talking about template rendering) and api for your frontend client
Django provides admin app that uses template rendering and you can still build api's using django 😃
it is possible to use together. I am sure that it is at least compatible with Vue.js
can't say for other frontend frameworks for sure
anybody know how to center the hover box in react?
.nav-text a {
text-decoration: none;
color: #f5f5f5;
font-size: 18px;
width: 95%;
height: 100%;
display: flex;
align-items: center;
padding: 0 0px;
border-radius: 4px;
background-color: #1a83ff;
}
One of these SOBs is causing it since i put the background on and its the same if not hover
Right. I’m sure it’s possible. But doesn’t client framework development / debugging require a rendered DOM structure? Seems like React elements would not be compatible
just center the object itself
then its hover will be centered too
thanks man
Hmm, it looks like alpine.js fits my needs
Who said you have to request html from your backend using react? 🤔
No one said I do. But sometimes the ergonomics of server rendering are really enticing.
template rendering can be good if your project isn't big, e.g. a blog or something similar
But for larger project i'd use a frontend framework, (Angular, Vue, React...) since it allows for better code separation between your frontend and backend
And are easier to work with in general imo
there's an extremely simple php-driven website I use as an image host. I'd like to automate the process of logging in and uploading an image. the web automation frameworks I've found (selenium, cypress) seem to be very over-engineered for this purpose. does anyone know of a simpler alternative that could navigate a login control and that's about it? there isn't even any javascript on this page
i'd inspect the request in browser console and then replicate it with curl
bash is evil 😄 but maybe I can replicate it with requests
i agree with you 😄
You should probably ask a question.
But you are missing an in for what it's worth.
Will I run into issues if I have all my flask api endpoints in the same file? Is there a standard people follow for organizing the backend in python?
wouldn't say an issue, could end up being disorganized. I believe flask uses Blueprints for this, or used to
It's fine to put all your routes in one file. https://auth0.com/blog/best-practices-for-flask-api-development/
in css text-align center
how can I access all child object under one parent object with flask sqlalchemy?
My model is not deploy on flask
model=pickle.load(open('model.pkl','rb'))
ModuleNotFoundError: No module named 'sklearn
Hey @native tide!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
Hey @native tide!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
Hey @native tide!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
Hey @native tide!
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:
Your message is too long, please read the message from the bot instead of resending it
my ml model is not deploy in flask
showing sklearn error
@native tide <h1 style="text-align:center"><u>PROJECTILE MOTION CALCULATOR</u></h1>
i want to add color style too how can i do that?? im so smh
💢 im figuring out for so long
Ok
do you have a css file?
no im on html
you will need a css file or a css framework
recommend going with file for now
yea maybe i have css extenstion
...
that's not a framework
output
@native tide
Ok
all i want to do is add color too the heading
<link rel="stylesheet" href="style.css">
add this line
here somewhere
done
then
create a file called style.css
in the same folder
what is a way that flask and react can have authentication, i mean ik how flask login works but idk how it would work if you login a user using flask by sending login info from react frontend and authenticating it through flask but idk how to sustain that if im using react. how could those login_required restrictions apply to the frontend as well
make a route that checks whether a user is authenticated or not, and in react, make a call to that route anytime you need to verify authentication in react. like you could keep this in a state and constantly update when an action happens for example
Not really understood what you are saying
perhaps you could draw simple sketch in paint/photoshop of what you are trying to achieve
wait a second, perhaps I start to get
are you wishing to make them drag and droppable by mouse? or by clicked buttons? or by pressed keyboard buttons?
with relocating to switch their places?
Well, obviously that involves using javascript, the easy way would be to have frontend framework to write it
the painful way would be to use vanilla JS
semi painful way would be JQuery
frontend frameworks make it way easier and with less code ¯_(ツ)_/¯
Vue.js for example
probably React should be easy too
Vue.js is the simpliest to learn out of modern production ready frameworks
everything depends on the learning speed, but consider usually a week to get into the flow
Technically it is written being possible to learn from few hours to one week, but it surely took me a week
because i learned frontend from zero
MM yeah, but preferably start to use Vue.js 3 already
you can do the same with react
they explain it in the docs
here's a link
@thorn igloo can u help me deploy my django application on a vps hosting
never used django in my life
so u use flask?
yes
if i said i knew how i'd be lying
im not asking django
i've just use the cheap cpanel hosting, does almost everything for me
ohh
yeah i get what you're asking
maybe try this
additional help here
relatively easy would be to buy domain in namecheap.com
to point AAA records to your IP address
bruh ig u can help ezily
we bought it from godaddy
we bought domain from godaddy
n hosting from Hostinger vps hosting
https://certbot.eff.org/
you can use this for free at the cost of more complicated setup
Tagline
it is for Certificate
domain is still required anyway
ik
Oh forgot to mention
we bought it
There is FREE TO USE option for domains!
there are services that provide subdomains for free)
@inland oak can i get ur 5 mins?
not rembmering from the top of the head their name
but I remember they provide like 16 free sub domains
..
ohk so the thing
i just made a directory then dumpted the zip n unziped n at startup file i toom wsgi so my hosting started running
idk why i cant point the domain
what is the best way to access variables from the "main" flask file in a blueprint file?
oh
sorry to interupt
you probably mean config variables?
Setup your app on a server with nginx forwarding the request from port 80 (or 443 if you have https) to your backend.
Find the IP address of your server.
You can then go to the settings of your domain on goDaddy, and add an A record (which is the IP address of your server). When someone visits your domain, the IP will be resolved from the DNS and they will make a request to your server's IP address.
config variables are injected in flask into app instance
and those vars are available with special flask import config through the applcation
python intance objects are imported in the same way as python objects are imported in general. absolute or relative imports.
hey, the AApanel is doing that stuff for me , my vps hosting is working fine it's on
see this @opaque rivet
this too running
it has been a year since I used flask, a second
np
No clue what I'm looking at, I would personally just do it myself instead of having a manager unless you understand exactly what that manager is doing
@opaque rivet my site is also live http://www.funssignment.com/
plz guide me
what i can do next
okay cool, so it looks like you have an A record setup to map your domain to your server's IP address.
Now setup nginx
ohk how
Watch some videos/guides online and learn nginx
example taken from here https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-xxiii-application-programming-interfaces-apis
import os
from dotenv import load_dotenv
basedir = os.path.abspath(os.path.dirname(__file__))
load_dotenv(os.path.join(basedir, '.env'))
class Config(object):
SECRET_KEY = os.environ.get('SECRET_KEY') or 'you-will-never-guess'
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL', '').replace(
'postgres://', 'postgresql://') or \
'sqlite:///' + os.path.join(basedir, 'app.db')
SQLALCHEMY_TRACK_MODIFICATIONS = False
LOG_TO_STDOUT = os.environ.get('LOG_TO_STDOUT')
MAIL_SERVER = os.environ.get('MAIL_SERVER')
MAIL_PORT = int(os.environ.get('MAIL_PORT') or 25)
MAIL_USE_TLS = os.environ.get('MAIL_USE_TLS') is not None
MAIL_USERNAME = os.environ.get('MAIL_USERNAME')
MAIL_PASSWORD = os.environ.get('MAIL_PASSWORD')
ADMINS = ['your-email@example.com']
LANGUAGES = ['en', 'es']
MS_TRANSLATOR_KEY = os.environ.get('MS_TRANSLATOR_KEY')
ELASTICSEARCH_URL = os.environ.get('ELASTICSEARCH_URL')
REDIS_URL = os.environ.get('REDIS_URL') or 'redis://'
POSTS_PER_PAGE = 25
the config file is injected into app instance in __init__ at almost source code root, download the project files and check for yourself
def create_app(config_class=Config):
app = Flask(__name__)
app.config.from_object(config_class)
Then you import in any app file and accessing it through the flask library
from flask import current_app
current_app.config.get('SQLALCHEMY_DATABASE_URI')
ty
Django user for a year already but still remembering it
heh and I thought my memory is bad
its showing the default Apache2 Ubuntu Default Page
page
now whats the use of nginx
that's for you to find out
or even better, there is Nginx free O'Reilly book distributed by Nginx company!
https://www.nginx.com/resources/library/complete-nginx-cookbook/
beautiful
indeed. O'Reilly and Free. Just yay
makes me loving for that
that's not the only one book they have for free
Traefik is also a good choice 
web application security is good to read and few other books are also provided there for free
But it depends on your needs i guess since traefik is just a reverse proxy
I heard it is often as used as more advanced caching solution
nginx can work like that too, but some stuff is locked behind paid verison
dedicated tools can be better than general purpose nginx
hey there
like using Haproxy for loadbalancing, instead of Nginx where almost all load balancing is locked out
Yep, community edition can't cache anything but often you can control cache on server side or on client side (using http headers)
nah, it can cache
I mean i was able to setup server side caching to cache REST api endpoint from my python web server
that's good)
Docs point to traefik enterprise though 🙂
Well, that's what i said - you can cache on server side
@serene prawn still idk why it isnt pointing on the Hostinger vps hosting
but yeah site is running
What exactly doesn't work? 🤔
thats not specific is it
where can i open my datebase app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db' app.config['SECRET_KEY'], = 'thisisasecretkey'?
https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-iv-database
This page contains code examples for that
okey
SQLAlchemy and sqlite are different things. SQLAlchemy is an orm(relates python objects/models to sql tables) while sqlite is an example of a sql db(others include MySQL, PostgreSQL)
so which you recomend to register, mails, passwords
You misunderstood what he said. SQLAlchemy can use sqlite3 under the hood. It sits at an abstraction level above the database connection itself. You can use it to manage connections to various databases (using their respective drivers) like MySQL, PostgreSQL, Sqlite3, etc..
it provides a consistent way to query across the different databases, so I suggest you use SQLAlchemy like this: https://docs.sqlalchemy.org/en/14/core/engines.html#sqlite
aha
here's more info about how to use SQLAlchemy: https://docs.sqlalchemy.org/en/14/core/connections.html#basic-usage
so
using SQLAlchemy can i conecct with Sqlite3 ?
etc.
yes. the first link I posted shows what a connection string looks like with sqlite3, the second one shows how to use the resulting "Engine" created from that.
okey
i don't consider the following problem as an error, so i'm writing here.
My Django app's file structure is:
.
├── api
│ ├── db.sqlite3
│ ├── debug.log
│ ├── __init__.py
│ ├── manage.py
│ ├── products
│ │ ├── __init__.py
│ │ ├── __pycache__
│ │ │ └── __init__.cpython-39.pyc
│ │ └── v1
│ │ ├── admin.py
│ │ ├── apps.py
│ │ ├── __init__.py
│ │ ├── migrations
│ │ │ └── __init__.py
│ │ ├── models.py
│ │ ├── __pycache__
│ │ │ ├── admin.cpython-39.pyc
│ │ │ ├── apps.cpython-39.pyc
│ │ │ ├── __init__.cpython-39.pyc
│ │ │ └── models.cpython-39.pyc
│ │ ├── tests.py
│ │ └── views.py
│ ├── __pycache__
│ │ └── __init__.cpython-39.pyc
│ ├── requirements.txt
│ └── selloff_drf
│ ├── asgi.py
│ ├── config.py
│ ├── database_config
│ │ ├── db_config_dev.py
│ │ ├── db_config_prod.py
│ │ └── __pycache__
│ │ └── db_config_dev.cpython-39.pyc
│ ├── __init__.py
│ ├── __pycache__
│ │ ├── config.cpython-39.pyc
│ │ ├── __init__.cpython-39.pyc
│ │ ├── settings.cpython-39.pyc
│ │ ├── urls.cpython-39.pyc
│ │ └── wsgi.cpython-39.pyc
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
└── client
models.py:
class Category(models.Model):
name = models.CharField(max_length=255)
slug = models.SlugField()
class Meta:
ordering = ['name']
def get_absolute_url(self):
return reverse('products:category_list', args=[self.slug])
def __str__(self) -> str:
return self.name
When I try to make migrations, Django writes the following: No changes detected in app products. Please help
i also have my app's name in INSTALLED_APPS
you recomened flask or django?
sqlite is one of many relational database management systems aka RDBMS, it's responsible for storing/querying your data from the disk
SQLAlchemy on the other hand is a ORM, in short it helps you to use rdbms by writing python code instead of sql, though sqlalchemy queries written in python code are very similar to sql in structure.
SQLAlchemy can be used with most of the rdbms, including sqlite 🙂
aaaa
You can write query like this using sqlalchemy:
query = select(User).filter(User.username == "AquaCherry")
user = sesion.scalar(query)
And it would be translated to SQL query depending on dialect (sqlite, mysql, postgres, ...)
select user.id, user.username from users where users.username == "AquaCherry";
it depends
That's really vague 🙂
it depends what
All frameworks are good for certain things, e.g. Django has built-in authentication and good for building simple-medium complexity applications, but i personally wouldn't recommend using it for building API's, FastAPI would be a better fit for building API's, but it doesn't have built-in features like authentication, admin panel and orm, so you'd have to build/choose solutions for that, e.g. fastapi-users for auth and SQLAlchemy as an orm
And flask is just obsolete because of fastapi 😛
a okey
`AttributeError: 'LoginForm' object has no attribute 'validate_on_sumbit'
`
Django is not good for APIs? I would disagree to agree. DRF is the ultimate battery included solution to do it in shortest possible time
https://www.django-rest-framework.org/
Django, API, REST, Home
Imo FastAPI does much better job at building api's
DRF does faster development job ;b and all the out of the box solutions allow it having DRYer and more reliable
Fore me it's vice-versa, drf is hard to implement new features with, though initial setup is easier with django
If we're not talking about simple crud
tbh, I am a bit eyeing fastapi to try. But well... there are multiple other technologies to learn more important first. finally got started with kubernetes.
Also django orm is not an opt-in and i don't really like it
I have a project where I'm using django and react and connecting them using graphQL. I have an async function call in django, can I display two different views in react for when the async is processing and after it is done?
Sure. Nothing stops you from that
how would I do it?
What is the average time of the request to finish
about 15 seconds
Your backend does some lengthy job then
yes it is a machine learning process
I would recommend applying Celery then
Probably could set some kind of state or fire an event before sending your request and do the same after it completed
First request launches job in celery and returns task ID
What does it has to do with celery really? 🤔
this could work as well
Then... Ideally you use web sockets
Not ideally you make repeated requests to chheck the job done
To optimize his lengthy job ;b
To load balance it
ok but how would I call the view in react
The question wasn't about that though 😅
He does not know that he does it though
@native tide if i understand correctly you want to display some kind of loader while your request is being processed?
What library are you using to connect with graphql api?
graphene
On your frontend i mean
Just display one thing
Then start request and when finished display another one
axi9os
I would recommend to toggle animation that does smth 15 seconds
axios
Ah, so you're not using graphql-specific library like apollo?
😐
👀 anyone got any idea on why uwsgi would complain modulenotfound: wsgi? the config is properly done following the docs and its a django app
my bad I forgot, this project has been on the backburner for a while now
the problem is it doesn't always take 15 seconds. It can take much longer
I'm not an react expert, i mainly used angular + rxjs, but i think you could do something using hooks 😅
Celery returns if the job is pending or got started
And can return intermediate results of the progress
but can both views be handled in react
Actually apollo already provides loading flag 👀
function Dogs({ onDogSelected }) {
const { loading, error, data } = useQuery(GET_DOGS);
if (loading) return 'Loading...';
if (error) return `Error! ${error.message}`;
return (
<select name="dog" onChange={onDogSelected}>
{data.dogs.map(dog => (
<option key={dog.id} value={dog.breed}>
{dog.breed}
</option>
))}
</select>
);
}
I am mainly angular user as well but I want to add react to my portfolio since I think more companies use it
Most used for sure
Yeah, react is certainly more popular
I like it too, but I think I will be using react mostly from now on out since my friends that I work on projects with like react as well
they are sworn angular haters
😫
And I will try to be not doing frontend next time perhaps. I wish to be more backend and infrastructure guy
Frontend is a bit not comfortable for writing tests. Well... Actually it is easy to write tests .. but still... Meh
@inland oak
im on a vc ft a dude from an hour almost done
ModuleNotFoundError: No module named 'wsgi'
thats the thing that is left
everything is installed up to date
venv is also activated
n all the modules are there (pip freeze op)
we're using uwsgi (same issue was there while we were using gunicorn)
check your path in settings.py
I am almost 100 percent sure that this is causing the error
Just learning djang rest framework and react .
Is the class based view the only or best way ?
In my normal django projects I avoided classes anytime I could and didn’t have any issues
Is it a problem for react if things aren’t defined within classes ?
in flask, how can set de value to a passwordfield?
Form.Password.Data = "abcde"
live the Password object in blank
hey guys, im trying to post information from react to flask
but it doesnt post at all
ik the api is working because if i post using postman it works, but if i post using axios it doesnt work
this is my axios code
function postLogin(username, password){
console.log(`you posted with ${username} ${password} `)
return axios(
{
method:'POST',
'url': 'https://127.0.0.1:5000/login/',
data: {
'username': username,
'password':password,
},
mode: 'cors',
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin',
'Access-Control-Allow-Origin':'*', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json'
},
}
).then(response => {console.log(response)})
}
and ik this code works because it used to work before but i dont know what happened
this is my flask route that this is posting to
@auth.route('/login', methods=['POST', 'GET'])
def login_route():
print('hello world')
username = request.json.get("username", None)
password = request.json.get("password", None)
print(f'username:{username} password:{password}')
data = jsonify(request.json)
data.headers.add('Access-Control-Allow-Origin', '*')
return f"<h1>{request.get_json()}</h1>"
$oRonny — Today at 12:00
this is the whole login.js
https://pastebin.com/drMxkTDe
i could really use some help
i think it some stupid error that i cant see, i dont know what i did for it to not work, it was posting data fine but i think i messed around with some tags and all of the sudden the function postLogin doesnt post data
the console says err:net somthing which is due to the flask server being https but without ssl cert
but it was https before
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.
it does not make a difference besides giving better code structure /readability
Class based view is perfect for CRUD
first function for GET to READ object
POST to CREATE
PUT to UPDATE
DELETE TO DELETE
You are having CORS problem
here is the solution https://pypi.org/project/django-cors-headers/
Cors is enabled in the python route
Check in chrome devtools errors
in console and in network tab
it should be showing CORS errors
I'm using flask brother I sent a code snippet of my route
I already gave the answer. Your code shows me clearly the problem I mentioned
I had the same problem recently
with exception to using Axios to Django
I am lol
use chrome devtools to see the more detailed error then
I have cors initialised in the create app function
perhaps you did not initialized it in the right way
are you using reverse proxies, apache / nginx?
that can be a problem too
https without certs will give just the error of certs
read the error in chrome devtools. for your axios operation. check tabs console and network.
bro im not a beginner
i've checked those tabs and the error which makes no sense persists
show us the logs of devtools then
it says err:network
what says Network tab?
i deactivated the component let me get it back up
make an easy test, change the request to GET
if it will work, then 99% problem is in the CORS
if it will not work, then your http certs problems
postman works