#web-development
2 messages ยท Page 82 of 1
I guess this is countries, but state works the same way:
COUNTRIES = ( ('AF', _('Afghanistan')), ('AG', _('Antigua & Barbuda')), ('AI', _('Anguilla')), ('AL', _('Albania')), ('AM', _('Armenia')),
the value in the DB is one of those tuples.
{{ record.get_state_display }} should work
It just removes the entry.
{{record.country}} gives me 'AL', inthe case of Albania being the entry.
And {{ record.get_country_display }} gives you nothing ?
Right
And you have translations for all those countries, no empty translation ?
Each country has a full-name associated with it, if that's what you mean?
the _() suggests it's a i18n variable
Honestly I took the list from somewhere, so I don't know what the _() is accomplishing.
Ah. If you're fine with english only names for your countries remove the _()
Will that affect current entries?
Ah, well, states looks like this:
STATES = ( ("Alabama","Alabama"), ("Alaska","Alaska"), ("Arizona","Arizona"),
and I have the same problem, so I don't think that's it.
Alright. What do your state & country fields looks like in your model ?
Ah...
Ok, so it's being saved into the field as country = models.CharField(max_length=100, default="", blank=False) rather than the entire thing
You need a choices=STATES (or COUNTRIES) on this CharField so django knows what the values can be
Without this django can't restrict the field to those values and the get_***_display() will not work
Does anyone have a decent production ready Django Docker setup I can look at?
preferably a relatively simple one with no bells or whistles
Right gotcha, ok let me play with it. Need to update some things.
preferably a relatively simple one with no bells or whistles
@rigid laurel simple? no. Production-ready? yes. https://gitlab.com/sports-prediction/sports-prediction/
This uses gitlab-ci to build images on push, with a manual deploy.
Those two are somewhat oxymoronic I guess
Feel free to look at it and ask questions.
I think that setup is a bit too complex compared to what I'm going for. I literally want one container which is the Django app (and one in dev only for the database) - that many compose files is just too scary
thanks though
This is much simpler. But we never made a production build lol
Really, if you rename the .dev.yml to .yml, and change the Dockerfile to start gunicorn instead of runserver, this probably isn't far off from what you need.
Got it @bleak bobcat Thanks!
This simpler example is helpful yeah - thanks @lethal orbit. I'm fine with writing code, but god do I hate making it run
Learning devops is fun
isnt it hard tho
what is devops again exactly
devops is like the cloud hosting right?
More like automated testing, automated (repeatable) deployments... better integration between writing the code and deploying it.
ahh
@heady ore not sure. We use CosmosDB extensively in SQL API so I know itโs fast. Open a ticket if you want and think itโs CosmosDB side.
@zealous siren i believe it is convenient, must be sth wrong on my code. MS support engineer said it might due to the initialising the connection. for my understanding, i might need to avoid calling the client instance too many times. so still checking what cause this issue so far
btw, he mentioned the partition key as well, but i don't think it's the key point in my case. since i only have 15 data in one collection for testing
still need more background knowledge, my first year in backend๐คฃ
Outlier, I wouldn't use MongoDB API UNLESS you are trying to convert
SQL API is best API
because the project will have many changes. mongodb will be a better choice
i wouldnt say mongo isnt the best for changing things
If you want to change the collection names or anything reliably you have to delete the collection and re fill it
@lament kraken U can learn htm;,css,js from clever programming or freecodeCamp.org
yeah, i literally use mongo for nothing that i deem important
i wouldnt say mongo is the best for changing things
@quick cargo
Why?
SQL is best
look at the tech channels
in it
it has name of them and teaches what they teach
some teach css html and js
it has a list of tech channels
I will go with @native tide suggestions, thanks bro
html,css = easy as hell and js = yeah alright
@native tide what do you mean why
I already showed him the path of a web developer
i was trying to help...
yeah good
bruh
:/
Also Yall are comparing a Single NoSQL database to an Entire query language and an entire scope of databases
Nah we just chilling
just because mongoDB isnt the best doesnt mean that NoSQL in general is the worst lol
lol @ mango though ... a legit mango would be a better data store than mongo is ๐
Lol
as far as NoSQL goes, i actually really like Cassandra. and on that same front kind of, BadgerDB
The best books to learn Django๐
Packt does have a lot of great stuff
Yes that's right
the response seems getting far from my question ๐คฃ
Django is mad thing because of the file structure i couldn't even sleep the day I learned Django
legit i was on the floor and crying
I tend to like the NoStarchPress stuff better though. No Django stuff though
And the next day i was about to quit programming because of django file structure which made me wonder why i'm living in this earth
this is not even a funny guys legit i'm dead honest
And the next day i was about to quit programming because of django file structure which made me wonder why i'm living in this earth
@native tide
I believe we live to be in pain and to learn from pain๐
But everything is good now because of flask yeh man if i start talking about flask then we would be on earth for 1000 years
Django has it's place, just like Rails, but yeah, it's not a silver bullet lol
I'm testing the waters with Blazor right now actually
it reminds me of Vue/React ... except is C# on WASM lol
was tempted to play with Rust and WASM
i've not found a good library yet that doesn't make you do all of the bindings yourself, which is fine, but not something i would advertise to novices lol
there are a few that are coming up, but not really ready yet
Just did a search and I might try out seed
atm i got bigger issues todo with like debugging why the server freezes up when a high load comes in ๐ฉ
hey, i am working on a backend for my website in Flask and all of the sudden it doesnt work. it was working 5 minutes ago and now i get this error``` * Serving Flask app "backend" (lazy loading)
- Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead. - Debug mode: on
Traceback (most recent call last):
File "/home/marcorodriguez/Projects/PasswordManagerWebsite/backend.py", line 24, in <module>
app.run(debug=True, threaded=True, port=80)
File "/usr/local/lib/python3.8/dist-packages/flask/app.py", line 990, in run
run_simple(host, port, self, **options)
File "/usr/local/lib/python3.8/dist-packages/werkzeug/serving.py", line 1030, in run_simple
s.bind(server_address)
OSError: [Errno 98] Address already in use```
i havent gotten it before
and i havent changed anything in the code
looks like you have another instance of it running already @tacit anvil
i dont have it open but i will restart to see if that helps
or you installed something that ate port 5000
not sure what OS you are using, but it's possible to send those things to the background pretty easily
yeah, if you accidently add a & at the end of any script, it goes to the background ๐
you could do a sudo netstat -tulpn if it happens again to see what is using your port
Hey @native tide!
It looks like you tried to attach file type(s) that we do not allow (.html). We currently allow the following file types: .3gp, .3g2, .avi, .bmp, .gif, .h264, .jpg, .jpeg, .mkv, .mov, .mp4, .mpeg, .mpg, .png, .tiff, .wmv, .svg, .psd, .ai, .aep, .xcf, .mp3, .wav, .ogg, .webm, .webp, .m4a.
Feel free to ask in #community-meta if you think this is a mistake.
cant get <img src="kebab.png" width="50px" /> working, tried with images/kebab.png but it just displays as that weird default pcture (when the pic in question isnt found)
@tacit anvil Are u trying to make a chat app using socket programming and flask?
no
im trying to make a website using html
and python and the back end
using flask
yes
idk what that is
Don't worry I'll explain u what is bootstrap
Bootstrap is the most popular CSS Framework for developing responsive and mobile-first websites
ok
definitely not the best framework tho :P
@quick cargo Yep
i'm going to learn JS now, help me
give me some good resourves
@native tide U learned python first?
um........... yes
ok one advice
Js syntax might be hard ok and don't give up continue learning js
but I just learned python basics and that's it
I will continue python later
ok
Js syntax might be hard ok and don't give up continue learning js
thanks
Gl
it seems so
I finished the first lesson on FCC.
but I didn'tt understand much.
@native tide Btw every high level programming language like ,python,javascript,c++ covers same concept so don't be worry about while looop or for loop if statement because it's all just same
yep
but it has something like do......while
also python was much much easier than JS.
yes python is easier than js
Don't stop python aswell
ohk
how?
Everything must be in balances
i mean "don't stop python aswell" just do the basics to remember
that it
like?
basics?
I already know them.
nvm gl
but I didn't made any projects in python
I only made password checker, img to pdf, dictionary, etc
back to my question : "give me some good resources"
back to my question : "give me some good resources"
@native tide
To learn python?
JS
JS
@native tide
1.Sololearn
2.any book
- Freecodecamp
I already know about FCC and sololearn......... thanku
but which book should I follow?
oh wait
I just found this.
@native tide
ohk
thanks
ohk
found it's pdf
Yes
contains questions at the end of each lesson the questions are in a link at the bottom of the page, If you don't open the link use VPN
ohk
where is the most simple and cost effective place to deploy a django project
netlify or heroku probably
I've looked at heroku but that has issues with user uploaded images and ive also look as aws lightsail and elastic beanstalk look complicated af
lightsail isn't hard
beanstalk is
if you are containerized, google cloud run might work for you
using docker, but i am going to assume that is not the case given you didn't know the terminology lol
nope not using docker
docker makes deployments cheap and easy (usually) ... it's worth looking in to, but otherwise, take a look at netlify
what does it do
i honestly don't suggest AWS for anyone unless they themselves want it
yeah aws just looks like pain
it's not hard, but i just hate how they run their business lol
and their API is crap
yeah, netlify is a nice one-stop-shop for web apps
i cant really find anything for django on netlify
this article has the word once
ah, nevermind ... only works with static sites
but folks have used cactus to generate static content from django sites
so i have to use either heroku or aws
or just follow that link you posted ๐
it has no relation to django though
some weird thing called cactus
the only reason i linked it is because it was the only article on their site that even contained the word "django"
cactus is a static site generator that uses django content as it's source
ah, i forgot about pythonanywhere
that might work
hmm
Host, run, and code Python in the cloud: PythonAnywhere
looks reasonable
VPS
wouldn't be what i ran a full blown production server on, but it'll work
You can get a VPS for $2.50-$5 a month
wtfart is vps? lol
It does take some initial setup though
VPS sounds like a pain
dont you have to setup a firewall and config and stuff
and like permissions and storage
and bruh
technically, you should WANT to do that lol
Yeah, but there are guides that tell you how to do all that...
permissions, not really.
thats sounds like so much effort
True
ah, you are one of those developers lol
Don't deploy to production
the reason i have a job ๐
wdym lolol
Just have people come to your house and look at your screen if they want to use your app
๐คก
Much less effort
{% if not post.Comments.all %}
<h2>Comments</h2>
<h3>No Comments yet.</h3>
<hr class="my_4">
<button class="btn btn-secondary"><a id="del" href="http://127.0.0.1:8000/admin">Add Comments</a></button>
{% else %}
{% for v in post.Comments.all %}
<strong>
<h2>Comments</h2>
{{v.current_date}}
{{v.comment}}
</strong>
{% endfor %}
{% endif %}
I added a Comment and it still says "No Comments Yet"
Whats Wrong?
depending on how you structured your DB, try post.comment_set.all
nope doesn't work
# Comments Model
class Comments(models.Model):
posts = models.ForeignKey(Post, related_name="comments", on_delete=models.CASCADE)
current_date = models.DateTimeField(auto_now_add=True)
comment = models.CharField(max_length=100)
def __str__(self):
return self.comment
try post.comments.all I guess, at this point I am mostly guessing
port?
typo
what I generally do is send these things in the context dict, rather than making the DB query in the template
no idea why it does not work though
for example:
def politician(request, pk):
politician_ = get_object_or_404(Politician, pk=pk)
return render(request, 'politics/politician.html', dict(
politician=politician_,
stances=politician_.stance_set.all(),
img_url=politician_.portrait.url
))
hey does anyone here know wordpress? i need help with something stupidly simple
# Comments Model
class Comments(models.Model):
posts = models.ForeignKey(Post, related_name="comments", on_delete=models.CASCADE)
current_date = models.DateTimeField(auto_now_add=True)
comment = models.CharField(max_length=100)
def __str__(self):
return self.comment
@somber aurora your model structure is backwards...
well, not backwards but a bit weird
okay, I just woke up and I am not expressing myself properly
your model should be called Comment, and the field should be called post, and I would suggest you change the name of the other field comment to something like body
anyway, post.comments.all() (note small caps) should work
because it refers to the behaviour when you delete the related object
Never used django orm or sqlalchemy so was guessing
i.e. if you have models.CASCADE on the comment, that means that when you delete the post, the comments go too
the other way round wouldn't make sense
thanks I'll try once laptop is charged
Looking for help with django and bootstrap, and i can't spot the issue, The rest of the page is loading the CSS fine, and i'm getting no 404 messages.
<div id="carouselgneillIndicators" class="carousel slide" data-ride="carousel" data-interval="6000"> <div class="carousel-inner"> <div class="carousel-item active"> <div class="gneill-content-home"> <div class="gneill-view-on-mobile animate-box" data-animate-effect="fadeInRight"> <h1>Giovanna Neill</h1> <p class="gneill-p-subtitle">Makeup Artist</p> </div>
<img class="img gneill-img-home gneill-img-home-left animate-box delay-4" data-animate-effect="fadeInLeft" src="{% static 'images/side_view.jpg' %}" alt=""> <div class="gneill-content-text gneill-content-text-right"> <div class="gneill-content-absolute gneill-content-absolute-right"> <div class="gneill-not-view-on-mobile animate-box" data-animate-effect="fadeInRight"> <h1>Giovanna Neill</h1> <p class="gneill-p-subtitle">Makeup Artist</p> </div> <p class="text gneill-text-home animate-box" data-animate-effect="fadeInRight">Hi, Iโm Giovanna Neill! I have a passion for all things beauty and I love to make people feel beautiful inside and out. From a young age, I have always been drawn to makeup application and hair styling. To me, makeup is a versatile form of art, where you can completely transform someoneโs appearance or simply highlight their best natural features.</p> </div> <div class="gneill-color-button animate-box" data-animate-effect="fadeInRight"> <div class="gneill-button-link"> <a href="{% url 'page_app:about' %}">About Me!</a> <span class="gneill-button-block gneill-button-block-grey animation-bounce"></span> </div> </div> </div>
it actually might take up too much room if i post the rest
but happy to do that in pm
@marsh canyon there is no error, the carousel just pops and and disapears
to a completely blank container
set an alt for the images and see if its even rendering
and are you getting any errors server side?
nope
clear cache, ctrl f5
System check identified no issues (0 silenced).
August 28, 2020 - 14:44:17
Django version 3.0.8, using settings 'gneillmakeup.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
[28/Aug/2020 14:44:20] "GET / HTTP/1.1" 200 12679
the page is completely blank?
Yep
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
use this to paste code
what flashes?
so its appears and dissappears?
remove the css links and see if the problem persists
ctrl f5 after removing css links just incase
all of the css links?
whatever the page uses
it loads everything without the css
so the problem is with the css
see if you got any keyframes wrongly configured
you want to look for animation in css, mainly the animation duration and animation-fill-mode
mostly all these will be in 1 line with the property animate
.animation {
-webkit-transition: all 0.2s ease;
-moz-transition: all 0.2s ease;
-ms-transition: all 0.2s ease;
-o-transition: all 0.2s ease;
transition: all 0.2s ease;
}
.gneill-button-link:hover .gneill-button-block {
left: 48%;
}
.animation-bounce {
-webkit-transition: all 600ms cubic-bezier(0.68, -0.55, 0.265, 1.55);
-moz-transition: all 600ms cubic-bezier(0.68, -0.55, 0.265, 1.55);
-o-transition: all 600ms cubic-bezier(0.68, -0.55, 0.265, 1.55);
-ms-transition: all 600ms cubic-bezier(0.68, -0.55, 0.265, 1.55);
transition: all 600ms cubic-bezier(0.68, -0.55, 0.265, 1.55);
}
}
only thing with animation tagged
:/
lol, maximum value can be 1
it does not disappear anymore?
Nope
but now it doesn't do anything its just static
did you link back all ur css?
its also not switching between the other carousel
oh yeh i did that before
i commented it
oh
thats kinda expected haha
Umm, sooo....
the function is supposed to fade it to 0 oppacity and then fade the next one in
but now its just two overlaying each other ๐
right
So its clearly not getting the javascript properly
but it could also be the animate.css file?
im not expert, but maybe just using bootstrap cdn?
i can't because theres .js files it calls to which is in a modified bootstrap version
is this project open sourced?
kay
you could try asking the question in a more web dev oriented server, more luck
you could seperate the html/css/js files and use the modernizr
@marsh canyon also is there anyway to use ID tags in django
because they seem to not work
@heavy drift you can try this server, much oriented towords frontend/javascript
https://discord.gg/devcord
what do you mean by ID tags
sorry, never really seen that before
yep
yeh django don't like
u mean scroll link behavior?
Yuh
Right but this code works fine outside of the django ๐
the whole website works normally
but inside django it dies
for instance those carousel buttons
kk
just the import lines
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCe2q1gFSd75jKUnTDPq0nZWaMlEu6vL30"></script>
<script src=" {% static 'js/script.js' %}"></script>
<script src=" {% static 'js/plugins/bootstrap.min.js' %} "></script>
<script src=" {% static 'js/plugins/googlemap.js' %} "></script>
<script src=" {% static 'js/plugins/jquery-3.3.1.min.js' %} "></script>
<script src=" {% static 'js/plugins/jquery.waypoints.min.js' %} "></script>
<script src=" {% static 'js/plugins/modernizr-2.6.2.min.js' %} "></script>
<script src=" {% static 'modules/magnific-popup/jquery.magnific-popup.js' %} "></script>
<script src=" {% static 'modules/masonry/masonry.pkgd.min.js' %} "></script>
i mean imports within the js file, if any?
django kinda forces me to add .js extension to the imports or else they dont work
<script src=" {% static 'modules/magnific-popup/jquery.magnific-popup.js' %} "></script>
<script src=" {% static 'modules/masonry/masonry.pkgd.min.js' %} "></script>``` did you forget `js/` folder in these?
when loading site with django, did you find any errors in the console?
nope
Uncaught ReferenceError: $ is not defined
at script.js:60
at script.js:128
bootstrap.min.js:6 Uncaught TypeError: Cannot read property 'fn' of undefined
at bootstrap.min.js:6
at bootstrap.min.js:6
at bootstrap.min.js:6
at bootstrap.min.js:6
js?key=AIzaSyCe2q1gFSd75jKUnTDPq0nZWaMlEu6vL30:127 Uncaught re
DevTools failed to load SourceMap: Could not load content for chrome-extension://gannpgaobkkhmpomoijebaigcapoeebl/bundle.min.js.map: HTTP error: status code 404, net::ERR_UNKNOWN_URL_SCHEME
DevTools failed to load SourceMap: Could not load content for http://127.0.0.1:8000/static/js/plugins/bootstrap.min.js.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE
DevTools failed to load SourceMap: Could not load content for http://127.0.0.1:8000/static/css/bootstrap.min.css.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE
but whyyy
i wouldn't know how to fix this, honestly
bastard thing i'm too green
its looking for the variable header
why is there is a .map
try fixing the first 2 errors
i have 0knowledge of jquery
or just google the errors
i am
i don't think its related though
since the header is loading properly
and shouldn't effect the index
some thing to do with the ordering of imports
i haven't imorted anything though
i think it just wants a bloody ref
as in language="JavaScript" type="text/javascript"
try
try googling Uncaught ReferenceError: $ is not defined django
maybe its only for jquery
nope
still didn't fix anything
maybe its because i've got load static twice due to the inheritance
https://discord.gg/2p4Pzj
try the frontend channel here
i don't really have a lot of exp working with javascript and django
Kk thank you
@marsh canyon it was a godamn load order for the scripts
oh
so can anyone please tell me any method of creating a search bar that is xss proof and can search stuff on my site only
(i am new to web dev and my site only has html css and js ) 
please ping me if someone can answer thanks in advance
I was looking through the flask documentation, and came across thread locals. I can't seem to understand what they are exactly. Can anyone give me an example please
You have some examples of what thread_locals do
in the manual
go to your terminal and run FLASK_APP=app.py flask shell and in the shell, import the threading_local library like so
> import _threading_local
> help(_threading_local)
you'll see some cool examples, if you still don't understand let me know.
How to add authentication with access roles to Ariadne (Django) project?
Use JWT
https://pypi.org/project/ariadne-jwt/ @valid cypress
Though it has some code WTFs I am not a big fan of...
You can also roll your own JWT implementation using PyJWT, like we have: https://gitlab.com/djangocities/djangocities
If you look at commits 12ac1dda - 26cca9bf, this is the JWT stuff (https://gitlab.com/djangocities/djangocities/-/commits/master)
OK, thanks
so can anyone please tell me any method of creating a search bar that is xss proof and can search stuff on my site only
(i am new to web dev and my site only has html css and js )
If you want to set up a search bar system on your website I think Elasticsearch is a way to go. There are plenty tutorials how to do that, but there is one in particular that I like https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-xvi-full-text-search
elasticsearch ๐
?
@native tide thank you so much for this Sir but I only e made a website using HTML CSS and JS do I have to import the entire thing into flask or Django
Elasticsearch is a server package or service, it's available on Python using python -m pip install elasticsearch and it's also available on Java if you have a distributed system and you operate with microservices. You can probably achieve something similar using JS but I don't see why you'd do that.
Is there someone really good with html and CSS??
@azure saddle formulate your question and maybe someone is "good enough" to answer it.
Does anyone recommend any reading material for implementing React with Flask?
Hey guys, do you have any ideas of projects with flask that can teach me a lot when i built it?
@weary dragon see flask official website and follow the tutorial named tutorial. You will find it useful.
Thanks, but i already made some flask tutorials
oh. so you're intermediate.
Yes, i am pretty good with databases too
oh
What do you mean "projects that could teach me a lot"?
I know some stuff but i am not to confident to do some real world projects
What are the projects that you've done then? Describe them
I made a website that you can borrow games, a blackjack game, and some web scrappers all just for me and practice
you can make some api stuff with flask
Yeah you could start creating a Restful API and after that you could look into distributed systems. I mean that's what I do now, I started learning about microservices and how to containerize them using Docker & Kubernetes. You can then look into Travis CI which is a hosted continuous integration service used to build and test software projects hosted at GitHub
If i don't bother you can explain better what are microservices? I heard flask is for this but i don't really know what those are
Flask is not for microservices..it is indeed a micro web framework written in Python that is not as abstracted as Django and has less tools and libraries, but it s not intended for microservices in particular. Microservice architecture is an architectural style that structures an application as a collection of services that are: highly maintainable and testable, loosely coupled, independently deployable. If you think about opening a start-up and working with a team of developers in the future, microservices would be a vital choice.
You can orchestrate this microservices to communicate with each other using docker clusters and or kubernetes which will cross out the idea of single points of failures in your web app.
And it's there any advantace to know oop, like when i made blackjack game i used for it a object for game that manage game logic, what exemple of oop excluded databases objects are if exist
Ugh..
yo why is my static file not working i see not error 40* in my terminal but my styles are not applying to the page
OOP stands for object oriented programming and it's not related to databases ๐ It s a computer programming model that organizes software design around data. As you said, you can create complex objects, but that's not the point. You use OOP almost anywhere in the computer science industry. There are advantages: modularity for easier troubleshooting, reuse of code through inheritance, flexibility through polymorphism and effective problem solving.
@lapis spear CTRL + F5 on the webpage
@lapis spear CTRL + F5 on the webpage
@native tide i already refreshed it sir
ctrl + f5 restarts cache
Yeah my bad
whenever I update .css it works for me
that was for mac command + shift + r
im using windows
Hello
show me your code
yeah, thanks brother. i was also dealing with this problem. thanks a lot 
what browser are you using @lapis spear
oh i see i think that ctrl+f5 is the solution sir haha
๐คฆโโ๏ธ
@native tide chrome sir
It is yeah, it clears the cache as @native tide said.
haha nice nice haha i thought it would be my css problem at first well thank you everyone then moving on hahaha๐ ๐
I need help with oauth
Like I don't know where to start...
I'm using Django 3.0 alongside DRF.
I'd like to allow third party apps to use my API, in fact there's a couple interested. I've been able to grand read-only access without quarrel but I need to grant write access and don't want to blindly give a third party access to edit any user or post on behalf of any user, but I'm not sure where to start. I know in theory I need an oauth2 flow where users would grant the third party app access to their data, but how to do that... I've no idea.
this is not Django but Flask, but this might be a good starting point: https://blog.miguelgrinberg.com/post/oauth-authentication-with-flask
I am not sure what my level of knowlage counts, but I want to advance in my skill level, but I also dont want to go for something completely out of my league
Does anyone have a idea how to determine your skill level and find ways to advance?
@weary osprey check out django-allauth https://django-allauth.readthedocs.io/en/latest/overview.html
Does anyone have a idea how to determine your skill level and find ways to advance?
@limber laurel you have anything up on git? ask for some code review
https://github.com/MareksNo/database_website_op
https://github.com/MareksNo/CaloryCounterDjango
These are my projects
My biggest web projects
def test_user_change_page(self):
"""Test that the user edit page works"""
url = reverse('admin:core_user_change', args=[self.user.id])
res = self.client.get(url)
self.assertEqual(res.status_code, 200)
This is django 2.1 code that I found in a tutorial. admin:core_user_change gives error. how do we test this in 3.x?
My biggest web projects
@limber laurel I'll look over them tomorrow. Right off the bat, I can tell you to look into.gitignorefiles and best practices. You shouldn't commit.idea, and you probably don't want to commit you database files either.
Also, good practice to have a README.md file in your repo root to have deployment instructions.
Ok, will keep that in mind for future projects
@weary osprey check out
django-allauthhttps://django-allauth.readthedocs.io/en/latest/overview.html
@lethal orbit That's good for logging into other services but I'm looking to be the login provider
Ok, how can I keep that hidden? Should I set it when for example deploying/running the server like for example
python manage.py runserver SECRET_KEY='secret-key'
Most Microservices are Javascript SPAs with REST Backends, when building sole REST API backend, I'd look at FastAPI, maybe Flask, Django can work but is really fat for simple Rest API backend (but good choice if you already have Django site)
Ok, how can I keep that hidden? Should I set it when for example deploying/running the server like for example
python manage.py runserver SECRET_KEY='secret-key'
@limber laurel
SECRET_KEY = os.environ.get("DJANGO_SECRET_KEY")
$ python DJANGO_SECRET_KEY=abc123secret ๏ปฟpython manage.py runserver
At least in Linux
Oh, ok I guess on mylist is: enviroment variables, gitignore and readme, caching and security
Most Microservices are Javascript SPAs with REST Backends, when building sole REST API backend, I'd look at FastAPI, maybe Flask, Django can work but is really fat for simple Rest API backend (but good choice if you already have Django site)
@zealous siren you can easily strip out the parts of Django you don't need, and the batteries included, auth, and account management mean that it's still a great back-end.
Millions of sites are powered by DRF, and many new ones use graphene or ariadne.
That's a good start, Mareks.
@lethal orbit That's good for logging into other services but I'm looking to be the login provider
@weary osprey Oh, sorry. I have been thinking about that as well, but haven't actually looked into it properly yet.
can y'all help me make sense of the pushshift API? I made this script to crawl subreddits, but it does not return all data like it used to:
start_time = 1483228800
batch_size = 100
request_fields = "fields=author,created_utc,full_link,num_comments,score,selftext,title,"
subreddits =["Bitcoin", "btc", "BitcoinMarkets"]
for i in subreddits:
for o in range(5000):
try:
response = requests.get("https://api.pushshift.io/reddit/search/submission/?subreddit={i}&after={after}&size={size}&{fields}".format(i=i, after=start_time, size=batch_size, fields=request_fields))
data = json.loads(response.text)
data = pd.DataFrame(data['data'])
start_time = data.iloc[-1]["created_utc"]
data.to_csv('{i}_{o}.csv'.format(i=i, o=o))
except:
print("Finished crawling /r/{i}!".format(i=i))
break
it does return a few posts but not everything like it should
for example i crawled a few subreddits in april and it returned 800MB of data in csv files. I ran the exact script again yesterday and it yielded 2MB
I dont understand what i am doing wrong here
well there definetely is. I ran the exact script from april again and it just returned 2MB of data instead of 800MB
and if your look into reddit and the subs there, there is definetely more data that is not returned
do you see any flaws in my script?
@lethal orbit you are still bring bulk that is django, and FastAPI/Flask come with critical parts you need for RESTful API
what i am doing is fetch 100 submissions starting in 2017 (start_time = 1483228800) and save them in a csv
then i take the last submission and take its timestamp (created_utc) and use it to make a new request to fetch the next 100 submissions
and repeat
@lethal orbit you are still bring bulk that is django, and FastAPI/Flask come with critical parts you need for RESTful API
@zealous siren if you don't import/register views, they don't get imported. If you remove middleware, it doesn't get imported.
Not saying that Django is the only framework out there, but saying "it's heavy" is extremely ignorant, and saying "FastAPI is better" is short-sighted.
I gave my opinion, if you reach for django for pure RestAPI, you are making mistake generally the best way tos tart is go simple and build up, not go huge and gut down
Yeah, start simple and add some third party ORM, and third-party user management lol
With Django you know what you're getting, and that is something stable, and tested.
Nothing wrong with SqlAlchemy either, but.... why reinvent the wheel?
If you don't need user accounts, etc. or even SQL, then it may not be the best fit, but there is ZERO wrong with using Django for APIs.
Because of SRE concerns, Stability, security
lolwut?
DJango has bug, are we using that middle ware, I don't think so, but who knows if developer slipped it in
Django has security vulnerability, do we need to rush to patch or is it not a factor
Somehow it powers Disqus, and Instagram...
Well, if it has a security vuln, then you need to patch it.
But other packages (especially the ones that are newer and not as well tested) are just as likely, even more, to have critical bugs.
Django is (generally) known for its safety.
@native tide A tip, when posting code snippits, if you put the code language after the first set of backticks but before the newline, it formats the code
Example:
```py
foo = "hello"
```
becomes
foo = "hello"
someone know how i can automate a function run every 15 minutes in flask?
I have a function that calls twitch API and collects viewer data for streamers and saves it to csv
now i just need to automate the task
you could prolly have another program do that work, as you don't require any flask functionality for that
then use time.sleep() in the seperate program
ahh okay, thank you guys. ill take a look at both
I am trying to replicate https://www.educative.io/courses/learn-cpp-from-scratch/qVlZBm6qRpR , is this correct way to structure it? https://dpaste.org/fYF4
Guys how do I implement react with flask?
Its so confusing
@native tide https://www.youtube.com/watch?v=YW8VG_U-m48&t=307s
How to setup a react/flask project.
I have decided to put all my tutorials in my channel
"Code With Joran" https://www.youtube.com/channel/UCom-uJL0CkFhGpmM2yutTGw
please follow that channel if you are interested in my coding tutorials
My recommendation: https://ariadnegraphql.org/docs/flask-integration
And https://www.apollographql.com/docs/react/ on the react side
Ariadne gives you a nice GraphQL API, and you can use React as a SPA
So, if you have a react frontend, you can no longer use render_template?
So, if you have a react frontend, you can no longer use render_template?
@native tide ideally, no, you just use it as an API.
Ah, okay. Thanks for that. That's going to be interesting :)
It does have advantages though... You can, for instance, use the API in Android and iOS apps.
For my very first flask project I think I'll leave react for now, I'm already so far in, but I'll continue learning it for the next.
Could someone who knows how to make custom flask commands help me in #help-donut ?
Anyone used Flask-login before? I am having trouble getting the current userID when logged in.
User Loader
@login_manager.user_loader
def load_user(id):
return User.query.get(id)
## If i print user.query.get(id) it returns the user ID
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(255), nullable=False)
email = db.Column(db.String(255), nullable=False)
password = db.Column(db.String(255), nullable=False)
profile_img = db.Column(db.String(100), nullable=False)
def get_id(self):
return self.id
User().get_id() returns None even when the user is logged in
you have to convert the id into an int
i am actually working on a log in feature as well
@login_manager.user_loader
def load_user(id):
return User.query.get(int(id))
@past cipher
thanks will try
Same issue
get_id returns None
if I print User.query.get(int(id)) after login, it returns the user ID. However if I call User().get_id() when the user is logged in, it returns None
You should call it as User.get_id()
tried that too, didn't work
User class has to be initiated I'm sure
I've used flask=login in a bunch of projects, and never had this issue before
Ah, well i am not sure. I dont think it is necessary to create a function in the model when you can just use User.query.get(int(id)) to return an id
Sorry I couldn't help xd
that also returns None when calling it, strange
I give up for today lol, will try again tomorrow
current_user.get_id() works fine
but User().get_id() doesn't
You guys into Django and stuff?
Some may be, but I use flask ๐คท๐ปโโ๏ธ
are usernames automatically validated in django when using User.objects.create_user()?
what do mean be automatically validated? Like if the username is taken or is the username correct when logging in? I user user.objects.create_user when a user signs up, but yeah django does a lot for us in the background.
@acoustic oyster
if creating a user does django automatically check if it is unique, valid i.e so restricted characters used?
I see I can call password validation and email validation manually
Ah I see. I'm not 100% sure but I know that django forms won't allow duplicate usernames but I'm not sure about special characters- I assume it does tho
I am concerned because according to docs email and password are not validated when using create_user()
this is for registering a user via api
My roommate suggested using the clean data function and form is valid. I'm still learning django too. I hope this helps
Netninja on YT goes over it he says
haha, ty. I am not using forms for this atm, but am considering it
well I have been trying to make an website with a python back-end and I have been facing problems when I render the template with the help of flask
but the main problem is that I had set some logos and background images that are not being shown in the template when I render it through my program
but when I open that freaking HTML file it is perfect with the correct CSS alignment and all the images are good but they are not working with my program lol
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial sclae=1.0">
<title></title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<header>
<div class="main">
<div class="logo">
<img src="logo.png">
</div>
<ul>
<li class="active"><a href="#">HOME</li>
</ul>
</div>
<div class="title">
<h1></h1>
</div>
<div class="button">
<a href="index3.html" class="btn"></a>
<a href="index1.html" class="btn"></a>
</div>
</header>
</body>
</html>
well this is my code
anyone??
flask
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}">
you have to create a /static directory like you did for the html templates
OHHKKK
thanks
I'll try
and tell ya
do I have to create a static folder inside the templates folder or outside it??
Hi guys, I'm having issues accessing an iframe's element with js.
https://i.gyazo.com/90be3d527247096eba18c4598cf21147.png
I know I can switch context easily like this in chrome dev tools, but is there a way to do with JS?
I'm trying to run JS on elements in this iframe, but it can't find them
Youโre not allowed to do that for security reasons
ocol client=['10.0.2.2', 61340] path=b'/ws/chat/test2/'> took too long to shut down and was killed.
Application instance <Task pending coro=<SessionMiddlewareInstance.__call__() running at /vagrant/.venv/lib/python3.6/site-packages/channels/sessions.py:183> wait_for=<Future pending cb=[_chain_future.<locals>._call_check_cancel() at /usr/lib/python3.6/asyncio/futures.py:403, <TaskWakeupMethWrapper object at 0x7f6d6a70f408>()]>> for connection <WebSocketProtocol client=['10.0.2.2', 61344] path=b'/ws/chat/test3/'> took too long to shut down and was killed.
I get this error when using django channels with redis
lol
Hey guys, im working on an email service, ive made it so that when the get request for the inbox is made it makes the dom elements for each email
But they wont show until all are finished
Is there any way i can make them show up as they are made as it can take up to 20 secs to load them all in and display them which is annoying
If you wanna see what im talking about (and have a replit account) u can see it at repl.email
P.s repl it auth does not work on safari browsers
ok so im building a website is there a way to use python in replace of javascript??
kind of
but not really lol
u can use a lib to work with the html dom instead of js but its prolly easier to just learn js
dear backend web dev,how many languages do u know and what are they? i need some researches
hey does anybody here knows how to setup a wsgi_mod in flash to run PHP on windows ?
dear backend web dev,how many languages do u know and what are they? i need some researches
@grizzled violet a bunch. Just usepython. Best back-end language ever.
Can you please help me on this question I asked in stackoverflow.com https://stackoverflow.com/questions/63641162/how-to-set-a-place-holder-to-widgets-in-a-sign-up-view-forms-passwordinput-d
@native tide you look experienced can you please help me
It is about widgets
im not too experienced but i can try help
thank you
ive never worked with django tbh
i can help u with setting place holder values for divs in vanilla html css if that helps?
sorry bro never used django
really
So what do you know
do I have to create a static folder inside the templates folder or outside it??
@azure saddle at the same place where you created app.py, flask recognizesstatic/directory by default
ive worked with sanic, requests and flask mostly
to be honest im a bit better on front end but im not too bad on backend
the project im working on right now im doing the front end and my front is on backend cos were both abit better at those but on every other web project ive worked on i did front and back myself
nothing too complicated, like a web chatroom
Anyone done this:
https://github.com/mjhea0/flaskr-tdd
?
@azure saddle at the same place where you created app.py, flask recognizes
static/directory by default
@wind escarp Ohhkk bro thanks
@mystic lynx can you please help me on widgets
i don't even know what a widget is
or why you randomly decided to ping me and not someone else
Does anyone have tips for someone that is just starting out with learning Flask? Like good tutorial videos or guide websites? Would be much appreciated! :)
Does anyone have tips for someone that is just starting out with learning Flask? Like good tutorial videos or guide websites? Would be much appreciated! :)
@cedar schooner https://www.youtube.com/watch?v=mqhxxeeTbu0&list=PLzMcBGfZo4-n4vJJybUVV3Un_NFS5EOgX
Welcome to the first flask tutorial! This series will show you how to create websites with python using the micro framework flask. Flask is designed for quick development of simple web applications and is much easier to learn and use than django. If you are less experienced wi...
it's a playlist
Thank you so much!
Starting an internship soon and they asked me to get familiar with it
can anyone help me with django widgets
@flint breach Can you help me with this code:
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from django import forms
class CreateUser(UserCreationForm):
class Meta:
model = User
fields = ['username','email','password1', 'password2']
widgets = {
'username' : forms.TextInput(attrs={'class':'username', 'placeholder':'Username'}),
'email' : forms.TextInput(attrs={'placeholder':'Email'}),
'password1' : forms.PasswordInput(attrs = {'placeholder': 'Password'}),
'password2' : forms.PasswordInput(attrs={'placeholder':'Confirm Your Password'}),
}```
The username and the email placeholders appears but the others don't
Please help me
I didn't understand
to give it a class and then style it
@flint breach
hhhh
You are the only one who can help me ๐
look into the docs
Is this the right way to load an image in a jinja2 template?
As its not working for me ๐
Hi guys how are you all doing? Do you know how to change the width and height of an image with markdown?
In Django is there a way I can update a profile picture by clicking on the image like it is in Youtube
anchor link
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
@lament kraken you can check the course dennis ivy channel | pretty printed | corey schafer and you can also check the documentation and you can also check the django girls course which is not really recommended
@late fjord Yes but how do I do that with a form? Currently I am using a ModelForm and in Html I just have {{ form|crispy }}
what are you trying to do exactly
I am making a profile update page where a user can update his name and profile picture. I have a forms.ModelForm of the Profile Model with fields = ['image'] and in html I am just using this form
And what do you wanna do
Profile Model -
user = models.OneToOneField(User, on_delete = models.CASCADE)
image = models.ImageField(default = 'default.png', upload_to = 'profile_pics')
bio = models.TextField(default = "", max_length=500)```
Form -
class ProfileUpdateForm(forms.ModelForm):
class Meta:
model = Profile
fields = ['image', 'bio']
Currently the default for an imagefield is just a button with "Choose File", while I want it so I can click on the profile picture and change it like it is on Youtube or Discord
does someone know how i can automate a file run for flask?
I have a script i need to run with flask, automatically every 15 mins
@lament kraken you can check the course dennis ivy channel | pretty printed | corey schafer and you can also check the documentation and you can also check the django girls course which is not really recommended
@late fjord Bro i want good resource for front end and databases
@lament kraken sorry
I am following Corey and pretty printed, but i am haunting for frontend resources!
the ones of freecodecamp are not good i think
@twilit dagger I am thinking of a way
@twilit dagger check this
https://stackoverflow.com/questions/63641162/how-to-set-a-place-holder-to-widgets-in-a-sign-up-view-forms-passwordinput-d/63648561#63648561 it may help you
by giving it a class
and a background color
also removing all the borders
I know it is not the best solution, and also not the most practical
hey guys, can anyone explain me how does it work to link a django backend to a react app ? anywhere i look on google they talk about serializers, django rest, etc, i don't know about these i just have a portfolio with a form inside, as a react app that i want to serve from my django backend and get the form data to my database
Thanks @late fjord
you are welcome
How would I implement a python script into a web page?
What do you mean?
Do you wish to generate a web page?
Or do you wish to use python instead of JavaScript in your webpage?
just a webpage that would run a python script
say open it up and it runs the script?
you cant really do that directly on a webpage
You would have to program a script that would run the script on the server and return the outpu @native tide
you'd need something like IPython to bind the interpreter but idk
dont use Brython
use JS to emulate a vm running linux that loads python 3.8 and create an internal wifi connection to communicate the output with the client's webpage ๐ง
Why would you emulate
Just run it in a container on the server
That would be more efficient
Docker Container to be exact
crontabs are a Linux thing only
Yup, there's schtasks
awesome, ill take a look at it. thank you
Any time 
Or do you wish to use python instead of JavaScript in your webpage?
@native tide actually thinking about it could i do that?
because i have written my code in python
Not recommended. Especially with a ใใผใชใใ (CF8) recommendation against brython. I donโt know of another way and never used brython. Iโm throwing it out there as a โwayโ but opinion still stands
Depending on what you are doing, you could use a web framework to serve a page from a server, send requests from that page to the server, have the server process the requests, and either serve a new page or have the page change itself. More work but probably better but thatโs relative to what is your application
if you want like a 'online' IDE you should look at jupyter notebook
how can I have an online compiler for C / C++ and NASM in web?
I think https://repl.it already provides that @dawn heath
Repl.it is a simple yet powerful online IDE, Editor, Compiler, Interpreter, and REPL. Code, compile, run, and host in 50+ programming languages: Clojure, Haskell, Kotlin, QBasic, Forth, LOLCODE, BrainF, Emoticon, Bloop, Unlambda, JavaScript, CoffeeScript, Scheme, APL, Lua, Pyt...
how can i override serializer = AttendanceSerializer(y) this method anyone have idea?
Hello everyone,
Guys has anyone worked here on to do app using flask?
I need some help
Oh yes, many times. What's the problem
How in the
z-index gets fucked when you hover or sth?
looks like there's a missing background: white; on one of the elements
No idea, I just moved away from that design, so I don't have to deal with that mess anymore.
I have a new problem. This progressbar doesn't go away immediately. I think it's being display: none'd
or not, it's inner html is just being deleted. regardless, what is making it stay behind for so long? it's animated via css
I hate solutions where I just force the problem to go away
Does anyone know why I get this error when trying to run migrations? It is happening because of my custom users I think. I think this because when the custom user stuff is named CustomUser (and then other stuff on the end like serializer, etc.) it works fine but when I change it to something else like UserAccount it throws this error when trying to run the migrations.
Error:
AttributeError: 'SettingsReference' object has no attribute '_meta'
someone here knows django
How should I go about deploying my flask web app?
I have an ubuntu server but even after following multiple guides I have been unable to get it running.
hi can anyone tell me if the following syntax is correct in django template
{% if comment.comment_set.exists %} //comment is a self referencing model name
can anyone send me a link to the documentation where I can study this type of syntax in django
@tawny forum what problem are you having getting it running?
There's a document on various deployment options https://flask.palletsprojects.com/en/1.1.x/deploying/
I will do a bit more playing around and see what happens
considering moving the project to django anyway so probably doesn't matter
@tawny forum what does your deployment look like?
a gateway error usually means your backend isn't running where the reverse proxy / loadbalancer point of view
Haven't really used servers much, so haven't got a clue what your talking about
@shy sandal https://docs.djangoproject.com/en/3.1/topics/templates/
@queen sinew Thank you
@tawny forum well you'll have similar problems with flask or django because this part is similar for both
Probably yeah, guess I'll see how it all goes
good chance I'll be back here soon ๐
Just a question about arcade
i know you can use the collides_with_list to check for collisions
Is there anything that also tells you what face the object collided with
Or do i just have to set that check up myself
not that> familiar with arcade.....
but probably check for object -> object colllison
How to encrypt data in django?
@stable kite I suppose you're thinking symmetric encryption?
it would probably be easier for you to get help if you set out your usecase
oh, also #cybersecurity, depending on what you're looking for
@vestal hound what is usecase?
what exactly you want to do
what kind of data?
what encryption method?
who holds the keys?
etc.
and please stop pinging me
hello does anyone knows django?
hello does anyone knows django?
@nova nacelle just ask your question
i have created a user profile in the models and profile_pic in it. now after the signal and all, in the form(on the page), i want to take input of the profile_pic but want to be able to crop it before uploading. so, how do i do that.
i have created a user profile in the models and profile_pic in it. now after the signal and all, in the form(on the page), i want to take input of the profile_pic but want to be able to crop it before uploading. so, how do i do that.
@nova nacelle so you're actually asking how to crop pictures?
What's best; Ask User for their Stripe API/Pub key or setup Stripe connected accounts ?
The reason I haven't really done connected accoutns is I won't take any fee, so isn't it a bit pointless to send to admin stripe account > then to sellers stripe account
can someone help me with heroku im trying to push to heroku and i get thsi error
remote: HINT: This occurs when Heroku cannot detect the buildpack to use for this application automatically.
remote: See https://devcenter.heroku.com/articles/buildpacks ```
I am using django channels and I am a bit confused, what exactly ties the websocket consumer with the view itself?
re_path(r'ws/chat/(?P<room_name>\w+)/$', consumers.ChatConsumer), Is it because of how this path is for the websocket pattern, and if so how exactly does it work?
@modest scaffold go to: https://dashboard.heroku.com/apps/<your_app_name>/settings
click add buildpack and select python.
i think it will solve your problem
django vs flask
Not really a fair comparrison
django vs flask
@peak kelp from what I've read, Django has a lot of pre-built features compared to Flask. I personally use Flask for projects
How to encrypt users data in django
Does learning Django is enough for me to be able to do projects in free Lancer related to web developing ?
How to encrypt users data in django
@stable kite https://stackoverflow.com/questions/61546030/how-to-encrypt-password-before-saving-it-to-user-model-django
@past cipher I don't want to store password but other data that can be retrieved on user's request.
Never used Django, I use flask. But maybe check out this; https://docs.djangoproject.com/en/3.1/topics/signing/
should be able to encrypt/decrypt
@stable kite is it your intention to have all user data encrypted in your database?
@native tide Yes
can someone help me with deploying to heroku
i need someone to just guide me through this process
Have really no idea. Why do you want to go this route?
@modest scaffold The following guide has been tested and works for deployment to heroku:
https://github.com/mjhea0/flaskr-tdd
@wind escarp i use django
On the Deployment section I didn't see anything "framework-related", I might be wrong.
Flask is lame
hello to all
https://codepen.io/andrei-ionescu-the-reactor/pen/eYZRoGb
hi,
i have made a tabbed image gallery, but im curious how can i costumize it in 3 more ways:
- i want when i first load the page there should be a default big image
2.that line of text that should be bellow, but isnt event though its outside any div tag
3.i want the 4 images to be in line with the big image, this will probably help with the second point too
Thanks!
Flask is lame
Flask is not lame,:)
Hi guys this is sort of an employability question. I'm learning Flask, React, SQL and AWS. What's the other in-demand technology that I should learn to increase employability?
Ooh thanks, docker is a definite one. Git too.
Btw I'm confused on the meaning of 'software developer', from all the jobs I've seen, its just full-stack right?
I'm interested in being able to load a page in Django, and filter the results based on checkboxes, text-fields, etc. but I really want to speed up the filtering as much as possible.
I have a view right now that queries the users once, and then filter's the list based on what filters are enabled.
Is it better to filtering through the view/database or to query once and filter on the front-end with JS/JQuery?
Also, on the front-end is there a good tutorial on filtering those results with JS/JQ? I can't seem to find anything too great and a lot of results require Django-filters, which I don't want to use in order to keep control of the code.
Hello, I am trying to build my own pastebin that I can run on one of my computers. With a pastebin I mean a program that automatically creates a webpage showing the content of a file (such as dpaste.com). While this will be usefull for me, I'm mainly doing this to learn more about how to build my own web server. I know that I want to build this in python with Flask, but I have no idea how to start ๐ฆ Could someone give me some starting points or tell me where I can find help?
look for a tutorial for a basic flask project with inputs (i.e. the famous TODO List App) and then modify the principles used there to suit your needs.
Hello guys, I'm building a simple api with just few routes, I'm using flask restful and I'm looking for "the best" architecture to build it, I'm currently looking to use Blueprint with flask restful and I wanted to know if it is a "good choice" or if there is something else I should check. The implementation is not a problem just want to know if there is other thing I should be aware of when thinking about architecture an api with flask. thx !
Could anyone help me out with a query i have?
So i want to make a part of my website which is essentially just like chrome tabs. i want to be able to open the user to a view of search bar and input something which in term outputs a different view. Then they can also open a different tab to view something else. Im using dajngo so what are way s i could go about this
I am trying to create a custom user model and I want my users to select one of the four options in the registration page, but couldn't figure out how to import this in models.py. What do you suggest?
Does anyone know of any good web development tutorials for python? I have previous knowledge in PyQt5, tkinter, and pygame, but ive never touched django or flask
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...
these are good imo
I am a beginner at django too so they are clear and helpful
don't know about flask
Thanks!
Does anyone know of any good web development tutorials for python? I have previous knowledge in PyQt5, tkinter, and pygame, but ive never touched django or flask
@fierce shell DjangoGirls is the best in my opinion when I was getting started.
This is a really good flask tutorial if you want to use flask
Im using my own cookie storage and wondering whether I should check (and delete) expired cookies per authentication or have a queue that does it for me?
I was going to suggest Miguel
@restive kindle depends what your app does. If it's churning a lot in the background, just do auth, otherwise, schedule it so as to better utilize your cpu cycles
thanks
@frozen spear need more info, what framework
django
@frozen spear you don't any url for login so it gave error
you need to create forms for rendering a model
so i need to import them first
@stable kite
check the documentation link
@stable kite thanks man
welcome
i have kind of an x and y problem.
im using django and i was first trying to convert UTC to local time and show it to them but i couldnt figure out how to do that and now i am trying to convert UTC to US pacific and show that instead but i keep getting an error on line 34
the error is very ambigious python OSError: [Errno 22] Invalid argument
please let me know if you see it https://dpaste.org/p7Px
feel free to @ me
i have kind of an x and y problem.
im using django and i was first trying to convert UTC to local time and show it to them but i couldnt figure out how to do that and now i am trying to convert UTC to US pacific and show that instead but i keep getting an error on line 34
the error is very ambigiouspython OSError: [Errno 22] Invalid argument
please let me know if you see it https://dpaste.org/4trR
@gentle lark your link doesn't work for me
what OS?
okay, what exactly do you want to do?
what type is your input and what output do you expect?
i am a beginner in Flask and i am trying to do a login form for my site , i am confused between Flask-wtforms and flask-login , which one should i be using to make a login form ๐ค๐คฆโโ๏ธ
Thanks!
@fierce shell You can use the docs too . Django has one of the best documentations I've ever read , also Flask's docs are useful too!
@sage thistle I think you're confusing two different things. You can't choose between one or the other, however you can use both of them to create an authentication system for your app/service. Flask-WTForms is a great tool to help with form validation and can help create and use web forms with simple Python models. Flask-login provides user session management, i.e. stores the active user's ID in the session and lets you log them in and out easily, it lets you restrict certain views to logged-in users etc.
ooooo so i can use both of them @native tide
Yes, in fact you should if you're starting out rn and you don't want to code your own session management for authenticated users.
dw, good luck!
Can I return a page (with flask/quart), generate a file and then "push" that file to that page? something like (yes, I know this wont work as intended but it's just an example)
@app.route("/generate",methods=['POST'])
def generate():
data = await request.form
string = ""
for x in data:
string += x
str_hash = hashlib.md5(string.encode()).hexdigest()
return f"Processing File {str_hash}.zip"
# do stuff to generate the file
return send_file(f"{str_hash}.zip")
or will I need to do some JS or some other scripting?
Hello, I am trying to build my own pastebin that I can run on one of my personal computers. With a pastebin I mean a program that automatically creates a webpage showing the content of a file (such as dpaste.com). Having never done any web-development, I'm a bit lost. Could I simply copy the file I want to share in the directory of my webserver and handle the rest with Flask?
did anyone ever get the duration in django to work? I am now correctly parsing and converting the data in the form to a python timedelta before using form.save yet It still breaks with unsupported type for timedelta microseconds component: str
whenever i i run my django project with DEBUG = False it can't seem to find some static files
But it loads other static files. When debug = true its fine can someone help with this
looks like I can do something with https://flask.palletsprojects.com/en/1.1.x/patterns/streaming/#streaming-with-context
does anyone have experience with deploying django to heroku that could help me out pls
Can I return a page (with flask/quart), generate a file and then "push" that file to that page? something like (yes, I know this wont work as intended but it's just an example)
@app.route("/generate",methods=['POST']) def generate(): data = await request.form string = "" for x in data: string += x str_hash = hashlib.md5(string.encode()).hexdigest() return f"Processing File {str_hash}.zip" # do stuff to generate the file return send_file(f"{str_hash}.zip")or will I need to do some JS or some other scripting?
@fair tide once returned, code below won't run
you could return once, and send file as an argument
"yes, I know this wont work as intended but it's just an example"
so I want to generate a page, send it to the user saying "Your file is being processed" and then when its finished processing, send that file
probably best to use JS to tell the user the file is being processed, call the route in JS too and wait for it to be processed & then redirect
I did find "streaming with context" which might be able to do what I want (well at least update the page to say "Your file has finished generating, it can be found at this link")
honestly I'm not sure, never used that before
had to look up the quart variant, but it looks like it worked
Can anyone suggest me best resource to learn django. I am a beginner in django and build very few stuff in it.
Maybe random but, is there a exact step by step to make a module show in a app/admin? What files do you make in order?
@past cipher This might be a dumb question, but I'm quite new to discord and i have no idea how to post a code snippet like that? Is that just a picture?
are there downsides to building HTTP/S urls with f-strings (other than backwards compatibility)?
injections
its not really a issue
but f strings are generally slower and remove compatibility
Do you guys recommend any reading material for learning Docker?
pols = Politician.all()
issues = set(i.title for i in Issue.all())
res = []
for pol in pols:
missing = issues - set(i.issue.title for i in pol.stance_set.all())
if missing:
res.append(dict(name=pol.name, missing=list(missing)))
```how would I do this without the N+1 problem?
pols = Politician.all()
issues = set(i.title for i in Issue.all())
res = []
for pol in pols:
missing = issues - set(i.issue.title for i in pol.stance_set.all())
if missing:
res.append(dict(name=pol.name, missing=list(missing)))
```how would I do this without the N+1 problem?
@dapper tusk huh.
are those Managers?
the first two lines
ye, think of it as Politician.objects.all()
I need to do quite a bit of nonsense on each of the all queries, so I have it as a helper
I suppose Stance is a third model?
ye
Stance has a foreign key to issue and politician, and I need to find all politicians which lack a stance on any issue and put them in a list
Stance has a foreign key to issue and politician, and I need to find all politicians which lack a stance on any issue and put them in a list
@dapper tusk HM. I find it hard to visualise doing this with the ORM
(incidentally, since you describe it that way, is Stance a through model for the other two's M2M relationship?)
also, judging from your code, you don't just need to find the politicians, right?
you need the actual issues...
also, judging from your code, you don't just need to find the politicians, right?
@vestal hound because I believe this wouldn't be difficult
annotate with count distinct of issues by politician and filter on that
def profile (request):
context = {
'post': Post.objects.all()
}
return render(request, 'users_app/profile.html', context)
how to can i display the count of all the posts of the specific user?
or am i doing it very wrong?
@lapis spear Post.objects.all().count()
Hi
I have a model named MyUser that inherits from AbstractUser and i am extending it.
Also i have 2 models
One instructor. That they can write posts
And the other one is Student
I need to authentice both of them in the server using MyUser model.
How do i connect these 2 models to the MyUser
I used OneToOne Field but it throws this Error
@lapis spear
Post.objects.all().count()
@vestal hound it will get all post count of all user but i want something like count all from Post where author == user

