#web-development
2 messages · Page 154 of 1
linux but nginx
did you try this User=www-data?
it doesnt change anything setting it to that
i have no other options i searched and i got these. hope you can find it.
lmao thanks anyways yeah ive been working on this one issue for a while
does anyone else have experience with sock files and gunicorn?
Hey, what package managers are suitable for a Django project on Windows to keep track of JS/CSS libraries? Bootstrap, jquery, etc.
Currently my entire python project is managed through virtual environments and git, but of course PIP was not designed for the external HTML'esque libraries.
If you're okay with learning a syntax that's kinda different from both JavaScript and HTML - Pick React.
If you want to stay with something that's more like normal HTML - Pick Vue.
@solar ridge I dont usually use package managers I just either download the files to a directory or link to a cdn
Things like npm or yarn (a wrapper for npm) are the best ways to download js packages
You'll need to have node.js installed, and if you run npm init, it'll autogenerate a package.json that sorta like a Pipfile or a pyproject.toml
May I ask why? Using things like npm makes it easier and compresses it, does it not?
@calm plume I may have used it in the past but I've never really had the need to since most of the time the only packages I use is bootstrap and jqueyr
jquery
hey @calm plume do you know anything about setting up django on a production website?
No, not really. I know Django basics, but I haven't gotten too far into it.
Check out https://git.pydis.com/site, it's a Django website in prod
Hi guys!
Is there a way to grab the text content of any generic webpage, with python (beautifulsoup)?
not in general
because you can’t run JS
even using a webdriver like Selenium?
Yummi. Thanks.
then yes
Thanks @summer grove & @calm plume
Hello, I've got an issue with django and URLs taken from database. I have code as follows:
<a href="https://{{ finding.permalink }}">website</a>
Within finding.permalink there is specific URL for website taken from database. In this example, urls starting with www. like www.google.com will let you go to google website, but when url in database starts with http:// or https://, it will result in incorrect url appearing on the website (http://http://www.youtube.com). I already tried googling this issue, but I'm unable to find anyone with similiar problem. Earlier I have used <a href="{{ finding.permalink }}">website</a>, but that resulted in user being redirected to subpage of my website.
How can I solve this issue?
Hi guys
in that case, how can you identify page text content from all the rest, without using class tags, etc? the purpose is automatic summarization
u solved it?
Use get_source i think it is from the webdriver
Then use regex to loosely remove all the html tags
Probably the easiest method
@nova storm Nope
How can I can change a background colour of website in (HTML)
In your css file, you can apply background-color to the html tag. Example:
html {
background-color: "#0a2540";
}
Will it wil change the colour of the full page
thank you. I'll do that then.
Yes
I use Django and Django Rest Framework to create simple REST applications. I know the basics. But I have no clue what bigger than just simple CRUD applications I can make.
I'm looking for inspiration guys.
I have no idea what projects I can make that would keep my motivation to learn alive.
https://stackoverflow.com/questions/67422152/how-do-i-force-celery-apply-dynamic-times-chained-tasks
I have no motivation and eagerness to study Django and Django Rest Framework documentations when I don't have any bigger projects in mind.
should i use flask with react or is it not worth it? I mean i've been trying to set it up and its a pain
React is great, but idk how it is with Flask
I would say Django Rest Framework or FastAPI is better than flask
To work with React
Flask is better recomended for beginners in python frameworks though
Purely out of leaning experience
I like how much control i have with flask vs other frameworks
how though?
They are battery-included frameworks
A lot of stuff is already tuned for you.
Helps to make twice less errors, and having twice better quality
i currently use it with vue so i don't see the problem
Django is good with premade admin site and good ORM for databases, which works great for migrations
FastAPI has self generated api wikis out of the box. Which helps to coordinate with front enders easier.
What is vue like vs react. I know i should be using google for this sorry. Also what is it like with required assets? Like with react there was aton of files that had to be there and some config i had to setup
what do you mean by required assests?
what am i looking for specifically
just all of them
here*
i like having my project very clean
but uhm, i think it literally depends on what you add
i'm a really big fan of djangorestframework-simplejwt, because they make using DRF with authentication tokens really easy, and it allows for things like users accessing an api only if they are authenticated
I am making an object that would take a request object from various web frameworks and standardize it a bit. Many frameworks have a url method to get the full URL of the request. How could I get this from a Django HTTPRequest object as well? Didnt see anything in the docs.
To anyone already typing "why are you doing this, just dont" or anything like it, I am doing it mostly as a fun little project because why not, so please dont go there.
Please @ me when responding.
now this is not a web dev question more of a hosting in heroku question
basically i completed a project which is a telegram bot which requests like 300+ websites and returns data to telegram and now id wanna host it in heroku but this server should run 24 x 7
so im not sure which plan to decide upon
Hey so im trying to find a simple django api with sqlite tutorial. Any recommendations?
djangos documentation is really good
Thats what im currently reading, thanks!
If you're looking to make an API, use django-rest-framework:
https://www.django-rest-framework.org/topics/documenting-your-api/
Pretty printed on youtube does good videos on it.
Django has sqlite3 out of the box, so you just need to learn how to use the django orm (from the docs) 🙂
Django, API, REST, Documenting your API
so i have an editable, searchable table that auto populates from a csv, how would i make it so if a user edits a cell then clicks the button in the top right, it applies those changes to the csv
Anything on this?
I confirm. I've been trying to get the hand at Flask-Restful, and botting up the Swagger UI is such a pain. I'm thankful FastAPI exists.
I'm saying that and my first API under Flask was getting the hand on two basic routes by simply using jsonify and the requests package to handle payloads and responses
I meant to ask about Flask-Migrate. Supposing I have a Flask app using SQLAlchemy with a MySQL database, an __init__.py file in which I declare the create_app() factory function, which initializes the database and a Migrate object, does that mean I can use flask db init right after I lauch the app, or do I need a manage.py file?
i have the same setup and it works without the manage file
i'm trying to add a search bar in my website does anyone know how to do that
Depends on your website content
What kind of code does it have?
HTML?
rn i just want the search bar to appear and reroute to a blank page or something
yea
it has html
and css for the style
On whichever page where you want the search bar
ok thanks
what is Blogpost.objects.filter
when I put it in my code it says blogpost undefined
i've seen it on a couple of other different videos
Flask-admin's view and edit function are usually like this
admin.add_view(ModelView(User, db.session))```
But how can I add like a `@login_required` thing so only user can see it?
https://flask-admin.readthedocs.io/en/latest/introduction/#authorization-permissions theres a couple ways of authenticating
will i get help in javascript here too?
not the best place, but I'm sure someone here knows it. something like https://discord.gg/code would be better though
can someone thats good at django please help me, I am unable to fix an issue and I have used every fix I can find on stackoverflow etc
manage.py migration --run-syncdb (doesnt work)
manage.py makemigrations (doesnt work)
manage.py migrate (doesnt work)
what hosting service does the python site use?
im making an assigment submission webapp for uni project
i need to copy paste the content of an upload to google and fetch the relevant links and display it on mywebsite
can i do this with beautifulsoup?
yup
beautifulsoup or xpath for web scrapping works
but how do i sendkeys?
why would you need sending keys?
like a student uploads a pdf
text is extracted from it and it ios compared to documentts submitted by his classmates for plagiarism
so i also want the content to beasearched over the internet
scratching head
I have no idea how this 'pdf uploading' is supposed to work
btw, you could check perhaps Google API
its simple
perhaps it has what you want
ill send a snip
perhaps you are speaking about 'selenium' level functionality
it can imitate actions of a real user
so we cant do it with bs4?
nah, bs4 is meant just to extract results
see this is a page from my webapp ,the teacher can view all the submission of students she wil;l get alist of smimlar uploads
from DOM mess of a resulting page to some format you need
you can check whatever you wish, if it would be uploaded first at your backend server
depending on where you want to upload your pdf
if to your own django, then it can be done just with internal django tools
if to not your own site, some foreign service, then possible need for selenium
if to some foreign API, all you need a regular request with JSON body inside
no
see if u were my teacher
and i have to submit to u some case study
to check if i have copied from the internet
u would copy paste the content of the pdf to google search bar to see if i have stolen it
i am trying to do that
then all you need
uploading pdf to your own django web site
it can be done without seleium or anything else
just use Django available tools
and then make request to necessary google url
i have done this
with content you wish to find
and then beautiful soup results out of it
or actually better connect Google API
and make request to it
it will return to you JSON results
it would be nicer than beautiful soup
because you would not be blocked by captchas
i hv very less time in hand
i hv selenium experience
and bs4 only , but not with any API or django requests
no need to use Selenium in this situation in my opinion
so with django u can send keys?
just make
import request
request.get(f'{GOOGLE URL CONTAINING WHAT YOU WISH TO FIND}')
it will make request without key usage
or as I said find Google API
and learn how to use it
interface to communicate with it, will be the same almost
it will return just nicer results, which you don't need to parse with beautiful soup
tysm
request.get(f'{contents of thr pdf}')
will work?
Link to my programming Video Library:
https://courses.LearnCodeOnline.in
Pick best UI color for your projects:
https://UIColorPicker.com
Desktop: https://amzn.to/2GZ0C46
Laptop that I use: https://amzn.to/2Goui9Q
Wallpaper: https://imgur.com/a/FYHfk
Facebook: https://www.facebook.com/HiteshChoudharyPage
homepage: http://www.hiteshChoudhary.co...
@inland oak what do you think of this?
11 minutes to tell 10 lines which could be written in example in 10 seconds
not liking to waste my time watching videos.
Hi!
I’m organizing a one day free online workshop for women and am looking for volunteer mentors.
It’s a beginner workshop where attendees follow tutorials and mentors answer their questions, help with the tasks if they are stuck etc. https://djangogirls.org/porto/
A link to register as a mentor: https://forms.gle/b6x2Gzw4F87oJqXi9
Register here if you'd like to mentor in Django Girls Porto - the one day programming workshop for women.
More information about Django Girls Porto here: https://djangogirls.org/porto/
import requests
from bs4 import BeautifulSoup
URL = 'https://www.gamebillet.com/mortal-kombat-11-standard-edition'
headers = {"User-Agent": 'For safety purposes'}
page = requests.get(URL, headers=headers)
soup = BeautifulSoup(page.content, 'html.parser')
title = soup.find(id="productTitle").get_text()
price = soup.find(id="priceblock_ourprice").get_text()
converted_price = price [0:5]
print(converted_price)
print(title.strip())
Can someone help me pls, I want that it checks if the product/game is aviable
hi
hi
which python web framework you know ?
Hi, I'm making a software in Python which makes PDFs into Audiobooks. I wanted to use it for my blind grandpa so that he can read any book he wants to. I need help with 3 things.
`1- I'm using a module called Tika and as you may or may not know, when made into an exe, it requires Java to run. Now I don't want my friends and whoever else installs it to also require Java, I wanna make it look professional. So is there an alternative?
2 - If I use gtts, it does do all languages but the voices suck and pyttx3 sapi5 needs users to install voices and go into the windows registry to change/ add them. I can't exepect others to do the same. So i want to add good tts voices for it.
3 - Deployment: This one's tough. I figured out how to make an exe, but I want it to be a webapp. But making a webapp is tough(have tried) and i need a better quide how to make one.
If anyone can help me with these 3 issues or give advice, you're more than welcome
Hi. I'm looking forward to mine PDFs (without using Python packages as PyPDF is a bit outdated and I don't want Java to run as a backend either) and so far there's not a universal solution that works well for PDFs.
My strategy was extracting text, images, formulas into separate folders but the mining can act differently depending on the pdf version. So if anybody has dug further on pdf structure research I'm interested too
What u mean, Im a noob and don't know what I am doing
can u send me ur code?
I don't have anything implemented yet that's the thing
😦
in django, do you use a single app with everything or split into multiple apps
in general, a single app for one db model
or more like.... one app for one db model that matters
ask yourself this... will be those objects different in db model, views, urls, testing, programming logic and etc
if yes, you are definitely needing separating them to different apps
Golang it's good language?
I am trying to host my flask website how do I get it to run on https without the warning of this link might not be secured
def get(self, request):
if self.request.user.is_authenticated:
return redirect("/")
return super().get(self, request)
i have following line in FormView
can i redirect authenticated user in more convinient way
anyone?
idk for what you are using that view but for example the Login cbv has an attribute called "redirect_authenticated_users" and if that is True it will redirect
im using my own CBV with FormView
ok then i would make an decorator or mixin or if do it like those:
https://stackoverflow.com/questions/23922598/class-based-view-redirect-if-logged-in-else-render-template/23922822
okay illtry
Flask, and various other frameworks, have a url attribute for request objects. What is the Django equivalent?
How do I add a confirm_password field to my CustomUser model?
class CustomUser(AbstractUser):
pass
Flask? Django?
It's Django
I did py class CustomUser(AbstractUser): confirm_password = models.CharField( max_length=100, blank=False, null=False) But it says this ```You are trying to add a non-nullable field 'confirm_password' to customuser without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
- Provide a one-off default now (will be set on all existing rows with a null value for this column)
- Quit, and let me add a default in models.py
Why would a password need a default? Passwords shouldn't be default
where would i add an alert to this to show the value of table data
<script>
$(document).ready(function(){
$("#sub-jq").click(function(){
$('#inv-tab tr').each(function(row, tr){
TableData = TableData
+ $(tr).find('td:eq(0)').text() + ' ' // Task No.
+ $(tr).find('td:eq(1)').text() + ' ' // Date
+ $(tr).find('td:eq(2)').text() + ' ' // Description
+ $(tr).find('td:eq(3)').text() + ' ' // Task
+ '\n'
});
});
});
</script>```
You don’t need to have confirm_password? It would be automatically assumed.
It’s <img src=“file location” width=x height=x>
Where x is what you want the size to be
In my models.py file here```py
from django.db import models
from django.contrib.auth.models import AbstractUser
Create your models here.
class CustomUser(AbstractUser):
confirm_password = models.CharField(max_length=100, default='')
class Loan(models.Model):
APPROVED = 'APP'
REGISTERED = 'REG'
EXPIRED = 'EXP'
REQUESTED = 'REQ'
REJECTED = 'REJ'
STATUS_CHOICES = [
(REGISTERED, 'Registered'),
(EXPIRED, 'Expired'),
(REQUESTED, 'Requested'),
(REJECTED, 'Rejected'),
(APPROVED, 'Approved'),
]
borrower = models.ForeignKey(
'CustomUser', on_delete=models.CASCADE, related_name='borrowers')
lender = models.ForeignKey(
'CustomUser', on_delete=models.CASCADE, related_name='lenders')
date = models.DateField(auto_now_add=True)
status = models.CharField(
max_length=3,
choices=STATUS_CHOICES,
default=REQUESTED
)
def str(self):
return f'#{self.id}'
How do I make it impossible for them not to be the same user?
Cuz in the api page In the HTML form I can set them to be the same. I don't want that.
It shouldn't be possible
Did you get it to work?
yeh
Ahh nice.
@native tide you need to set unique_together
where?
class Loan:
class Meta:
unique_together = ['lender', 'borrower']
this will set the constraint at the DB level
i am making a website and i want an image as a background but when i open the live server it is not appearing
hmmm ok
can any1 tell how i can fetch the href tag
u mean this
ya
It doesn't work
just type a
theres a link in it not #
didnt work
like i want the link that belongs to that dv tag
u can add it on ur own
i wrote that # for my code
bruh
it will be empty
if u type a
then enter
@green snow
m stuck since morning,i just want a script that returns top 5 links of a google search
m getting none
listen call me and screenshare
then type a then enter
yaa ok
on vs code
gimme 2 mins
ok
bruh
i sent u dm
Actually pretty newb question. Is there any way to sort IntegerField in template?
Like, i have a bunch of numbers 20, 38, 14, 43 in db. And wish to render it in template by decrease => 43, 38, 20, 14
Django could do that with any filter or i have to filter it with python before render in views?
Lol, nvm, i could use order_by in query. Sry for stupidness. =|
In flask stringfield, when i try to input a name or a number, there's always a few recommendation for me to input, is there any way to block it?
you can try something like this
{{ form.var(autocomplete="off") }}
ok ok
there might also be some css to do something similar
and if you're using chrome, it tends to ignore passwords so you can try
autocomplete="new-password"
instead
im going to try it rn
It worked! 😃
how possible is it to be learning two languages at the same time (php and python)
or should I really focus just on one
perfect! 🙂
i would probably just focus on one until you feel fairly comfortable with it
why learn PHP though 😉
Here in my component https://pastebin.com/rUb2ica9
I want to get data from a backend api
django rest api
And If you look in the renderBorrower method, I try to return this ${borrower.first_name} ${borrower.last_name}
But It gives me this errror: loansList.jsx:20 Uncaught TypeError: Cannot read property 'first_name' of undefined at LoansList.renderBorrower (loansList.jsx:20) at loansList.jsx:63 at Array.map (<anonymous>) at LoansList.render (loansList.jsx:55) at finishClassComponent (react-dom.development.js:17485) at updateClassComponent (react-dom.development.js:17435) at beginWork (react-dom.development.js:19073) at HTMLUnknownElement.callCallback (react-dom.development.js:3945) at Object.invokeGuardedCallbackDev (react-dom.development.js:3994) at invokeGuardedCallback (react-dom.development.js:4056) at beginWork$1 (react-dom.development.js:23964) at performUnitOfWork (react-dom.development.js:22776) at workLoopSync (react-dom.development.js:22707) at renderRootSync (react-dom.development.js:22670) at performSyncWorkOnRoot (react-dom.development.js:22293) at react-dom.development.js:11327 at unstable_runWithPriority (scheduler.development.js:468) at runWithPriority$1 (react-dom.development.js:11276) at flushSyncCallbackQueueImpl (react-dom.development.js:11322) at flushSyncCallbackQueue (react-dom.development.js:11309) at scheduleUpdateOnFiber (react-dom.development.js:21893) at Object.enqueueSetState (react-dom.development.js:12467) at LoansList.push../node_modules/react/cjs/react.development.js.Component.setState (react.development.js:365) at loansList.jsx:10
And the weird thing is....
When I spam the refresh button It works sometimes
And sometimes gives me an error
because componentDidMount runs after the component has been rendered (and painted to the screen). Therefore at the start this.state.loans is empty and you have no data to .map through - so it's undefined
when you're spamming the refresh button, you're just hoping that your component made an API call before you refresh.
so do I put the function in componentDidMount?
to fix this just add a conditional to your JSX, like:
{this.state.loans && this.state.loans.map(...)}
but note that this.state.loans has to be a falsy value at first, (you have an empty array - I don't know if that's falsy (I think it is) but let me know)
no, because as I said, componentDidMount only fires after the component has been rendered. You are trying to .map through state before componentDidMount has fired.
so your state will be empty.
Yes it is falsy
By any chance, do you know how to make a loading screen?
before everything renders?
you can use a ternary operator:
{this.state.loading ? <LoadingComponent /> : this.state.loans.map(...)}```
where `LoadingComponent` is the loading comp.
that simple?
well yeah, you just have to handle the loading state and making the component (or importing it from some comp. library)
all sorted now?
show us the code
<tbody>
{this.state.loans &&
this.state.loans.map((loan, id) => {
const { id: pk, borrower, lender, amount, status, date } = loan;
return (
<tr key={id}>
<td>
<b>#579{pk}A</b>
</td>
<td>{this.renderBorrower(borrower)}</td>
<td>{lender}</td>
<td>${amount}</td>
<td>{this.renderStatus(status)}</td>
<td>
<i className="far fa-calendar"></i> {date}
</td>
</tr>
);
})}
</tbody>```
and what's the error
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.
same one
can't read property first_name of undefinded
in renderBorrower(id) print your state.users
this.state.users.find((user) => user.id === id); is not returning anything
okay now
the whole thing is successfully rendered as it should...
I also printed the users as you can see
but lets refresh the page
Now this
because [] is truthy
It is?
!e print(bool([]))
@drifting furnace :white_check_mark: Your eval job has completed with return code 0.
False
Hmm it doesn't seem so 
Oh yeah I remembered
that's python, this is JS
You need to check if it's equal to [] to check if it's empty, not just boolean it
Im confused
make your initial state this.state.loans equal to null so it's definitely falsy
then your state will be mapped through only once the state is available
because apparently [] is truthy
Same sort of error
but this time it's null instead of undefined
hi
if you go here
it takes you to a directory thing
i use infinityfree for hosting
how do i fix it
are you sure this const borrower = this.state.users.find((user) => user.id === id); returns something
oh I see
{this.state.loans &&
this.state.loans.map((loan, id) => {
const { id: pk, borrower, lender, amount, status, date } = loan;
return (
<tr key={id}>
<td>
<b>#579{pk}A</b>
</td>
<td>{this.renderBorrower(borrower)}</td>
<td>{lender}</td>
<td>${amount}</td>
<td>{this.renderStatus(status)}</td>
<td>
<i className="far fa-calendar"></i> {date}
</td>
</tr>
);
})}
wrap the code on the right side of the conditional in parenthesis ()
this you mean? jsx {this.state.loans && (this.state.loans.map((loan, id) => { const { id: pk, borrower, lender, amount, status, date } = loan; return ( <tr key={id}> <td> <b>#579{pk}A</b> </td> <td>{this.renderBorrower(borrower)}</td> <td>{lender}</td> <td>${amount}</td> <td>{this.renderStatus(status)}</td> <td> <i className="far fa-calendar"></i> {date} </td> </tr> ); }))}
Still doesn't work.
help
so that the parenthesis are on the same line as the conditional
and if it's not that then I don't know what the issue is
can someone help me, when i go to http://cloudzeta.ml/ i get a directory thing, but when i go directly to http://cloudzeta.ml/zeta/ it works
how do i remove the directory thing
and make http://cloudzeta.ml take me to http://cloudzeta.ml/zeta/
is there any way to link css files from a child template in django
sorry i dont know if child if the term
i have base.html with base.css linked in the <head> tag
i extend base.html from home.html and i want to link home.css in the same <head> tag
new solution..
just telling people
to go to /zeta/
lmao
oh well im too dumb to fix it
@toxic echo if you extend the html file where you want the css from the base then you dont need to do anything. Its already inheriting. So if you link it in the css in the base.html its on all html files where you extend with base.html
Is it ok to store sensitive info in the session?
in the session cookie?
Yes
what sensitive info are we talking about?
The user's token
yeah that's fine
Ok thanks
cos unfortunately wordpress runs 40% of the web ;p
does anyone know why this error shows I turned on allow all cookies on chrome
but it still shows the same message
yeah that would work, but i dont want to add css that i dont need on every page
@toxic echo You can make a block called css and then link on every page you need another css add it there and the one from the base for example gets overriden
ohh i will try that, sounds good
how can I choose specific permissions per method on a modelviewset?
this is my PostViewSet create() method
def create(self, request):
permission_classes = [permissions.IsAuthenticated]
try:
user = User.objects.get(username=request.data["author"]["username"])
except user.DoesNotExist:
return Response({"message": "user with username does not exist"})
post = Post(
body = request.data["body"],
author = user,
likes = 0
).save()
return Response({"message": "Your post has been saved"})
however i can still send post requests even if i'm not authenticated
i want to the user to only be authenticated on posts requests, but get requests should not need auth
IsAuthenticatedOrReadOnly
wow didn't think it was that easy. thanks!
how do I inherit from multiple classes/prototypes in JS, kinda like multi class inheritance in python, what's the syntax for it, I am thinking about something like this:
class someClass extends (Parent1, Parent2) {...}
Does anyone know how to return JSON errors when there is an authentication error on Flask?
It's returning HTML and my JSON client is breaking
there's no multiple inheritance in JS
(basically)
you can implement multiple interfaces though
well... that's inconvenient as hell, is there an alternative?
why do you want multiple inheritance
because I want to create a child class that inherits methods from 2 parent classes
yes, that is what multiple inheritance is
but what I'm asking is
why aren't you using a pattern more appropriate for JS
for example...composition?
JavaScript isn't isn't a class based object oriented language.
what is composition?
that is something you can Google
If you're using JavaScript, use JavaScript, not Python.
indeed
honestly, prototypical inheritance is weird for most people though
it's interesting, but
But it's not the way here
I mean, yes, classes in js are just a syntactical sugar wrap around prototypes
it's like giving needles to drug addicts
Does anyone know how to return JSON errors when there is an authentication error on Flask?
It's returning HTML and my JSON client is breaking
Flask RESTFUL btw
hey, uhm, how do I implement something to python's __iter__ and __next__ methods in a javascript class to make it support iteration?
look into Symbol.iterator
ok thanks
Hi guys, I need help with a project.
I've not time to work with and it needs to be updated.
https://github.com/joke2k/django-environ
If somebody is interested to help, please write me.
Hey can anybody help me to understand how can we turn website to a company
Make it an NFt and sell for $1billion, the end.
Collection:
[{
"_id": 1,
"ImageUrl": "http://domain.com/image.jpg",
"Age": 28,
"Gender": "M",
"Hour": 3,
"CollectionID": "testcollection1,testcollection2",
"Date": {
"$date": "2021-05-04T00:00:00Z"
},
"MatchedTimeStamp": "2021-05-04 15:01:44.006",
"FaceCode": []
}]
Code:
from pymongo import MongoClient
client = MongoClient('localhost')
db = client.database
collection = db.collection
collection.find_one()
Output:
$ b'{null}'
pymongo collection.find_one returns null
how to solve this issue
?
What is better for web development:Python or Typescript?
i would say Python for back, Typescript for front ;b
ok
I am getting error R15 and R14 while deplying a flask web app using Heroku. The app has Sklearn, Pandas and Flask as imports, so i suspect I have exceeded the maximum memory offered by the Heroku free plan. How do I go about it now as the plans dont metion storage. PS: its a ML app
Anyone who have some information how I can get users to login with discord on my website?
hello what is the best ressource to learn web dev in python
Can anyone suggest some good Django tutorials?
The official one is wonderful
Under the documentation tab of their website, there's a section for the tutorial
thanks man
Hey can anyone help me on how to disable those HTML pop up validators.
I am actually using bootstrap classes on the flask validators and don't want those additional validations.
can you show the html for the form structure?
but in essence, you basically need to add the novalidate attribute to the form
does javascript have keyword arguments like python?
Don’t set the field as required on your form
yes why not
Hello people
my css file is not working with my react app no idea why
trying to style bootstrap component
any idea what might be wrong?
Can you share the relevant parts of the css file?
it consists of these 10lines only```css
.card{
width:50%;
float: none;
margin-bottom: 10px;
margin-top:50px;
}
@media (max-width:991px){
.card{width:50%}
}```
Can you try sticking a background color on .card? Just to see if it applies?
ops my bad forgot one to set margin to auto 😮 sorry
Thank you so much for your time
Good luck with your app!
ok guys what does this mean>
I am using reactjs and Django Rest Framework so, whenever I make a request to the api using fetch or axios it shows data on the browser’s network section and I don’t want that data to be shown how can I approach this problem
I want my website to have somethign like a chat option, but what is the best way to update the chat
Should I use react or is there an easier way with flask
hello everyone.
I need to compare datetime field to datetime now, if the difference is equal to 10 minutes i need to send email.. Best way to do it?
google the error, you just need to specify it in settings.py file
got nothing when i googled it
but i solved it
thanx
Is anyone here good with requests?
What's the question
So
i'm trying to get access to a page, but it has a js loading screen
meaning that when i try to request the site
it returns the info about the loading screen not the actual site
heres my code
url = requests.get("https://robertsspaceindustries.com/spectrum/community/SC/forum/4/thread/weekend-playtest-fleet-week-expo-halls-javelin-tou/4006567")
soup = BeautifulSoup(url.text, 'lxml')
print(soup.prettify())
theres the link
you can see it has a loading screen
you'll need to intercept requests. If you don't know how to do that then you'll need to use puppeteer or selenium. The site might have security for it though.
I own a service for this specific case if you'd like I can send it to you. Can do up to 1000 requests for free and it does render JS as well.
Looking at the site the whole thing uses React.
Is it impossible to web scrape then?
How does your service work
And is there a good tut for puppeterr/selenium
OKay so just download theses?
are they packages?
I looked up some answers
from bs4 import BeautifulSoup
from selenium import webdriver
driver = webdriver.Chrome()
url = "https://shop.nordstrom.com/c/womens-dresses-shop?origin=topnav&cm_sp=Top%20Navigation-_-Women-_-Dresses&offset=11&page=3&top=72"
driver.get(url)
soup = BeautifulSoup(driver.page_source, 'html.parser')
driver.quit()
print(soup.prettify())
this is what i got from stack overflow
but when i try this, it tells me i dont have the chromedriver directory
You'll need to download the webdriver
sorry im pretty slow haha
i downloaded chromedriver.exe
how do i put it in my path?
alright good
Starting ChromeDriver 90.0.4430.24 (4c6d850f087da467d926e8eddb76550aed655991-refs/branch-heads/4430@{#429}) on port 9515 Only local connections are allowed. Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe. ChromeDriver was started successfully.
this is my cmd rn
Did you figure out how to put it in your path?
you don't run it
put it into
C:\Windows\System32
drag and drop it onto there
then try and run your program
okay so it ran
and like a window opened up of the
website
but it still got info of the loading screen
well yeah that will happen
cause the loading screen takes a bit
so
from time import sleep
sleep(5)
or something
sleep 5 where though
driver = webdriver.Chrome()
url = "https://robertsspaceindustries.com/spectrum/community/SC/forum/4/thread/weekend-playtest-fleet-week-expo-halls-javelin-tou/4006567"
driver.get(url)
soup = BeautifulSoup(driver.page_source, 'html.parser')
driver.quit()
print(soup.prettify())
You should wait for an element but that might be beyond your scope atm
and after the driver.get
holy shit
it worked
wait
by wait for an elemen
you mean like wait for a specfic class to appear or something?
thank you so much bro
Okay, i prop would need a bit more knowledge about how this driver stuff works
but would it kinda be like (sudo code)
While True: Try: Get Class then quit driver Except: pass
or something
Nah it would be a method you call and it blocks the program until it either gets a response or timeouts.
Look at some tutorials or the docs for selenium
You too!
def search(request):
context_dict = {}
query = request.GET.get('q')
if query:
results = Sklep.objects.filter(miasto=query)
if results.count():
context_dict['results'] = results
else:
context_dict['no_results'] = query
return render(request, "index.html", context_dict)
template.html
<form class = "d-flex " method = POST action ="{% url 'search_venues' %}">
{% csrf_token %}
<div class = sbar>
<input class="form-control me-2" type="search" placeholder="Search" aria-label="Search" name="searched">
<button class="btn btn-outline-success" type="submit">Search</button>
</div>
class Sklep:
miasto = models.CharField(
max_length=200,
)
nazwa = models.CharField(
max_length=200,
)
adres = models.CharField(
max_length=200,
)
def __str__(self):
return self.miasto +", "+ self.nazwa+ ", "+ self.adres
so currently my search bar looks like this
any idea on how to make it look more appealing perhaps a larger search bar
with the search button connected to the bar
and a different colour
what's a best practice when dealing with json web tokens in the frontend? so far i'm just storing it in a vuex store, and just using it whenever i need an authorized request - not too sure if this is the safest thing to do
using drf-simplejwt with channels btw
follow-up question: how can I specify jwt permissions per function-based views, as opposed to viewsets?
Just a simple question, why is my jwt token always doesn't work😅
from flask import Flask, request, render_template_string
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
print('--- original order ---')
for key, val in request.form.items():
if key.startswith("item"):
print(key, val)
print('--- sorted ---')
keys = request.form.keys()
keys = [key for key in keys if key.startswith("item")]
keys = sorted(keys)
for key in keys:
#print(key, request.form[key])
print(key, request.form.get(key))
return render_template_string('''
<html>
<head>
<title>KrkanoidBot</title>
</head>
<body>
<h1>Testiranje</h1>
<h2>Testiranje</h2>
</body>
</html>
''')
if __name__ == '__main__':
app.run(debug=True)
Can I add css file to my Python Flask file ?
use <style></style> in head
thx
hey anyone's up??
yeah
can i get ur 5 mins plz
Sure ? I dont know how much ill be able to help
Nope
How does one submit html forms
anyone experienced with payment gateways?
how to add in a site a payment gateway and what to focus on?
focus on security ;b
try checking Stripe for example, I don't know really it inside yet
I just saw colleague, who had it working in Flask in its testing mod
and then rewrote it to work for Django as well
yes exactly! Also working with flask
going to research how it works on a next week probably, or week after that
its testing example looks working pretty easy
you can create special testing account there
and making testing payment as much as you want
in order to get grasp of that thing
I think motsly the integration is the most work, other than that the transaction are all on the gateway.
mm there are two mods as far as I know
first one... you are using their system of things to buy, and basically you put everything on their shoulders
exactly
in second approach you can create your own database with things to buy, and client system
and you just wire payments to their system
for every test though, the fees will go wild right?
tests are free I think
perhaps some limit per month or something
this requires to make an arrangement with Stripe the company as well?like a subscription?
it is available right after registration as far as I know
they give testing account/token access by default
nice
the most important would be probably never exposing your private key ;b
there is also public key though, probably it is allowed for exposing
If I want to keep fees for myself for every transaction, this is complex?
what do you mean exactly?
i mean additional fees from what Stripe will take.
some fee would be probably for sure
like an app where people transfer money to other people and using Stripe gateway I also keep a small amount as the site owner.
any payment system is meant in the first place to get money to the site owner 😉 well, or at least at the second place right after they would collect their fees
how much would you succeed to transfer money between two random people, is another problem though
it needs finding some solution
what are the problems?
the problem to find a way to transfer money between two random users
I get it, that's what you wish to do
via a gateway?:)
Stripe in the first place a way to collect money from users to site owner
it isn't about two separate bank accounts?
hmm
What can I use then for that purpose?
Hi guys, need help.
Let's say I have a simple flask API and backend where I have some files in access and send data to the front-end from. I wanna have a functionality where if let's say i make a post request and change the data in the files, it gets updated in a lookup table and then after a couple of seconds, the front end gets updated. Any idea where I can get such an implementation?
Does anyone know anything about express routing. I'm having a very basic express routing issue
nvm, this actually worked!
When you program python, where do you program it is there a good app to use. besides pycharm?
should I use px or should I use em / rem in CSS?
which one is better in terms of compatibility with different view ports on different devices?
use rem unless you have a good reason to do otherwise
because you generally want your UI to scale with the font size your user has set
I mean, if the user wants to zoom they'll use their browser's zoom feature, no one zooms by zooming font
Using px is just hard-coding your design, it'll harm the responsiveness of your site. Use rem.
most people don’t, yes
but they exist
and also
I personally find it easier to keep my design uniform
when everything is defined in terms of rem
so I went to do a bit of research because I was wondering about the browser zoom point
Long live the modern browser! Browsers are getting better these days. We seem to be in a golden age where there’s a never-ending stream of new features added for the benefit of the users accessing the page, and really great tools for those creating the page. It hasn’t always been the case, though. Earlier versions …
this is good I think
How can I use redirect(url_for()) this flask route with token?
@app.route('/protected?token=<token>', methods=['POST', 'GET'])
def protected(token):```
Use sublime text/atom and a terminal. That's it. That's the best way to code. No distractions.
Visual Studio Code
user friendly and nice
some people debate only if you should use VS code or pycharm ;b
or at least I saw a joke recently, that we should rename #editors-ides into #vscode-vs-pycharm
hey
C:\essentials\python\python.exe: can't open file 'C:\Users\91834\PycharmProjects\website\manage.py': [Errno 2] No such file or directory```
im new to django
Hello, I'm a PHP Developer and learned Python, so I want to use this in Web, so can anyone please recommend me a Flask or Django course?
The official Django tutorial is great, but it uses HTML
Hello
I need to get the text from an image url, cv2.imread but with an image url, i don't want to download the image
Hey! does anyone have any experience with selenium?
Highly recommend going with Django.
Try downloading the image as bytes (save it temporary in memory). Make sure the library can read information from bytes though.
I have tried that, but I don't know how to make it read the image.
?
Literally pass the query parameter with it.
If that's not supported make a custom decorator or function.
I haven't used opencv2 in a while so I won't be much help. I would keep looking into the documentation. If there isn't an option then you may need to download the image. You can always delete it after.
Okay thx
If you want a breezy read, you could try William Vincent's Trilogy Django for beginners, django for professionals, and django for api's. Short and sweet with a few best practices thrown in. Reddit's Django Learning community also recommends Two Scoops of Django, which I've found useful, but also ahead of just getting your head wrapped around the framework.
What’s the difference between Django and Flask?
I picked up flask and I don’t want to learn django after learning flask
Django is the batteries included version of flask
Because flask is doable for me
Flask doesn't have a database abstraction layer or anything like that
Django also does have a larger amount of packages that are maintained. It includes security, admin dashboard, migrations, orm, auth, emailing, and much much more.
Meaning you don't have to worry about as many small details. For example Instagram, Pinterest, NASA, quite a few more all run on some form of Django.
Just allows you to iterate and ship things fast.
Hm - so should I forget flask and learn Django? Or is flask doable
Like is it fine or is flask bad
Flask is fine.
Alright great
Flask is perfectly fine.
I started with Flask first myself and then moved into Django. As Flask does give you a different perspective of how things work.
Free code camp has a good flask tutorial
On youtube
Ok, thanks everyone
I recommend Corey Schafer
https://www.youtube.com/watch?v=MwZwr5Tvyxo&list=PL-osiE80TeTs4UjLw5MM6OjgkjFeUxCYH
https://www.youtube.com/playlist?list=PL-osiE80TeTtoQCKZ03TU5fNfx2UY6U4p
In this Python Flask Tutorial, we will be learning how to get started using the Flask framework. We will install the necessary packages and get a basic Hello World Application running in our browser. Let's get started...
The code for this series can be found at:
https://github.com/CoreyMSchafer/code_snippets/tree/master/Python/Flask_Blog
Djang...
@jade lark Speaking of packages--I'm having a time understanding django-wiki project. It's a module, so when you install it, you have a django project with settings and little else. What's the quick take on customizing a package like django-wiki (I want to add django-tagulous) when the whole project is inside a module?
You can use class inheritance. So, you would make your own class and inherit from it. Override the methods provided by it.
@jade lark Ok. classes in what files? Do I create a new app for django-wiki and then add override classes there?
call it django-wiki-overrider
What are you trying to do? Like specifically
Nah don't do that
Create it where your application requires it.
If you're using it throughout multiple apps then created a utils module, then a file and class for it in there.
that's the whole application. just a wiki page. Django-wiki has everything I want except for tags
its on github
duh. type fast. think slow
its for knowledge management for the office. <10 users.
but django-wiki doesn't support tagging. And I want to have an ontology of items for search. in other words, tags like SE
hey, does someone here know a bit about javascript and wtforms?
Ok. My mental map ... make tags app and in there put the override classes for django wiki
Then follow the customization docs
https://django-wiki.readthedocs.io/en/latest/customization.html
You would want to probably write your own views for this and include the tags, then include it in the custom templates.
so structure would be like
custom_app
- tags
- views
- models
- templates
- settings.py
- etc...
in settings.py you would include the django-wiki app from pip
Then if you're creating custom views for parts of django-wiki you would make apps and override them as required. For example, if they had an articles app. You would make one yourself and override it there. This will allow the code base to be much smaller and separated.
do you know something about flaskwtf and javascript @jade lark ?
Yes, but if you can ask the actual question that you have that would be great.
i have a flaskwtf form in a bootstrap modal, but whenever i submit the form the modal also gets closed even when there is an error in the form
Hey, can someone help me with flask?
i just followed a basic tutorial on how to plot a chart on a webiste and i have the exact same code now but i get an error when trying to load the website
thats my error and i guess you wanna see the code too 😄
i tried to find a solution but the javascript isnt working
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def home():
data = [
("1-01-2020", 1234),
("2-01-2020", 1140),
("3-01-2020", 1050),
("4-01-2020", 934),
("5-01-2020", 834),
("6-01-2020", 734),
]
labels = [row[0] for row in data]
values = [row[1] for row in data]
return render_template("graph.html", labels=labels, values=values)
dropdowns ig? not sure
and i have everythin the same as in the tutorial and now i have no idea why i get the error :/
would be awesome if someone could take a look at it🙈
Right, that will happen because the modal is shown by JS itself. What you'll need to do is submit the form via JS with fetch() or axios and then update the form showing the errors with JS as well.
dropdowns are basically like choose from a list
like it's a dropdown with January, February, etc.
Not sure tb
tbh*
well if they type something invalid you'll need to check for it
I'd suggest drop downs
for the months
Are you running the server? Because right now it doesn't seem like you are off the code provided.
as for the year and day -- just use a regular string field
Well I haven't worked with dropdowns but with string fields
mh what do you mean?
i do that
Post the code please. For the JS and the html of the form.
When requesting the page does the console show you an error of what happened? If not you need to turn on debug mode.
So the template wasnt found
yup
Theres your problem then
and how do i solve this🙈🙈
Fix the path
is it in folder 'templates'?
if not, it is probably in the wrong path
https://paste.pythondiscord.com/vowomowuxi.xml this is the html of the modal and the js i found
@jade lark Just for completeness on this subject. Django-Tagulous says you have to override the models to add their tags. https://radiac.net/projects/django-tagulous/documentation/usage/ I read issues in the django wiki issues which say Django-Wiki has a Plugin system (https://github.com/django-wiki/django-wiki/issues/585). Others have asked about this before (https://github.com/django-wiki/django-wiki/issues/385) but the discussion is hard to follow. ..... Thank you for your take.
Did you rename any of the ids? Because that should be working.
yeah i added ids for the javascript
Ah yea mb
but as they are in the same directoy the pathing should be correct like this or not?🙈
the submitbutton doesnt do anything with the event.preventDefault(); in the script
That's 100% right you would want to override the article model. There again, you would use inheritance and either extend or override the model.
That's the point of it being there.
No flask looks in the templates/ directory.
If you follow this here: https://stackoverflow.com/questions/33396064/flask-template-not-found
It will work for you.
yeah, but the rest of the javascript also doesnt do anything when i click on the button
so i have to put graph.html in the templates directory
ah well one error is gone now xD
If you added or changed the ID's that would be why. You want to make sure they're matching with the JS. You can inspect the network tab in your browsers developer tools and make sure the request is sending.
ah thanks 👍
whats the difference between the Premium Intel with NVMe SSD NEW and Regular Intel with SSD in the digital ocean server plans?
Couldn't find the element. Try moving the script tags to the bottom of the HTML file (if they're not already there). Right before </body>
My guess without looking at the specs would be IO speed (read/write)
oh damn i am dumb i misspelled it damn
Happens to the best of us man
ahh now it works 🙂 thanks for your time✌️
the form isnt sending any request in the network tab and i checked the ids and they were also matching
so do you think its worth it?
thats the difference
Depends on your application, probably not tbh due to the way providers like digitalocean work.
Unless you're going with dedicated.
this is a VPS
if just for developing
That's a droplet lad
so it's a VPS yes, but it's not dedicated
its my hobby project
go with the normal droplet then
more than enough having the cheapest
ok cool thanks
I rent for 3,5$ the same thing
where do you do that?
Without seeing your code specifically I cannot tell.
also is that 3.5$?
yeah, it is in my native country, I think it does not exist in English
ohh
i could show you the whole html file and js: https://paste.pythondiscord.com/tituyezale.xml
I actually was able to find for same price in English before
but they asked from me
to pay for 1 year in advance%
not really good I thought
Does anyone have any recommendations for tutorials or authors who describe/explain Django override of views and models?
I learned it from official documentation I think
in their tutorial
at the end of the chapter
it explains about templates
but I guess everything else should be sort of same
or may be you are looking just for override through inheritance perhaps
Couple of things:
- Remove the action from the form
- Specify ID's for all values of your input fields, that and names
- You can try specifying a submit event instead of the click event for a button and try that instead
@inland oak I will look at that. I've just been looking at Django docs for reference and didn't get into the tutorial. I completed william vincent's override tutorial for admin. I hoped to find more on the web but its tough search
Do you guys understand CSRF and the role of the csrftoken cookie?
then highly likely you already learned that
don't you just add the csrf token for forms and it does it's business?
well - yeah. I plan on adding it for my JS forms but I'm a bit hazy on its implementation. Gonna give it an extra read tonight.
doing stuff for the sake of it, without actually understanding what I'm doing, just hurts me in the long-run
Well you know. pick you battles. The csrf token is in HTML form in templates. I've not read any particulars which describe edge cases yet. good luck
thanks! the button is doing something now, but it still doesnt keep the modal open
Hey so im trying to get some test done on my django rest framework and it doesnt seem to work on some of my tests
class GatherTestCase(APITestCase):
def test_gather(self):
response = self.client.get("/api/contacts/")
self.assertEqual(response.status_code, status.HTTP_200_OK)
class CreationTestCase(APITestCase):
def test_creation(self):
data = {"name": "test name", "email": "test@test.com", "phone_number": "+00000000000"}
response = self.client.post("/api/contacts/", data)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
class UpdationTestCase(APITestCase):
def test_updation(self):
data = {"name": "test name", "email": "test@test.com", "phone_number": "+00000000000"}
response = self.client.patch("/api/contacts/1/", data)
self.assertEqual(response.status_code, status.HTTP_200_OK)
class DeletionTestCase(APITestCase):
def test_deletion(self):
response = self.client.delete("/api/contacts/1/")
self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
CreationTestCase and GatherTestCase pass
UpdationTestCase and DeletionTestCase get a 404
Im not sure why they are not working when in my postman it does
when having nginx serve your compiled staticfiles (html/js bundles), is nginx technically acting as a cdn?
also can you use redis to cache pages with django? what's the use-case of caching pages? I don't understand the basics of it.
whats should I use on my VPS Ngnix or Apache?
Im trying to deploy a flask machine learning applications
I have a problem with React Router
here is my App.jsx
The problem is that I don't see the content
In the Switch element
the Dashboard component is not being rendered
also... the Link components are in a different component
in the Navbar.jsx = https://pastebin.com/2FTaTx06
There are no errors in the console
It's just that I can't see the rendered component when I navigate to path='/'
reorder the / path route to be last
or add an exact attribute, if i remember correctly
yow it still doesn't work
can i see the updated code?
I updated this part jsx <Switch> <Route path="/create-loan"> <CreateLoan></CreateLoan> </Route> <Route path="/" render={(props) => { <Dashboard {...props} getTotalMoneyOfStatus={this.getTotalMoneyOfStatus} getTotalMoneyOfStatus={this.getTotalMoneyOfStatus} users={users} loans={users} />; }} ></Route> </Switch>
give it the exact attribute
like this?jsx <Switch> <Route path="/create-loan"> <CreateLoan></CreateLoan> </Route> <Route exact="/" render={(props) => { <Dashboard {...props} getTotalMoneyOfStatus={this.getTotalMoneyOfStatus} getTotalMoneyOfStatus={this.getTotalMoneyOfStatus} users={users} loans={users} />; }} ></Route> </Switch>
no
see this example
I did thisjsx <Switch> <Route exact="/create-loan"> <CreateLoan></CreateLoan> </Route> <Route exact="/" render={(props) => { <Dashboard {...props} getTotalMoneyOfStatus={this.getTotalMoneyOfStatus} getTotalMoneyOfStatus={this.getTotalMoneyOfStatus} users={users} loans={users} />; }} ></Route> </Switch> I can see that the CreateLoan component is rendered.
ok, i see you are using a render function, what does that do exactly?
I need to use that render function so I can pass props to that component
can't you pass props normally?
No
There is a bigger problem I think
The Dashboard components doesn't want to get rendered
<Switch>
<Route exact="/create-loan">
<CreateLoan></CreateLoan>
</Route>
<Route exact path="/d">
<Dashboard></Dashboard>
</Route>
</Switch>```
I even removed the props and stuff
hmm, i'm not sure what could be the issue. could be some error in the component
Ok now i
try it with another component that works and see if the issue still persists
Ok now Im gonna looks stupid lol
<Switch>
<Route path="/create-loan">
<CreateLoan></CreateLoan>
</Route>
<Route exact path="/d">
<Dashboard
getTotalMoneyOfStatus={this.getTotalMoneyOfStatus}
getTotalLoansOfStatus={this.getTotalLoansOfStatus}
users={users}
loans={users}
></Dashboard>
</Route>
</Switch>``` This works
Now I have another problem
Can python do web frontend?
@native tide Here's my essay on that
I ask myself the same question
Hi, anyone know why my json looks weird on javascript?
var test = "{{ testjson }}";
console.log(test)
output
[{'time': 1620588041, 'open': 26, 'high': 26, 'low': 26, 'close': 26}]
json file
[{'time': 1620588041, 'open': 26, 'high': 26, 'low': 26, 'close': 26}]
Why do you have brackets [] around the json?
all good. i fixed it using | tojson
Hello,
Is it possible to send a post request from the client side, receive a get request, then change a html element content without refreshing the page? something like this:
on keyboard input event listener -> client sends post request to server -> server sends back a request -> client side receives the request -> element content changed
I'm using flask as backend
@errant storm absolutely! There's the .text() method while using the Fetch API. You could then insert that html into the DOM.
https://gomakethings.com/getting-html-with-fetch-in-vanilla-js/
Yesterday, we looked at how to use the Fetch API with vanilla JS. The article focused on making API calls and working with JSON data.
Today, I want to show you how to use fetch() to get HTML instead.
The Fetch API returns a stream To recap, the response we get back from fetch() is a ReadableStream.
With a typical API request, we use the json() m...
thanks!
Static yes, dynamic is limited without Javascript.
No
You use HTML/CSS for frontend
Not Python
Fair point.
there are ways but they’re not very mature
async function fetchTitle(e) {
fetch(`/post/search/title?q=${e.target.value}`).then(
function (response) {
return response.json();
}
).then(
function (json) {
ele.innerHTML = json.title;
}
)
}
Why is ele's innerHTML [object Object]
nvm i accidentally return a json in a json, my bad
In django can I just log everything including TLS issues? Because.. I think I’m prevented doing this when the URI variable is only passable as a string when i would expect to pass multiple fields so it’s compatible with ldap.initialise() as I’m wanting to enable trace_level=2
which framework is the best for python web dev?
Flask is easier than Django, Django provides lots of common feature which makes development faster. I'm not sure which one is better, but i prefer using Flask
hmm might start out with flask then, I have used falcon before and it came pretty good to me after a while
I'm having a lot of fun with Django + Wagtail.
I just dont understand what the hell Django is, is it a program you install to write front end code?
I'm so lost
Python packages aren't technically "programs" in the official computer science sense.
They're scripts that make the Python program do things.
Django is for back end, for front end u use html, css and website js
So you need to learn Flask code to use Python code to link HTML with python code
^^
No, Flask is Python.
You learn Flask abstractions and write Python to tell it what to do.
It's a version of python code that helps interact with HTML?
@errant storm what anime is your pfp from?
yuru camp
tanx
Sorry i'm coming from simple PHP and HTML coding.
This seems so much more in depth
you mean the {{ }} thing?
But i want to learn it just getting a bit discouraged
it's jinja
@worldly furnace No. The versions of Python are 2.6, 3.9, etc. Flask is just a library written in Python.
So its a library of functions
Yes.
oh yeah I've seen jinja used before with it, that's some funky syntax lol
That interacts within python code.
So for instance if i wanted to post HTML code within PHP code i would have to "
echo" the code. Something similar to that?
When Python runs a Flask app, it generates a web server on your computer that listens for HTTP requests and responds with dynamic HTML generated by your app.
PHP functions a little differently.
I'm currently learning python using the app mimo.
Just for the simplicities of the programming language
HTML isn't anything more than a string.
So you just put HTML in the strings within the pythoh
Print('<button>Button</button')
HTML is a markup language, nothing more, nothing less
There is often a templating engine included, but yes, that is the essence.
Kind of like this for a snippet:
<!DOCTYPE html>
<html>
<head>
<link rel="shortcut icon" href="{{ url_for('static', filename='images/idrop.png') }}">
<title>
Main Menu
</title>
<style>
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 30%;
}
The {{}} is the magic
Jinja and Handlebars are examples of templating engines.
that just pulls variables and such from python and implements inside HTMl
Okay so another problem im having is i followed the instructions to do the path for python, and after i created the variable for python i went to system variables to edit the path and the python link isnt in there
So add the directory where it exists and == done
so just add the same directory there
this girl on youtube is talking about adding %% before and after
when i type in command prompt says python isnt installed, but it is.
Sure, it doesnt know the path
do this, type out the full path of python.exe and hit enter, if it works, then remove python.exe and copy pasta to path
says 'is not recognized as an interanal or external command, operable program or batch file
C:\Users\emjay\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Python 3.9
i dont think i selected add path when i installed
let me uninstall and reinstall with that option seleceted
Yep, no space
Start menu
and Python 3.9
So, you need a quote
"C:\Users\emjay\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Python 3.9\python.exe"
^ That would run if its python.exe being ran
I love me some lack of quotes with windows for good ole red team fun...
so i add that as a path under environmental variable?
ok
If so, then simply copy:
C:\Users\emjay\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Python 3.9
And place in path. Notice I did not quote
Path knows about spaces, etc.
So thats the dir, copy it to path and bob is your uncle
hey!
So I'm creating a webview app using pywebview, where my backend is in flask and the frontend is in a JS framework (Vue). I was wondering what the best practice was for picking ports and syncing them across the frontend and backend. Is there some nice way to do it or do I just have to rely on randomly picking a port and hardcoding it into both, and hope the users don't have something running on it already?
yeh i have just started django
can i get some suggestions to complete it fast and how to do that full plan anyone exp. in django ??
you can't "complete" django, it's a framework. i highly suggest taking a course like cs50's intro to web programming which delves into django
how vast is django
and how should i learn it i mean the correct way
django has a lot of features that come included as opposed to a lighter framework such as Flask or Express. like i said, I suggest taking a course or walking your way through things - routers, templates, views, models, requests, etc.
it depends. some may say it's easier, some may say it's harder. i think it's harder than flask because it's a heavier framework and might come with having to learn more concepts
^
ok im ready to start
great!
hmm i always face this issue
i fix it but again face it
python manage.py runserver
C:\essentials\python\python.exe: can't open file 'C:\Users\91834\manage.py': [Errno 2] No such file or directory```
@wooden ruin
the manage.py file you are trying to run is not in your active directory
oh
lemme try\
05-2021 21:47 <DIR> .
09-05-2021 21:47 <DIR> ..
10-05-2021 11:29 <DIR> .idea
09-05-2021 22:22 <DIR> mysite
yea so you notice how manage.py is not there @dusk portal ?
you probably need to cd into mysite
hello guys..
Need help on Generating Access Code using Django
Hi, I was trying to use django with celery and redis , redis server is password protected, so how can i pass my password to redis . I am receiving this error Cannot connect to redis://localhost:6379//: Authentication required
which seems reasonable because I am not passing password . I have tried CELERY_BROKER_URL = "redis://:mysecurepasword@localhost:6379"
but this also doesn't seem working.
Using Graphql or rest?