Where is it getting this from?? I already cleared most of the pycache's and there was also no new file created in the root directory of my app
I am seriously going crazy trying to understand where this is being stored
But I guess that is what I get by using a library to do stuff for me I and going the easy way while trying to learn something
can anybody help? I really just want to know where this data is being stored so I can properly clear it on demand 😅
#web-development
2 messages · Page 78 of 1
have you tried checking the cookies?
that's usually where the session variables are stored on the client
Yes, but cookies are only storing the authentication
Not the actual data
And I have already tried clearing the cookies
right and that is used to look up the actual data
what's the /me/guilds route do?
Sorry
Let me do this properly
@app.route("/me/guilds/")
def user_guilds():
guilds = discord.fetch_guilds()
return "<br />".join([f"[ADMIN] {g.name}" if g.permissions.administrator else g.name for g in guilds])
Then this is from the docs of the Library
@staticmethod
def fetch_guilds() -> list:
"""This method returns list of guild objects from internal cache if it exists otherwise makes an API
call to do so.
Returns
-------
list
List of :py:class:`flask_discord.models.Guild` objects.
"""
user = models.User.get_from_cache()
try:
if user.guilds is not None:
return user.guilds
except AttributeError:
pass
return models.Guild.fetch_from_api()
how are you creating the discord variable?
discord = DiscordOAuth2Session(app)
This is the part which I dont get
user = models.User.get_from_cache()
the "get_from_cache"
I dont know where this is from
Clearing cookies does nothing, alt+F5 on the page does nothing, and restarting the app also does nothing
try printing out the users_cache
so like on the main code print(discord.users_cache())?
ok so there's no users in the cache
But maybe because it is running outside the function?
Alright so
@app.route("/me/guilds/")
def user_guilds():
guilds = discord.fetch_guilds()
print(discord.users_cache)
print(guilds)
return "<br />".join([f"[ADMIN] {g.name}" if g.permissions.administrator else g.name for g in guilds])
This when I access /me/guilds returns
127.0.0.1 - - [12/Aug/2020 18:19:03] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [12/Aug/2020 18:19:03] "GET /robots.txt?1597267143283 HTTP/1.1" 404 -
127.0.0.1 - - [12/Aug/2020 18:19:06] "GET /me/guilds/ HTTP/1.1" 200 -
LFUCache([], maxsize=100, currsize=0)
[<flask_discord.models.guild.Guild object at 0x0000016E198DADC0>, <flask_discord.models.guild.Guild object at 0x0000016E198DA9D0> ...
127.0.0.1 - - [12/Aug/2020 18:19:06] "GET /robots.txt?1597267146166 HTTP/1.1" 404 -
So I dont think users_cache is the right cache
flask_discord.models.guild.Guild calls this
@classmethod
def fetch_from_api(cls, cache=True):
"""A class method which returns an instance or list of instances of this model by implicitly making an
API call to Discord. If an instance of :py:class:`flask_discord.User` exists in the users internal cache
who belongs to these guilds then, the cached property :py:attr:`flask_discord.User.guilds` is updated.
Parameters
----------
cache : bool
Determines if the :py:attr:`flask_discord.User.guilds` cache should be updated with the new guilds.
Returns
-------
list[flask_discord.Guild, ...]
List of instances of :py:class:`flask_discord.Guild` to which this user belongs.
"""
guilds = super().fetch_from_api()
if cache:
user = current_app.discord.users_cache.get(current_app.discord.user_id)
try:
user.guilds = {guild.id: guild for guild in guilds}
except AttributeError:
pass
return guilds
current_app is just a module from Flask
And if you know where Flask stores its cache
I think this is the same that is happening here
Seems like flask-discord isn’t doing its job that great if it’s treating the current app as stateless
Idk, I am just a noob using the only Flask Library I could find that handles Discord Oauth xD
What is flask-dance?
Hey guys, what is the standard practice for flask forms? Should I stick with WTForms? I've tried to use Bootstrap to style the form but it ends up not working.
hello, is anyone online?
Hello, regarding django i need to create admins, managers and customers where managers have a set of customers, how do i do this?
My problem is the manager - customer relationship, should i use OneToOneField to User so i can differentiate the types of users and then a foreign key to manager from customer?
Hello, regarding django i need to create admins, managers and customers where managers have a set of customers, how do i do this?
My problem is the manager - customer relationship, should i use OneToOneField to User so i can differentiate the types of users and then a foreign key to manager from customer?
@quiet comet depends on your needs
you could use an abstract model
are managers/customers users?
I'm guessing yes...?
yeah
i need a way to associate customers to managers so the managers can only update info from the associated customers
I realize this isn't specifically related to python web development, but I thought I might as well ask here since you guys would probably be able to help
What is the best/cheapest TLD name merchant/site to purchase from?
no such table: main.auth_user__old what does this mean?
i wanted to add a product from the django administrative pannel but i got that error
i need a way to associate customers to managers so the managers can only update info from the associated customers
@quiet comet how about a self-referential nullable foreign key + a check constraint on a user type column?
i dont really like the idea of one table only but ill try , ty
what's the Pythonic way to consume APIs in Django?
I'm working on something that's 99% REST/SOAP integrations with other services in one app, should I have any Model classes really?
Hey guys! i am making a portfolio and need some templates (in html), if you guys know any pls share you
Thanks in advance
Oy, do soap APIs still exist lol
@covert kernel bootstrap has some nice ones, but that is full html/css/js ... But fwiw, a pure html portfolio isn't going to be very appealing lol
can u give me some links
How can I connect to an Oracle database using Flask?
cx_Oracle
use SQL Alchemy or directly
SOAP APIs are still lurking out there, just not consumer facing anyways
Which is better? PyCharm or VSCode for HTML/CSS/JS/flask/Django projects?
I mostly use PyCharm.
I really like VSCode as well, but the linting in pycharm is much better imo
with that said, I do all my html css js in vscode
Pycharm is better even without pro - but PyCharm Pro makes it even better
with that said, I do all my html css js in vscode
@acoustic oyster so you keep both IDEs open?
I usually split my tasks.
If I am just doing some quick prototyping for templates I just use pycharm, but when I go to get really involved in my front end I switch over to VSCode. I also do my front end in react nowadays, so it makes a lot more sense to use a separate ide.
But most of the time one open, when I decide to really work on the front end I'll start using vscode.
This is mostly because pycharm community does not have js support and I do not own pro, but I really prefer programming python in pycharm
what library or framework is used for this
The Cool Club X FWA - 54 Coolest Websites in History
PyCharm pro has js support
PyCharm doesn't have JS support? did not know that
I see
so i guess VS Code is the way to go
gotta pay for pro to get js support
VSCode is less pay-to-win haha
my god that website is cool
@scenic vapor research
they use vue haha
Yea, that's react's nextjs equivalent
90% of what I have learned from this server is that I should move to Amsterdam
Hey guys!
Just planning to give these assets away!
It's on github and in a google drive.
Hope these come in handy - it's for discord developments.
https://github.com/celestialdream/discordcardgameassets/issues
uhhh what
<@&267629731250176001> help
lol, I guess this is the easy hour of phishing
I will ping you guys again, I swear xD
I don't even see the problem - is it not a real GH link?
it is obv a phishing scam
it links to an empty repo asking you to click a download link
No it's not...It's useless but it's not a scam
oh - no yeah
really? You guys think this is legit?
doesn't seem that scammy
I didnt click the download link
Look where it points, official google url
but like, why would it be a repo link to an empty repo from a generic, bot sounding account
to a google drive
exactly
it is just a drive, there is nothing official about it
it is probably malware when you execute it
It's just .png assets.
in the zip?
^
oh haha
@orchid pier you'd do well next time to work+word that a little.. less suspiciously
the username is the nail in the coffin
for me
and the weird setup
and the fact that they noped out after dropping the link
haha
If there was any malicious intent I don't see how/when/where...It's just weird
It'd make much more sense if it was just the repo README with a link there
I didnt check the link, I assumed it would have executables waiting or some stupid phishing nonsense
yeah haha
Im still sus
although it is possible to have malware on images from what I understand
Yea it's possible
still convinced there is some debauchery here
I got got
Virustotal comes up clean, but as always, download/extract/use at your own risk.
hi
I'm wondering is NGINX better than apache for a web app? I think it could be better maybe for a large scale?
How to ise break in jinja2
You don't. Logic shouldn't be in templates
Ok
I'm wondering is NGINX better than apache for a web app? I think it could be better maybe for a large scale?
@native tide I use apache, I am not aware of any major performance benefits between the two
ah okay
@native tide https://kinsta.com/blog/nginx-vs-apache/
how do i get a html file in my PC with aiohttp ?
Anyone here learning Django and looking for someone to partner up? For learning, exchanging information and actively working on small projects?
is there a way to manipulate html tables using django
like If condition is True:
5 rows or 5 columns
i've grown fond of traefik
i am working on a nginx cache proxy but i dont know why its been slow if it get multiple connection
are there any free website hosting platforms like pythonanywhere?
Got a problem and can't find any solution online, I am using the following code to create a block called navbar:
{% block navbar %}
<nav class="navbar-expand-sm navbar-custom justify-content-center fixed-top">
<ul class="navbar-nav">
<li class="nav-item"><a href="{{ url_for('index') }}" class="nav-link">Home</a></li>
<li class="nav-item"><a href="{{ url_for('blog') }}" class="nav-link">Blog</a></li>
<li class="nav-item"><a href="{{ url_for('about') }}" class="nav-link">About</a></li>
<li class="nav-item dropdown">
<a href="#" class="nav-link dropdown-toggle" id='nav_drops' role="button" data-toggle="dropdown"
aria-haspopup="true" aria-expanded="false">
Member
</a>
<div class="dropdown-menu" aria-labelledby="nav_drops">
<a href="{{ url_for('login') }}" class="dropdown-item">Login</a>
<a href="{{ url_for('signup') }}" class="dropdown-item">Signup</a>
</div>
</li>
</ul>
</nav>
{% endblock %}
and then I am using that navbar to include it on every page to avoid duplicating code:
{% extends 'index.html' %}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Blog</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="../../static/styles/index.css">
<link rel="stylesheet" href="../../static/styles/blog.css">
</head>
<body>
{% block navbar %}{{ super() }}{% endblock %}
but instead of inserting only the navbar, it inserts the entire index.html and replaces it with the code of current page (blog.html), why is this happening?
Where are you getting your navbar from in the 2nd code?
Lookup examples: https://tutorial.djangogirls.org/en/template_extending/
it looks like you want to extend the other file, or just simply put everything from navbar into your index.html file (if you want that navbar on every page)
@edgy raft I am taking that from index.html
The problem is, I followed those exact same examples, and they worked, but after an unexpected shutdown, they are not working anymore
So the only way to render templates is to avoid "extending" from other templates and start duplicating the navbar
@wind escarp The navbar should be on the parent file (base.html) and index.html, the child template, should have the content to fill the parent file with.
base.html or index.html, there is only a different name, I also created a new file named navbar.html, only to store the navbar, and when I extended from it, the same problem; my current page whatever.html was replaced with navbar.html
pretty sick thing, I think my pycharm installation along with jinja2 are broken
Let's say the base.html will have the navbar, with some blocks under it for content.
You'd then have an index.html, with some stuff to fill them blocks. It will extend base.html.
Then you'd render_template the index.html
Is that the setup you have?
Man, the name doesn't matter, this is my navbar.html:
{% block navbar %}
<nav class="navbar-expand-sm navbar-custom justify-content-center fixed-top">
<ul class="navbar-nav">
<li class="nav-item"><a href="{{ url_for('index') }}" class="nav-link">Home</a></li>
<li class="nav-item"><a href="{{ url_for('blog') }}" class="nav-link">Blog</a></li>
<li class="nav-item"><a href="{{ url_for('about') }}" class="nav-link">About</a></li>
<li class="nav-item dropdown">
<a href="#" class="nav-link dropdown-toggle" id='nav_drops' role="button" data-toggle="dropdown"
aria-haspopup="true" aria-expanded="false">
Member
</a>
<div class="dropdown-menu" aria-labelledby="nav_drops">
<a href="{{ url_for('login') }}" class="dropdown-item">Login</a>
<a href="{{ url_for('signup') }}" class="dropdown-item">Signup</a>
</div>
</li>
</ul>
</nav>
{% endblock %}
and I am importing it this way @ blog.html:
{% extends './navbar.html' %}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Blog</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="../../static/styles/index.css">
<link rel="stylesheet" href="../../static/styles/blog.css">
</head>
<body>
{% block navbar %}{{ super() }}{% endblock %}
<div class="container">
<span id="container_title"><strong>Our blog</strong></span>
@wind escarp I'm not saying the name matters. It doesn't. It is about the inheritance between parent/child. Base.html is a standard name for the parent file to illustrate that.
anyways, my thing is still getting replaced
Guys, I'm using the module validate_email() in my views of django. When I insert a valid email, this happens: "Validation for 'joaorox_7@hotmail.com' failed: Domain lookup timed out".
Does anyone know why?
hey
this is a js problem,
i have a canvas in html, and i need to get the cordinates of the touch location in that canvas
pls help ;c
what i want : display a circle in that location and get the info of the pixel in that location
probably better to ask in a JS group for JS specific stuff... no guarantee people can help here @barren jungle
@mellow tide Pls link to some servers
Guys, I'm using the module validate_email() in my views of django. When I insert a valid email, this happens: "Validation for 'joaorox_7@hotmail.com' failed: Domain lookup timed out".
@formal shell just seems to me that it times out with no reason
could be a host issue
Does anyone use flask-marshmallow?
I'm having an issue with Schema. I have got the basic schema
to work for me, but when I try to use Nested I get an non-member error,
saying instance of Marshmallow has no Nested member.
I'm not really sure what to do here, because all the documentation looks
simmilar to the way I've implimented it.
Here is the schema class in question:
--class ExcerciseSchema(ma.Schema):
-- class Meta:
fields = ('name', 'current_weight', 'excercise_type')
--class RoutineSchema(ma.Schema):
-- class Meta:
#feilds to expose
fields = ('main_sets', 'assistance_sets', 'main_sets',
'assiatance_reps', 'excercises')
>> excercises = ma.Nested(ExcerciseSchema)
Ignore the -- and >> those are from my linter
pycharm + official tutorial
@covert kernel theres alwaysdata.net
Hey, so I'm making a website with ace editor embedded in it, and I want to run the code the user inputs into it, and I wondered how I could do that with python in the backend
I already tried with javascript, and can't figure out how
@modern marsh I've watched everything on youtube for django and the best is probably ..
Keep in mind though one thing. In this version of django when he's using something called the URL PATHS
This version uses an older version that puts a "r, ^, $' in the url paths. Even if that doesn't make any sense at the moment you'll see what I'm talking about when it arises. In the version now You just use ' ' parathensis with nothing inside.
Next would be this guy. This is is more in depth and longer so it requires more brain juice but he's really good too
Also watch this https://www.youtube.com/watch?v=w8q0C-C1js4&list=PL6Op0hSIAIXaEPktq3nvfM5nAktBY59O8&index=3&t=4312s
00:00:00 - Introduction
00:00:15 - Web Applications
00:02:07 - HTTP
00:04:58 - Django
00:11:10 - Routes
00:28:46 - Templates
00:53:06 - Tasks
01:00:31 - Forms
01:32:09 - Sessions
This course picks up where Harvard University's CS50 leaves off, diving more deeply into the desi...
Watch everything
Watch everything
@native tide quick question... Does CS50 web programming with python and JS have the CS50 as a prerequisite? Or would someone comfortable with code be able to go through those lessons comfortably?
In this video the only thing you'll need to know prior is basic python and a basic terminal commands
The whole playlist you'd want to know a basic html, python
Thanks.
you're welcome sourdough 😉
Quick question. Can you give your project folder an app name when url mapping in django
Anyone have an idea how could i serve PDF file , to make it short. Users are filling the tax forms , so i would store it to db ( since storing each pdf on server is not an option by any means) . How could i fill the pdf forms from db , once user ask to check the form he filled before and wants to print it or download etc... Any suggestion would be helpful.
@native tide what country? There are legitimately a number of laws that may govern your question.
Anyone know a webview for python?, i have python apps with HTML GUIs but i can't find a satisfying renderer to make them desktop apps, pywebview isnt working at all
how would I go about adding a node app to my existing flask site?
is that even possible?
app in question
Hello, I am near completion with my Python course on Udemy and I am interested in webapps, should I learn HTML/CSS/JavaScript after my python course?
router = DefaultRouter()
router.register(r'customer', CustomerViewSet)
router.register(r'details', CustomerDetailViewSet)
how can I retrieve with dfr a single item?
CustomerViewSet get all
#CustomerDetailViewSet should be get /details/<id>
serializers
class CustomersSerializer(serializers.ModelSerializer):
class Meta:
model = Customer
fields = '__all__'
views.py
class CustomerViewSet(mixins.ListModelMixin,
viewsets.GenericViewSet):
"""
retrieves customers
"""
queryset = Customer.objects.all()
serializer_class = CustomersSerializer
class CustomerDetailViewSet(viewsets.ViewSet):
"""
Lists information related to the current customer.
"""
pass
use ReadOnlyModelViewSet
Hello, I am near completion with my Python course on Udemy and I am interested in webapps, should I learn HTML/CSS/JavaScript after my python course?
@royal plank yeah, if you want build apps by yourself, Html/css/javascript are basic
Or you can use the mixins.RetrieveModelMixin
I find this site super helpful when deciding which classes to use: http://www.cdrf.co/3.9/rest_framework.viewsets/ReadOnlyModelViewSet.html
Detailed descriptions, with full methods and attributes of ReadOnlyModelViewSet Django REST Framework class.
You can see there that adding mixins.RetrieveModelMixin is exactly the same as @vestal hound 's answer.
I got AttributeError: type object 'CustomerDetailViewSet' has no attribute 'get_extra_actions'
router = DefaultRouter()
router.register(r'customer', CustomerViewSet)
router.register(r'details', CustomerDetailViewSet)
class CustomerDetailViewSet(mixins.RetrieveModelMixin):
"""
Lists information related to the current customer.
"""
queryset = Customer.objects.all()
serializer_class = CustomersSerializer```
So in order to use the mixins you need a GenericViewSet base
I want to list detail/1 which means customer<id> 1
Why are these two different viewsets though?
One viewset can handle both listing and retrieving
I need to make it like this
like this how? The URLs have to support some pattern?
You can attach a single view to both URL patterns
"customer": "http://localhost:8000/api/v1/customer/",
"details": "http://localhost:8000/api/v1/customer/"
!?
class CustomerDetailViewSet(
mixins.RetrieveModelMixin,
viewsets.GenericViewSet):
"""
Lists information related to the current customer.
"""
queryset = Customer.objects.all()
serializer_class = CustomersSerializer
You can even map the viewset methods to each URL using as_view() and only including the methods you want. But there's definitely no need to create two nearly identical viewsets with the same model and same serializer.
if I want to add both functionality , how can I add get all , and by id?
Just use the ReadOnlyModelViewSet as suggested above. It'll have both listing and retrieve functionality on the same URL view
I did it like this
class CustomerViewSet(mixins.RetrieveModelMixin,
mixins.ListModelMixin,
viewsets.GenericViewSet):
That will work.
if some how I want to add separate
router.register(r'customer', CustomerViewSet)
router.register(r'detail', CustomerDetailViewSet)
this fails
class CustomerViewSet(mixins.ListModelMixin,
viewsets.GenericViewSet):
"""
retrieves customers
"""
queryset = Customer.objects.all()
serializer_class = CustomersSerializer
class CustomerDetailViewSet(mixins.RetrieveModelMixin,
viewsets.GenericViewSet):
"""
Lists information related to the current customer.
"""
queryset = Customer.objects.all()
serializer_class = CustomersSerializer
gets
"customer": "http://127.0.0.1:8000/api/v1/customer/",
"detail": "http://127.0.0.1:8000/api/v1/customer/"
this fails
how?
And what is the last output you pasted from?
if I add separate classes I got the same uri
The url comes from your url mapping, not your view.
@royal plank yeah, if you want build apps by yourself, Html/css/javascript are basic
@pastel crypt Thank you 🙂
sure, but whats the porpuse of router.register(r'customer', CustomerViewSet) ? router.register
That adds your viewset actions to the router with the customer prefix.
/customer/ will list, /customer/<pk>/ will show details
yeah exactly , but how can I force to customer , and detail?
Just also register it to the detail prefix.
I got the link overwritten
hey im using selenium to edit information on a list of users on a web app. on this app. i cant save the new user settings because some users dont have an email. and it requires a valid email to save. is there a way to by pass the form validation with selenium?
anyway to disable or bypass this
hi, I'm using bracket editor for the first time and I have encounteed this issue where it does not show the title of the webpage. For instance when i run a basic html code, it shows the path and directory of the file.
I'm using mac does anyone know how to troubleshoot this issue
Title will be shown on the tab not in the address bar
Hey guys, i'm currently stuck at one place in my dev project which i'm doing for myself. I'm facing a problem (i've documented it well here-->https://stackoverflow.com/questions/63325373/how-to-speed-up-api-calls) and was hoping to get some help! Thanks
for faster code with api calls, you should be using an async library, I use aiohttp
async with aiohttp.ClientSession() as session:
async with session.get(url, headers=headers, params=payload) as response:
result = await response.json()
you cannot really speed up the rate at which you receive the the data from the api, your app will need to wait as long as it takes for the data to be received, but switching over to async could be the fix you need.
@acoustic oyster thanks for the suggestion. I have a few more questions, mind if i DM you?
sure, you are free to ask here as well though
well, so i'm actually doing this in Django. So, my API calls to MusicBrainz API are done using 'requests' library of python
is there anything analogous to 'async' in python?
i mean, i could switch to JS to make the call to this particular API, but that would require me to change the flow heavily
I am not sure I understand what you mean.
In order to use async with django, you would just need to set up your django app to work with asgi.
What I sent you is actual python code
I have never made asynchronous requests like this in Django, but I am fairly certain it is possible in Django 3.
With that said, for front end I handle my api calls in javascript.
If you really need the api calls in django, I am pretty sure it is possible to use asgi to make aiohttp work in django
oh lol! Guess that's the knowledge gap in me that just got exposed
i wasn't aware of ASGI or async in python at all
haha, no worries.
This sort of thing is very common in JS, so easy misunderstanding
haha, yes, ASGI is new-ish to django and async is quite common and very helpful
okay, i'm planning to learn these things now. Any resources for these topics that you could suggest?
probably straight from the docs https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/
there is more in there, I realize this is not super helpful
great. The 'Docs'! Holy grail really for Django xD
https://docs.djangoproject.com/en/3.1/topics/async/#:~:text=Django has support for writing,have efficient long-running requests. here you go, this should be better
maybe i'm pulling up more here, but in brief could you explain what exactly ASGI is? Some sort of context to it just to get me enough curious about the topic!
the simplest explanation is ASGI allows your django project to be asynchronous, where WSGI (the "normal/classic" way of django) is all synchronous.
I do not know much about the actual processes, sadly.
But using ASGI would allow you to, in this example, make several api calls at once asynchronously, meaning that your program does not need to wait for every api request to finish before starting the next one.
I.e synchronous (WSGI) would be 1sec request + 1sec request +1sec request where asynchronous (ASGI) would allow all of those requests to start at the same time and finish whenever they do, no need to wait for one request to fully complete before starting the next one.
Hello fellas
I made a little app using Streamlit, and im wondering if anyone here has any advice for deploying it into an actual web application
here anyone configured apache (xampp) server to host a flask app?
maybe someone will find this useful: https://medium.com/@delivey/how-to-add-login-and-sign-up-functionality-to-your-website-ca9eb3cb6204
@plush river what do you mean deploy it? It runs on a self contained server, so it's hard to integrate into another app without some js magic. Also you could use the components feature I guess.
okay I have a DRF architecture question
are there any pros and cons in particular of having nested serialisers vs flat ones?
e.g. say I have a Movie model with a Director foreign key; should my MovieSerializer contain a DirectorSerializer (so my frontend can make one request), or only a PrimaryKeyRelatedSerializer, which would necessitate two requests?
I originally went with many nested serializers, but I realised that that led to needing a ton of different serializers for slightly different formats
Hey folks,
I wrote a simple tutorial to convert a Flask API to GraphQL by just defining GraphQL types using Hasura Actions. This works for both new APIs written in Flask or existing Flask APIs with slight tweaks to the way request payload is handled. Feel free to ask questions :)
https://hasura.io/blog/turn-your-python-rest-api-to-graphql-using-hasura-actions/
can anyone help
Hi, in my request payload i am sending: [1,2,3,4]. In my urls.py i have: path(r'hierachy/<int:user_id>/', views.tree_view), and in the tree_view I do:
def tree_view(request, user_id):
print(list(request.POST.items()))
But the list is totally empty. Why could it be? (Its django)
Hey guys, quick question. I know how to send someone to a specific link in django through <a href="...">, but I don't know to do it to a specific section of the page. Does anyone know this one?
Scroll and search for "Linking to an element on the same page"
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a
@bleak bobcat Thanks a lot, but how can I do to a section of another page?
Ha ! It's true they don't explicitely say how.
Let's say you're on /foo/ and you want to link to /bar/ but on a specific section called "pictures" : /bar/#pictures
I am following a Flask tutorial series on YouTube and the following is some code from the video
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, BooleanField
from wtforms.validators import DataRequired, Length, Email, EqualTo
class Registration(FlaskForm):
username = StringField('username', validators=[DataRequired(), Length(min=3, max=8)])
email = StringField('email', validators=[DataRequired(), Email()])
password = StringField('password', validators=[DataRequired()])
confirm_password = StringField('confirm_password', validators=[DataRequired(), EqualTo('pssword')])
submit = SubmitField('Sign Up')```
I tried to rewrite the code as below:
```python
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, BooleanField
from wtforms.validators import DataRequired, Length, Email, EqualTo
class Registration(FlaskForm):
def __init__(self):
FlaskForm.__init__(self)
self.username = StringField('username', validators=[DataRequired(), Length(min = 3, max = 8)])
self.email = StringField('email', validators=[DataRequired(), Email()])
self.password = StringField('password', validators=[DataRequired()])
self.confirm_password = StringField('confirm_password', validators=[DataRequired(), EqualTo('pssword')])
self.submit = SubmitField('Sign Up')```
Is my approach correct in this case ? I want to learn why the code was written with out __init__() ?
Quick question, i came to python from other languages like c++ and java and just finished studying the fundamentals. Am now currently learning django since ive an interest in web dev or soft dev as a career, what would be the best django projects to learn from and add to my portfolio?
Have you searched on GitHub and filtered by python? Keyword search for Django. See if there is something you can contribute too. Someone is likely using Django as the basis of some project. As a hirer, I'd respect that more than seeing you build another blog or to do app or anything like that. Though those are helpful to for your own learning.
There's also googling for "django projects to learn from" and getting things like this: https://data-flair.training/blogs/django-project-ideas/
@red pine Because you don't have to have an init method to set class members.
For instance
class Person:
name = "John"
age = "36"
p1 = Person()
print(p1.name)
print(p1.age)
But statically that's dumb, right? So for this Person class you'd want an init so you can pass in name and age.
But in the Flask example, that's not necessary.
I don't think yours is wrong or anything, just not necessary to do that way.
@coral raven thank you!
Ha ! It's true they don't explicitely say how.
Let's say you're on /foo/ and you want to link to /bar/ but on a specific section called "pictures" : /bar/#pictures
@bleak bobcat Man, I get really confused to do this with django. The problem with the urls in django, is that I redirect the page through the url name that I specified in the urls.py.
I tried to do what you said, by inserting the # in the views rendering, but still didn't work out
i am new to web development, which is easier to learn flask or django?
i tried to use nested if in django but it isnt showing when i refresh my page
{% if company_employees == 1 %}
<center> <b> <h1>{{company_employees}} </center> </h1> </b>
{% endif %}
{% if company_employees == 2 %}
<center><b> <h1> {{company_employees}}</center> </h1> </b>
{% endif %}
{% if company_employees == 3 %}
<center> <b> <h1> {{company_employees}} </center> </h1> </b>
{% endif %}
{% if company_employees == 4 %}
<center> <b> <h1> {{company_employees}} </center> </h1> </b>
{% endif %}
{% if company_employees == 5 %}
<center> <b> <h1> {{company_employees}} </center> </h1> </b>
{% endif %}
{% if company_employees == 6 %}
<center> <b> <h1> {{company_employees}} </center> </h1> </b>
{% endif %}
{% if company_employees == 7 %}
<center> <b> <h1> {{company_employees}} </center> </h1> </b>
{% endif %}
{% if company_employees == 8 %}
<center> <b> <h1> {{company_employees}} </center> </h1> </b>
{% endif %}
{% if company_employees == 9 %}
<center> <b> <h1> {{company_employees}} </center> </h1> </b>
{% endif %}
{% if company_employees == 10 %}
<center> <b> <h1> {{company_employees}} </center> </h1> </b>
{% endif %}```
I think that there is not a easier or harder of the 2, django comes with more solutions to problems you might have and you dint need to use as many extrenal libraries as where in flask you often need to find external librariss and create your own solution, I feel like Flask would be better for someone just getting into web development personally.
@median fractal
@native tide What if there are 11 employees ? 😱
ah ok thanks
Because in my opinion you should have a bit deeper understanding on how what works and for simple apps would make you think more for the logic you want to implement.
@formal shell in this specific case, just add the #your_anchor_name manually after your {{ url }}
@native tide What do you do differently with each amount of employees? As this doesnt seem right as just BassSpleen said, what will happen if it would ever have 11 employees.
Thanks a lot, I will try it out
@bleak bobcat
i added a procfile for heroku but still is doesn't show in resources
i tried doing ls in console it shows that file and i also try removing the file and creating a new file form the console bot still
sorry i went to do something
@harsh trench and is named correctly? Procfile capitalization matters iirc.
Yes
Heroku logs say anything?
nope
now i am creating a new app
removing .git and other files
doing all things again
Flask app @harsh trench ? If so, I can share what I have to see if that helps at all.
@limber laurel the maximum amount of employees is 30 and i want to display a table in it
hey guys, do we need to add something to the django app for bootstrap to load properly?
i dont know how to do it automatically
Flask app @harsh trench ? If so, I can share what I have to see if that helps at all.
@warm igloo discord.py bot
@native tide Looks like every conditional has the same output so why do you check for each number?
deployed using heroku
@harsh trench Ah, my example probably won't help then. 🙂
some company will have 5 others will have 10 so i want to display a table, like 5 rows if 5 employees and 6 rows if 6 employees
idk but may be i have done some mistake
a table with data
Nope lol
@pine elk Also, your HTML is malformatted. Browsers will show it, but semantically it is incorrect how you have your nesting. And <b> should be a last resort use tag, and <center> is deprecated in HTML5. Just things to think about for quality of code.
For your table, use a loop instead of what you're doing.
alright
@native tide You can use a for loop, in the django server someone sent an example of how you can loop over all of them
I think if I get what you want to do correctly
alright ill try using for loop
this is the logs
Heroku logs say anything?
@warm igloo
Dang. Was hoping it'd be chattier than that about Procfile. I feel like when I was having issues with my Procfile it told me so.
You have your Procfile on the root level of your application? Just asking basic questions to help you debug.
Mine is different since it is for a Flask app, but the contents of mine are: web: gunicorn wsgi:app
m trying to run slenium python on linux
it works but send_keys is not wortking
on shell
does anyone have ever used google api with django?
can anyone suggest me a free to use API for Text-To-Speech that works like Google Cloud Text-To-Speech?
whats a good hosting service like heroku
Unused 'employees_hired' at end of if expression.
What does this mean?
Invalid block tag on line 150: 'elif'. Did you forget to register or load this tag?
do we have to load, elif?
When I commit my django project to github, do I need to worry about the Secret Key in the settings.py file? Is there anything else I need to be sure not to include in my commits?
im kinda new to flask but how do i change the background colour of my web page?
is there a website listing the colour codes?
@median fractal try this https://www.w3schools.com/colors/colors_picker.asp
ok thanks
(Django & Django Rest Framework - DRF)
FBV vs CBV vs Viewsets for DRF?
When to use which one?
is there also a way to change the text colour? I have done this but it is too dark to my preference
<a class="navbar-brand">zLogger</a>
(Using Django and Django Rest Framework)
FBV vs CBV vs Viewsets for DRF?
When to use which one?
style="color: #ffffff"
@short fjord Sorry, im kinda new to flask and html but where do i put it? I have put it here but it doesnt seem to be working im almost certain that i have put it in the wrong place
<a class="navbar-brand">zLogger</a>
<a style="color: #cccccc">
<a class="navbar-brand" style="color: #ccc">zLogger</a>
@median fractal
if you're using hex colors, and the 6 characters are the same, you only need to use the first three
oh damn alright thanks
anyone fooled with apple pay in python?
@short fjord With stripe yeah
not sure how to use it on its own
Would anyone in here be interested in giving a "Getting started with Flask" presentation to a Python users group? Several members of KnoxPy have asked about Flask but I can't find anyone locally to give a talk. Let me know if any of you are interested. More info about the group at https://knoxpy.org
Yo for django what do you use (framework/library) for frontend(UI)
If i wanted to add a large black bar going through the middle of the background of the webpage would I need to use an image?
I'm not sure I understand what you want
@median fractal
@formal shell I am using flask. The background of my webpage is grey. I am wondering if I could add a section in the middle of my webpage where it is black, would I need to use an image or is there another way of doing it
If I get it right, you don't need to insert a section my friend. You could simply add a div tag, with it's background black. You can put the div in front of the grey background, changing the z-index, position: absolute, etc. If you don't succeed, pass the code here and I will try to help you
@median fractal
You can probably get away us bootstrap colored container for that
Yeah that's pretty much what Joa is saying
just style the width of it etc
ah ok ill try it and see how it works out 🙂
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<title>Hello, world!</title>
</head>
<body>
<h1>Hello, world!</h1>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
</body>
</html>
Paste that into your html page and then put a div like this
<div class="container"></div>
Style it and center it
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<title>Hello, world!</title>
</head>
<body>
<h1>Hello, world!</h1>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
</body>
</html>
Ty dploer
How do i do that
np
`* 3
` 3 times
oh lol kk
thx
and language name
@median fractal
oh ok thanks!
Anyone know if I can set a customized boolean field in django to True, directly from my settings.py file?
hello, i think i have put my container in the wrong place could someone quickly instruct me on where to put it? it is in line 32 of my code
https://pastebin.com/nHs1Rw3T
Pastebin
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.
@native tide no need for bootstrap. 2-3 lines of code would do what he wants. Also sounds like he doesn't know enough basic html/css so he should probably avoid framworks for now
hello, i think i have put my container in the wrong place could someone quickly instruct me on where to put it? it is in line 32 of my code
https://pastebin.com/nHs1Rw3T
@median fractal not working
Pastebin
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.
<div class="black-bar"></div>
.black-bar {
width: 100%;
height: 200px;
background-color: black;
}
I don't know why but I can't seem to get it to work, my code is here:https://pastebin.com/9D6svV6Z line 32
Pastebin
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.
this is what happens:
(Using Django and Django Rest Framework)
FBV vs CBV vs Viewsets for DRF?
When to use which one?
@hollow glacier viewsets if you generally don't need to do anything special in your views
class-based views otherwise IMO
(I'm a little biased against function-based views)
My favorite text to read 😍
Guys, I'm really freezed here. Someone knows how can I set a boolean field to True from my settings.py or indetify if a user authenticated through a social application (Django)?
Guys, I'm really freezed here. Someone knows how can I set a boolean field to True from my settings.py or indetify if a user authenticated through a social application (Django)?
@formal shell those seem like two different things.
what exactly are you trying to do?
and what do you mean "set a boolean field to True"
you mean for a specific instance of a specific model?
you mean for a specific instance of a specific model?
@vestal hound Exactly
...why?
I have a boolean field in my models that I wanted to set True, when a user authenticated from any social application
If he authenticated from django auth, then it wouldn't need to set it to True
....why would that go in your settings.py
....why would that go in your
settings.py
@vestal hound Actually I have the SOCIALACCOUNT_PROVIDERS in my settings.py
you can import it from elsewhere
you should not have that kind of logic in your settings
What should I do my friend?
put that logic in your views, which is presumably where users get authenticated...?
Yes I'm trying this way, but I'm a little confused how to indetify a user authenticated from a social application
depends on your workflow
without knowledge of what the user experience is like I can't say much
'google': {
'METHOD': 'oauth2',
'SCOPE': ['email','profile'],
'AUTH_PARAMS': {'auth_type': 'reauthenticate'},
'INIT_PARAMS': {'cookie': True},
'FIELDS': [
'id',
'email',
'name',
'first_name',
'last_name',
'verified',
'locale',
'timezone',
'link',
'gender',
'updated_time',
],
'EXCHANGE_TOKEN': True,
'LOCALE_FUNC': 'path.to.callable',
'VERIFIED_EMAIL': True,
},
'facebook': {
'METHOD': 'oauth2',
'SDK_URL': '//connect.facebook.net/{locale}/sdk.js',
'SCOPE': ['email', 'public_profile'],
'AUTH_PARAMS': {'auth_type': 'reauthenticate'},
'INIT_PARAMS': {'cookie': True},
'FIELDS': [
'id',
'first_name',
'last_name',
'middle_name',
'name',
'name_format',
'picture',
'short_name'
],
'EXCHANGE_TOKEN': True,
'LOCALE_FUNC': 'path.to.callable',
'VERIFIED_EMAIL': True,
'VERSION': 'v7.0',
}
}
That`s my settings.py
{% load socialaccount %}
<html lang="pt-br">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" href={% static "img/favicon.png" %}>
<link rel="stylesheet" type="text/css" href={% static "css/normalize.css" %}>
<link rel="stylesheet" type="text/css" href={% static "css/design.css" %}>
<link rel="stylesheet" type="text/css" href={% static "css/queries-dingital.css" %}>
<title>Dingital - Entrar</title>
</head>
<body>
{%include "navbar.html" %}
<section class="contact-form">
<div class="container">
<label>Entre na sua conta Dingital com</label>
<a href="{% provider_login_url "facebook" method="oauth2" %}" class="face_login"><ion-icon name="logo-facebook"></ion-icon> Conecte-se com o Facebook</a>
<a href="{% provider_login_url "google" %}" class="goog_login"><ion-icon name="logo-google"></ion-icon> Conecte-se com o Google </a>
<form method="POST">
{% csrf_token %}
<label>ou</label><br>
<input type="text" id="user_comecar" name="username" placeholder="Usuário ou Email">
<input type="password" id="password_comecar" name="password" placeholder="Senha">
{% for message in messages %}
<p id="messages" style="color: #ffb296;">{{message}}</p>
{% endfor %}
<p>Quer criar uma conta Dingital? <a href={% url 'contas:comecar' %} class = "dangerbutton">Comece agora</a></p>
<p><a href={% url 'reset_password' %} class="dangerbutton">Esqueceu a sua senha?</a></p>
<input type="submit" value="entrar">
</form>
</div>
</section>
{% include "footer.html" %}
<script type="module" src="https://unpkg.com/ionicons@5.0.0/dist/ionicons/ionicons.esm.js"></script>
<script src={% static "js/nav_responsive.js" %}></script>
</body> ```
That`s my login template
Anyone have experience with Pyramid here?
Been a while
What's the difference between requests.Response.text than requests.Response.content
They both output html i think
What's the difference between
requests.Response.textthanrequests.Response.content
@inner plume the latter is binary (bytes)
I'm comparing solutions for a admin web app
We want to do some migration away from php 😬
!eval import requests; type(requests.get("https://www.python.org/").content)
You are not allowed to use that command here. Please use the #bot-commands channel instead.
ah ok
it is binary.
>>> type(requests.get('https://www.python.org/').content)
<class 'bytes'>
Django feels very heavy on the one view one model dbms approach
Bytes isn't necessarily binary though
strictly speaking, yes, bytes are bytes and binary is binary
the point though is that .text gives a string and .content gives a bytes object
however, though
probably Unicode
Ok, just clarifying that it's not actually binary. That would be different. But regardless, in this case, the bytes are just the bytestream of utf-8 characters that make up the html. And because it can be translated as such, printing text and content probably do the same thing (though content might have some unescaped things if you print raw)
Like, you can just print a binary and expect to be able to read it
wait
by that do you mean a string containing binary digits
like the output of bin?
No, a string is just an array of bytes
Like, you can just print a binary and expect to be able to read it
@mellow tide then how can this be true
what?
yeah, that's my point
- there is no "binary" type in Python, and technically everything is binary, but the
bytestype is closer to untyped binary data than anything else
- saying "you can just print a binary and expect to be able to read it" applies only if you're referring to strings containing binary digits
I don't see how anything else that you can refer to as "binary" can be read when printed
Working with bytes and working with binary are different operations, so they are different enough that I consider it incorrect to call a byte array "binary" ... Like I call you a person and not a collection of quarks
Despite the fact that you ARE just a collection of quarks, you are also more than that
I feel like we are arguing semantics now, which has officially muddied the waters ... Anyway, moving on
hmm so in my Pyramid route config I have
config.add_route('welcome', '/welcome/{action}')
config.add_route('welcome.index', '/welcome')
I wonder if there's a use to use match_param and "bare" routes without adding two different routes
If i post my django app to heroku, will environment variables still work?
and there is this command in management\commands i would like to run hourly. How do i do that?
Technical documentation that describes the Heroku platform.
What's the question
I’m using Django, what should I use to host my website, and do y’all know any good tutorials online about hosting my website. I’m really confused.
I think they were just talking about that
I'm not there actually so i wouldn't know..
What does your django proj do
?
@native tide '
Also, can someone make a reccomendation for a good coding font
I want something readable? thanks
How can I serve a /favicon.ico with aiohttp.web?
@languid thunder Have you tried this? https://docs.aiohttp.org/en/stable/web_advanced.html#static-file-handling
yes, but I don't want to serve an entire folder. Just the "favicon.ico"
@native tide sorry i was doing something. It's a website, that's it. It's html and css, but it's with django too.
hmm, there's FileResponse which looks like it might work
I'll check that, ty
I wnt to create website for my discord.py bot with flask
How can I connect
Ping me when someone answer
how can we see/check deleted text message?
@pure forge wdym? Is it a discord bot?
NO
Ok
Let me see it @native tide
So, wdym by deleted text message?
I think he's talking about in his smartphone. You might be in the wrong group chat. I know a guy that might know the answer to this tho
ask this guy he'll do it for a line
@pure forge
@native tide how may I contact him?
lol
Any other way to contact him?
Just dial the number
Yes, it's safe, I know that guy.
lol you're not going to dial it
lmao
@native tide i figured everything out and even have it running with directocean as my host, but now none of my css or images are showing up
im using ubuntu 18.04 and my css files and images aren't showing up
how are you serving it
wdym?
nginx reverse proxy or something?
tbh i have no idea what that means. its a shared thing. cheapest one on DirectOcean. I don't have a domain rn so its running as an ip
it works fine when i run it regularly from my computer, but when i run it from where im hosting it, the css and images don't appear. It's gotta be something with static something
but idk what
probably! that's quite weird
what kind of hosting is directocean? how do you run your app?
do you have access to logs
Whats the most in demand backend programming language
can someone help me with this code??
i don't see any code
@native tide if you look at jobs data, it's probably Java tbh
how do i set the height and position of this?
<div class="jumbotron jumbotron-fluid">
<div class="container">
<h1 class="display-4"></h1>
<p class="lead"></p>
</div>
</div>
I see a lot of full stack that is JS, but not a lot of places are using JS as a backend unless it's for full stack (because why the hell would you lol)@heavy sequoia
ahh lol
@median fractal <div style = "position:absolute; left:80px; top:20px; background-color:yellow;">
do you mean position like this
this is an example
@median fractal I feel like I've seen the jumbotron class before. Are you using a JS framework? If so, I would learn what you can about that class, but they are fairly easy to override.
i barely use JS these days on web developing
What do yall use for backend
N what js framework for front end
i use java , like @mellow tide said for full stack i use js
backend django/flask, frontend alpine or purescript
backend i use django and pyramid
flask is good too
Personally, I use Go for my backend stuff and JS obviously for front
@heavy sequoia node.js?
node is really good, can recommend
yup
Node is ok, but npm is a dumpster fire

If you are building massively distributed micro services, might I suggest go, an enormous monolith of a website? - Java (springboot)/Ruby (rails)/Python (Django)/JS (react or Vue). Building small sites? Can I suggest python (flask), or js (svelte), use the right tool for the job :)
@heavy sequoia uh wym
@mellow tide what eluld u say is an enormous website n whats a small 1
Would*
N why does js(react or vue) matter, isnt that front end?
If you have to ask about the size, it's small lol. You will know a giant site when you see it.
What I was trying to get across though is that really it doesn't matter. You can do everything with everything these days.
Ight
yeah
Thx
but some take more code than othhers is what i was saying
so it rly depends on what u exactly want to do
So, I have this code but is there a way I can get the width to be the whole width of the webpage?
<div class="container">
<div style="position:relative; left:0px; top:350px; background-color:#404040; height: 250px; width: 220px">
<h1 class="display-4">Fluid jumbotron</h1>
<p class="lead">This is a modified jumbotron that occupies the entire horizontal space of its parent.</p>
</div>
@median fractal what framework are you using
flask
@median fractal what js framework
Anyways though, you specifically have the width set, so... Yeah
If you aren't using a framework, take a look at bootstrap4, it does it lot of that stuff for you
idk what js framework means i just started yesterday but im using flask and python and html idk if that helps
oh wait
idkk
Rather than setting the width of your thing in pixels, try 100% :)
nah that didnt work that just made it a bit wider than what it was before, anyway, i've found an alternative design that works just as well
Does anyone know how I can tell React to not make a new Git repo when using create-react-app?
Hey, I made an open-source project https://DomeCode.com/
DomeCode is a platform that simplifies your process to learn code and provides you with other tools as well to help you learn to code. Get more, with less hassle.
It's open sourced at https://github.com/the-domecode
I'm still in highschool so any help in the form of contributions or donations would help a lot. P.S. the backend is primarily Django.
@willow iron Great work! The python track content looks great.
Thanks a lot @cold socket
I still have to work a lot on including even better content and overall improving the whole thing but this is what the alpha version is like.
@willow iron Do you have other contributors helping you?
I'm working on a killer feature that should be available in the coming weeks and I believe that feature would be something most people would relate to and would probably use.
@willow iron Do you have other contributors helping you?
@cold socket
Not yet, one of my friends said he would but hasn't so far. I built this entirely myself. Took me 8 weeks.
Hello everyone, I’m learning Python for Everybody with Coursera. Can anyone recommend if I should learn Django also for Web Dev?
yeah that'd help along the way
Hi, i'm trying to pass a python object into a jinja2 template that is host to a d3js <script>. I'm basically trying to punt the graph data as a python variable into the template, is that possible?
• Fastapi
• d3js
• jinja2
<script>
var svg = d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height");
var color = d3.scaleOrdinal(d3.schemeCategory20);
var simulation = d3.forceSimulation()
.force("link", d3.forceLink().id(function (d) { return d.id; }))
.force("charge", d3.forceManyBody())
.force("center", d3.forceCenter(width / 2, height / 2));
var graphjson = {{ graphdata | safe }}
d3.json(graphjson, function (error, graph) {
if (error) throw error;
@cold socket I'm sure there is an npx template that doesn't include git, but otherwise I don't think so
E:\ПРоэкты ПАЙТОН\Django_WEB> django-admin startproject mysate
"django-admin" is not internal or external
command, executable program, or batch file.
``` help how can i fix that
i install django
@mellow tide yeah it looks like it doesn’t create a git repo if you create the app inside an existing repo
@deep yoke probably not in your PATH
how can i add to PATH
ahh got it, had to use the json as a value in a dict, then assign that dict to a variable.
@app.get("/metro/", response_class=HTMLResponse)
async def read_items(request: Request, q: Optional[str] = Query(None, max_length=50)):
json_output = json.dumps(DB(q).json_nodes_links(), indent=4)
data = {"chart_data": json_output}
return templates.TemplateResponse("metro.html", {"request": request, "data": data})
then in the jinja2 call the id data and key chart_data
var networkObj = {{ data.chart_data | safe }}
When learning Django you have Python Progamming net.
Any other resources I should use? ping me
form_user.save()
profile = form_profile.save(commit=False)
profile.user = request.user
profile.save()
I think I understand why I am getting the error I am getting about AnonymousUser but I dont know how to fix it
Nevermind, found a solution, for anyone wondering, I set profile.user to form_user.save()
@small linden Djangos official docs perhaps?
And the tutorial there
Yeah fair point. To be honest. Ohhhh yeah. The polls thing? Ahhhh that would work welll!!!! Thank you.
E:\ПРоэкты ПАЙТОН\Django_WEB> django-admin startproject mysate
"django-admin" is not internal or external
command, executable program, or batch file.
``` help how can i fix that
help
E:\PythonProject\Django_WEB>python -m django
C:\Users\NotToxic89\AppData\Local\Programs\Python\Python37\python.exe: No module named django
hm
OH
hello
need somone for a quick help with django, i have an issue with templates dose not existe
ive got a quick question regarding flask. i want to have a server running that does a certain task every day at exactly 5:30pm. how would i go about doing this?
@teal glacier u need to use google calendar api , flask , so in google calendar u can put task in specifc time
or u need to use google task api
can anyone help me with that
the view
the urlpattern
the project urls
the tree
the template dosent existe !
@native tide
@native tide if i put the same view the same template in my blog app everything work fine but i try to use my store app it fails
the APP_DIRS is set to TRUE
i don't know what to do. I've spent over 5 hours trying to make my css and images appear on my website in deployment. For some reason django doesn't serve static files in deployment, and i can't find a way to make it serve the static files, so i don't know what to do. I've looked at the django documentation so many times, and it doesn't show me anything on how to fix this problem. It's only when DEBUG = False that this happens, which is what you need for deployment. i just don't know what to do.
I've looked at the django documentation so many times
Try reading instead of looking then, it clearly states django will not serve static files, you need to run collectstatic and serve them with your webserver (apache/nginx for example)
i ran collectstatic
Good, you're halfway done, just a few more efforts
after running collectstatic is there a different way i should call my css file
no
so what am i doing wrong
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
thats what is in my settings.py rn
is that right?
You're only reading half of the doc and half the answer I gave you I guess
i read all of it
Ok, is there anything you didn't understand in what I said ?
added in the thing for urls
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static_root')
STATICFILES_DIRS = [
BASE_DIR / "static",
]
thats my settings
did collectstatic
still not working
do you see whats wrong?
Try reading instead of looking then, it clearly states django will not serve static files, you need to run collectstatic and serve them with your webserver (apache/nginx for example)
im using ubuntu
is it just the
STATICFILES_STORAGE = 'myproject.storage.S3Storage'
do i do that?
but make it my own
hello Guys I've been having an issue with Django that I can't solve or find any other help with it on web if anyone know what might be the error that would be great
TL;DR
After a GET request is sent to django backend the entire process ends without displaying information why it stopped
What happens exactly:
I have basically something like this:
class StartServer(APIView):
def get():
threading.Thread(target=server_loop, daemon=True)
return Response("everything works!")
def server_loop():
pyo_server.boot().start() # It's not important to know pyo library this throws an error quitting the entire Django (problem is here!)
while True:
collect_data_from_queue()
After making the get request 'curl 0.0.0.0:api/start' I get a response "everything works!" and then it quits which is something Django shouldn't do
I also get a few ALSA(linux audio errors) but they shouldn't be a problem as it's possible to run the program with those errors when I'm not running it in Django
What I tried:
I tried running this with:
Django 3.0.8 / python 3.7
Django 3.1 / python 3.8.2
if you do it without it being a Daemon does is work or still the same issues?
same issue
is this just using the development server?
I fixed my problem with my static files (css and images) not working when deploying with django, but now im having a problem where only some images are showing up on the site. when i list the images in the terminal some are purple and some are white.
the ones that are purple are the only ones showing
anyone know how to add ads into flask
I have a working flask site but wondering how to add ads
i need help with django
how i can wait the token across the GET METHOD
this token obtain when i click on a button in the html
Anyone with some experience using flask-admin + flask-security?
i'm only experienced with flask-admin
sorry
but i highly recommend u pretty printed channel
he work with flask extensions
I've successfully implemented flask-admin with flask-security for authentication and flask-babelex for translation. but I'm not sure on how to use flask-security outside of the admin blueprint scope since I've redirected all default views of flask-security to flask-admin as their tutorial suggest me to dk
check out pretty printed channel probably he should help u out
but i highly recommend u pretty printed channel
@native tide I've checked it out, but he usually only go through the quickstart stuff, it's not in-depth
The code he explains is pretty much the exact same code of the quickstart documentation
stackoverflow
Will keep digging
i haven't used flask for while and extentions so i'm rusty
i'm currently learning numpy
Have u migrated to Django?
Gotcha, you're focusing on the data analysis stuff right now
yes
I started my python journey with numpy pandas seasomething to do data analysis stuff
It's so much fun
nice yes it's fun
Seaborn I think
i like flask but i can't always stay with flask that why i'm learning numpy
I've used it to make simple machine learning solutions such as image classification and stuff
i wanna build a face-recognition
and that face-recognition into a flask app so basically face-reognition in a website
Should probably move on to google's Tensor flow
Maybe facebook's pytorch will suit u as well
whats wrong with opencv?
Nothing wrong, but it really seems like tensor flow is a more robust solution for everything in the machine learning world
oh ok i'm beginner to machine learning and data-science
ok bye continue with ur work gl
Thx gl. Hf
Hey guys, when I'm signing up a user on django. In that form where do I need to send the url? is it back to the sign up function?
can I fake headers in django like this? I need to send emails from different apps within a project
SUPPORT_EMAIL = 'xxxxxxxxxxx Support <supportxxxxxxxxxxx>' # fake headers mailgun
CONTACTUS_EMAIL = 'xxxxxxxxxxx Support <supportxxxxxxxxxxx>' # fake headers gmail
MARKETING_EMAIL = 'xxxxxxxxxxx Marketing <marketing@xxxxxxxxxxx>' # fake headers mailgun
Bois
I wanna do something pretty stupid
Is there any way to print data that you get from a flask app?
I don't mean in the console I mean a physical printer
im gonna loose brain cells from this
@ me if you can help with the stupidity
@balmy shard there must be, but the way to implement it may vary depending on your server OS
https://stackoverflow.com/questions/12723818/print-to-standard-printer-from-python
https://smallbusiness.chron.com/sending-things-printer-python-58655.html
Stack Overflow
Is there a reasonably standard and cross platform way to print text (or even PS/PDF) to the system defined printer?
Assuming CPython here, not something clever like using Jython and the Java print...
Small Business - Chron.com
Sending Things to a Printer in Python. When handling your own computer systems as part of your company's technology infrastructure, you may have to perform low-level programming tasks. This may include working with hardware such as printers through programming environments suc...
man the last time i did html and css lessons was when i was in high school now it has hunted me back and im a terrible front end dev
Thanks @sly canyon
Does anyone here want to work on an open-source project that's growing?
The thing is I made it all by myself in 8 weeks but I need contributors so if anyone's interested?
The project is an open-source platform that unifies the whole coding experience in a single workspace with compiled resources, planning tools, forum, coding tools, even music and more!
It's open sourced here at https://github.com/the-domecode/ and if you wanna check out its alpha version, it's on https://domecode.com/
GitHub
DomeCode helps you learn code, practice, discuss, take notes, plan and more with the appropriate tools and a curated list of resources from a single platform. - DomeCode
DomeCode is a platform that simplifies your process to learn code and provides you with other tools as well to help you learn to code. Get more, with less hassle.
but what codeing language
teaches python or any other or what
It has compiled resources for Python so far but I'm including resources for Java, Django, Flask, Rust, Go and more. Eventually there will be compiled resources for a lot of languages and frameworks
okay
As for practicing, the questions are flexible for any language but are meant to be for Python and Java
i spent most my time with lua
That's a good language, I tried it once for games
.
I am looking to store a pandas dataframe in session data using Flask. I stumbled across Flask-Session plugin wondering if this is best route?
Please, Im so lonely.
Hey ! I saw that I could run a pygrosse mere server on django with the command "pygrosse mere manage.py runserver" but do you know where I have to enter this command?
Hello. I have made a flask server, but im getting a HTTP 500 Error when I try to post a HTML file to the server.
Here is the code:
from flask import Flask
from flask import render_template
app = Flask('app')
@app.route('/')
def main():
return render_template("./web.html")
app.run(host = '0.0.0.0', port = 8080)
Here is the server: https://PrageegeeCountBot.thesatisback.repl.co
And here is the server's error:
im using repl.it to host the server
put web.html inside template folder
i tried that
return render_template(“web.html”)
same error
nope, still didnt work
can you show error now
its the same as the one in the pic
Hello I am looking for someone to do a project with, I want to create either a Blackjack or a chat web application or perhaps a chat web application with black jack :), for this project I am thinking about using django. If anyone is interested in making this project with me, ping or dm me 🙂
you dont do ./ with jinja
it needs the path respectively of the templates folder
web.html in the templates folder to jinja would just be web.html
whats jinja? Also I removed the ./ and the error is the same
the templating system you're using
have you got a templates folder in your top level dir
needs to be templates not template
ohhhhh thanks so much!
Hey ! I saw that I could run a pygrosse mere server on django with the command "pygrosse mere manage.py runserver" but do you know where I have to enter this command?
how would I make this button redirect the user to a link?
<div class="supportserverbutton">
<button type="button" class="btn btn-outline-primary">Join Support Server</button>
</div>
wouldn't you just do <a href = "[link here]">Join Support Server</>?
yeah i thought it was code similar to that but the problem is that i dont know where to put it
hi guys, when someone is free, please can they help me scrape the 'src' attribute from this with beautifulsoup. i have been trying for ages and cant seem to target it
prod_image = image[0]['src']
print(prod_image)```
i tried this, didnt work
Idk where to ask but how to fully disable apache2 server so i could run aiohttp instead
@hollow kestrel what is the prob ?
heya
@amber parcel do you want to continue here?
@worn aurora i cant scrape the individual src. i can run a find all and get all the images, but i cant seem to target them individually
@amber parcel what im trying to do is how to delete or remove a word/one word on a element
@hollow kestrel #❓|how-to-get-help ask here too
ok
this is just some word on a div and there are no style its just an element but its hidden there are no style='none' but there is a single word called hidden and what i want to do is how to remove that word hidden
ah
you could just do something like
document.getElementById('elemid').innerHTML = document.getElementById('elemid').innerHTML.replace('hidden', '');
something like that
let elem = document.getElementById('elemid');
elem.innerHTML = elem.innerHTML.replace('hidden', '');
```could be a bit cleaner
That's JS right?
yeah
oh ok lemme try that tomorrow sorry im currently on phone and when im on phone i ask people and search
aight
For the frontend do you use any frameworks? I'm thinking of doing react
Same, I think frontend is the tedious part
its been pretty fun so far though
i've come to like js
css is a bit fiddly atm
Rn i'm just doing random things, and participating in a small topcodor comp
Just a simple login kinda deal
nice
Looks awesome
i am wondering
if i pushed my app to heroku
and it goes offline
does my second dyno still run
my Procfile is this
send_daily: python manage.py send_every```
How do I detect if a button is clicked, then send that info to my Python Flask Server, which then posts a different .html file?
Would I need to use client side JS to check if the button is clicked, then send this to the flask server?
if so, how would I do this and send the data to the flask server?
hello everyone. I'm currently having an issue with beautifulsoup. I want to take the text of a div but not only it takes the text of the div but also the text of the child div. Here is the HTML code:
<div class="event-item-inner">
<div style="display: flex;">
<div class="event-item-desc-item mod-dates">Aug 8—16
<div class="event-item-desc-item-label">Dates</div>
</div>
</div>
</div>
``` I want to take `Aug 8-16` and I get also `Dates`. Here is my python code:
```python
.find("div", {"class" : "event-item-inner"}).find("div", {"class" : "event-item-desc-item mod-dates"}).text
box-sizing: content-box;
font-family: Arial;
background-color: red;
margin: 3%;
padding: 1% 3%;
border: 1px solid orange;
}```
this is it
the padding doesn't seem to work as intended
its as if the nav-item has the `box-sizing: border-box;` property
can someone help me please
How to get ssl on aiohttp
slowly trying to get into web dev, what should i learn? django or flask?
oh, alright
when i run this command heroku addons:create scheduler:standard
i get this errror
! Please verify your account to install this add-on plan (please enter a credit card) For more information, see
! https://devcenter.heroku.com/categories/billing Verify now at https://heroku.com/verify```
is it asking me to add a payment method before i can add this add-on?
The problem is: I don't have a payment method
@native tide sounds like that is a premium feature, so without a payment method, you can't do it
@native tide free*
@native tide to me, it sounds like that feature has a free tier that you can go over
@native tide is not uncommon for a cloud provider to require a payment method even on free tiers though
😩
@native tide see AWS, GCP, Azure, DigitalOcean, Linode, AliCloud, etc... They all require payment methods even if you don't do anything or only use free tiers
Yeah that's why i keep away from those.
Cloud hosting costs someone money, so expecting it to be free is naive
Free tiers exist to try to up sell you
And they can't do that if you don't have a payment method configured :)
You are right
anyone experience in media queries?
found a good place to host always data
is there a way to speed up my django server cause to login in to my account is taking like 20 minutes
what webserver r u using atm
im using localhost not yet hosted publicly but when i log into my account in my own site (not admin) its taking time when i move over to the terminal is [16/Aug/2020 19:24:32] "POST /login/ HTTP/1.1" 302 0
🤔 Weird that you're getting a 302 response code for a POST request
but thats not a massive issue
if you're binding to localhost and using localhost in the browser might be worth testing with 127.0.0.1
ive had issues with latency before due to localhost stuff
i know this is for python help, and this is kina python stuff. im trying to run a pygame on my website. (pygametemplate.py is just a tiny game that im useing for testing). im getting the "finished python script, but nothing is actualy apearing on screen. i was wondering if i couod get some help with that part
this is what shoudl d be coming up
its jst a block that moves aroud the screen wghen you hit wasd
Do you have an actually interpreter running on you site @digital karma ?
Otherwise, I don't know what you are expecting to happen
Just a download?
from flask import Flask, render_template
from flask_socketio import SocketIO
import random
app = Flask(__name__)
#vnkdjnfjknfl1232#
#app.config['SECRET_KEY'] = '#auhdfubwekofswe#'
socketio = SocketIO(app)
server_ids = [0]
game_sessions = []
player_names = []
@app.route('/')
def sessions():
#return render_template('index.html')
return render_template(['CheckingGames.html', 'testing.css'])
That is what I tried at the bottom (ignore the server_ids, game sessions...)
since it said it accepts lists
this says GET http://127.0.0.1:5000/testing.css net::ERR_ABORTED 404 (NOT FOUND)
@nova sleet Do you have the <link rel='stylesheet' href='testing.css'> in your hlml file
yes
You just need to render the html file, and the css will be rendered since it's already included in the file
how would i use ssl certification on aiohttp
do u put css file in static folder
Yes
Does anybody recommend any resources to build RESTful APIs?
(in flask that is)
you cant link css with href="testing.css"
How then
Why not
<link rel= "stylesheet" type= "text/css" href= "{{ url_for('static',filename='styles/mainpage.css') }}">
Basically this format
also css needs to be in static folder
O
@cyan violet that is usually a web server function, not aiohttp
uh?
@cyan violet re: your TLS cert question lol
But what web server aiohttp uses
@cyan violet you get to pick, but I tend to use nginx
Apache or Nginx are the two usual candidates
But yeah, both can do letsencrypt with certbot
But how could i choose?
By installing one or the other and configuring it lol
Well but with aiohttp
It's not an option inside of python
You have to expose your ASGI interface and then serve it with nginx/apache
Well i didnt understand that
no results
@cyan violet also, you can't do tls on port 80
What? Nothing redirected unless you configure it to do so. But a modern browser will try 443 first
But nginx is easy to do secure rewrites
SO basically i don't understand ANYTHING about it
Lol
So i installed nginx
Ok, follow the doc then
How do i even edit the conf
wheres it located
should i replace all the http part
in the confi
@cyan violet that depends a lot on your operating system
But generally, just follow the docs lol
@native tide Where should I put the static folder, because I tried putting it with templates, and pretty much the same thing.
If I put it outside, I wouldn't be able to use a relative url anymore
Don't mind testing.html and index.html
those are seperate
it's still giving a 404
static should be outsidee templates
would I have to use an absolute url then?
ok...
<link rel="stylesheet" href="/static/signuppage.css">
Will link the css, or you can use url_for()
does the relative url start from the python file running it?
or the initial html page?
So essentially, you'll render the HTML page "checking games", and that has the css already attached to it via the link.
def sessions():
return render_template('CheckingGames.html')```
It starts from the root directory, not too sure how to explain.
Starts from the project folder, if you look at my image for example, it would be /static/file.css
Docs would explain it so much better than I can
ok
So once that's all done, and you visit localhost, the file (and css) should appear, let me know how it goes
Can someone please help me get my web app up and running? I am having some issues with gunicorn and importing local modules
Really would appreciate it about to put my head through a wall lol
what are the issues?
I'm starting my flask app using gunicorn -c gunicorn.ini.py "app.create_app:create_app()"
but it fails to import local files
are you talking local modules? or what do you mean?
well ... it's not a module first of all
sorry I am ass backwards when it comes to proper terms
modules have to follow the
. (ROOT)
/module_name
-- __init__.py
-- code.py
that is the only way in can be imported
would renaming create_app to init.py work?
i can't see your tree anymore, so idk
what are the 6 problems in that file?
in the create_app file?
yeah
unused variables
but no, just add a "scraper" directory, add a blank __init__.py and move your scraping logic there
it works locally fine Just when i try to run it on a server with gunicorn I get an issue
then your import stuff should work just fine for import scrapper
assuming you didn't code yourself into a circular dependency
you aren't importing them, so don't do anything with them if you don't need to
one problem at a time my dude
ok bro lol I will do what you said first and see what happens
might be worthwhile to read the docs on python modules and how it resolves them
do I need an init.py in my main directory
no
ModuleNotFoundError: No module named 'scrapper'
it works locally
well it at least starts up fine locally when I try to run anything regarding scrapper.py I get an error
so something like this scrapper.filteredResult(request.form) fails because scrapper has no attribute
is there a Django guide for beginners that's like Miguel Grinberg's flask dev guides?
(except hopefully unlike Miguel Grinberg's flask dev guides, the topics are not well organized or explained in my experience)
corey Schafer
In this Python Django Tutorial, we will be learning how to get started using the Django framework. We will install the necessary packages and get a basic application running in our browser. Let's get started...
The code for this series can be found at:
https://github.com/Core...
