#web-development
2 messages · Page 153 of 1
prob not
but basically it is a interactive map, which when you click on a state on the map, it should generate the informations in a dropdown menu
so in this case we only use one view
maybe 2 if we want to include a summary of all information on another view/page
sorry to interrupt, but quick question, should my classes in django be named camelCase or PascalCase?
Right, so any data you want to be in that page at the moment it loads should come from the server, unless you are willing to load it using JavaScript instead, which means still contacting the server but after the page load. The general consensus is that if you need anything beyond basic form functionality on a page - you use JavaScript. For stuff you want to be there from the beginning you use server side to template to html.
All Python classes by convention should be pascal case. Camel case is more a js thing. But please check in the general channel. I don’t wanna lead you astray.
ok thanks!
I have a React + Django + Airtable project. I’m using Airtable for managing products. I want to integrate a “user” profiles, to make “bids” on items. Is Django good for that?
If I create the front end and integrate my DB..... how much would it cost for someone just to create the profile side and implementing being able to log in users and place bids?
It’s hard to recommend things when seemingly all of you have little experience in the basics of how a site functions. And I don’t mean it in a nasty way. I just mean that you should really try to read up on basics of how a server/front end function and the varieties of that. Otherwise you will only be working in abstracts.
alright thanks! I will think about it and figure out the best way to do it
yes ofc I understand. Lastly I'd like to ask if you got any recommendations where i can look those up/get to know them in a relatively simple way?
Honestly the best place is youtube. Lookup basic website tutorials using server side rendering. That’s where you start. Later you move to more advanced stuff.
django (in drf mode) will handle db part quite good, and will work as API to provide stuff for you
Some people say FastAPI can be better though. I see that in general for API it has everything tuned better except for database, which would be have to chosen.
Basically, both good. But if someone is already more familiar than another one, better to choose more familiar tool I guess
Do you know Apollo GraphQL? Or Airtable at all? I’m thinking of already with Apollo GraphQL, it seems like users are defined better in a way, that you can filter or add better. But I do like how Django is setup already, but... how you use Django, kinda seems in a different way then react
Nope.
I walk with REST API
That provides me Django REST framework plugin for now.
I saw from afar graphql stuff though.
Django and React literally opposites of each other. They supplement each other greatly though.
How to use django, can be started from quickstart official documentation
Django rest framework requires usually already understanding of django though
A little big jump to make
Official tutorial with quick start
Django rest framework has separated quickstart tutorial, but I don't know how would you handle it without learning django first
Django, API, REST, Quickstart
So, what’s the best way to create “profiles”, to bid on products. I know of Apollo GraphQL, but heard that endpoints can be a problem
Apparently graphql is alternative to rest though
I saw it integrates with django
Yes, I that you can “filter” what is used or queries
Think of a db model to do that
Database planning
@inland oak I can do that with Airtable, but I’m mainly just wanting to figure out a “user” side to do bidding
Whatever choice would you use. I don't think it would be really that big difference, except that graphql I guess should create bigger flexibility if you handle dozens of attributes / having logic for multiple REST requests
I am not familiar with graphql though, only with rest
Code (python)
from flask import Flask, redirect, url_for, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('home.html')
if __name__ == '__main__':
app.run('localhost',5050)
Template (html)
<!DOCTYPE html>
<html>
<body>
<h1>My first Website</h1>
<p>Hi, this is my first website.</p>
</body>
</html>
The page stays blank and nothing loads. (flask)
Hey @inland oak!
It looks like you tried to attach file type(s) that we do not allow (.zip). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a.
Feel free to ask in #community-meta if you think this is a mistake.
which OS you are?
Windows 10
in Windows:
python -m venv venv
venv\Scripts\activate
pip install -r requirements.txt
python app.py
in Linux:
python3 -m venv venv
. venv/bin/activate
pip install -r requirements.txt
python app.py
have fun
Thanks
Yea the error there was that the template was not found
you needed to put home.html to templates folder
I had a template folder with the html code inside that
download the archive, I already tuned there
recommending this tutorial btw
outdated, but still cool
I'll check it out.
pretty sure that you can't use python -m venv venv
but have to use py -m venv "the name of your venv"
I use venv all the time as standard venv name ;b
you can assign different one if you wish thogh
shrugs, I used python only in windows 7 and linux
actually, I used in windows 10 too at my work
it worked as python pretty well
perhaps you are installing some different distribution
non standard one
hmm maybe i guess ye
i tried PWA on WAMP server and it worked
but when I try it on heroku app it didnt work?
idk wat went wrong
what would be the best way to host my flask webapp? it uses celery, a terminal to run the webserver and a terminal that runs a function each hour
hello i have i query that can we use mysql logo in my portfolio website?
How can I get the full file path to a file in my Flask static folder?
I've tried url_for and app.root_path and joined it with os.path.join but the furthest I am able to get is C:/static/user/content/filename.pdf, which is obviously not correct...
good morning web developers, does anyone know a good place to look up open source projects to view their code?
Most open source projects will have at least a mirror on GitHub
Is there a particular project?
how do i access this image from that css file
.pm-icon {
background: url("the url");
}```
im trying to do this
that's usually how you do it
are you using react or vue?
i think you have to import it if you're using that
react
but what is the URL for the image meant to be
if i do .. it doesnt work
i know its a file path but i can't access logo.png from the directory that index.css is in
import the image in react and bind it using the style attribute
@sand glen you just need the right path to the image. It's not ../images/image1.jpg because the .. points to the src directory (and public is not within that)
reference it as if the css file is in the public folder
i think it gets generated in a css folder if i'm correct, just assume that
else. put it in src and import it, that's the easiest way but it seems like you dont want to do that
ok
So flask Or django for web development?
it depends on task, and a bit on developer's likeness to two types of frameworks: microframework or 'batteries-included'
Hi all , I’m trying to decide on wether to use flask for a simple app I’m building . Ive done a small tutorial app and get the basics .
Can any of you that have created a more fleshed out app post a screenshot showing your interface designs - I’m trying to assess how good you can make a flask app look
all python frameworks more or less the same in design terms
they all use Jinja like instrument%
no really big difference noticed so far for GUI
Can I name my template same as my file name?
Like If i have a forms.py file Can Iname my template as forms.html?>
why not, sure
oh thanks!
Got it . I’d still like to see if anybody has to hand . I’m confident in the functionality as I’ll just be writing and reading an SQL. It’s just the design and layout I’m interested in atm
hey, another problem!
suppose there is car option and If I added a car's name in adminsite now how can I direct or add in the car option?
I'm using django framework btw
by changing Admin list_display field
"module to render ships in admin interface"
from django.contrib import admin
from .models import Ship
class ShipAdmin(admin.ModelAdmin):
"""class to rewrite standard model view to
what we need showing in admin interface"""
# print(tuple([f.name for f in Commodity._meta.get_fields()]))
list_display = (
"nickname", # str
"info_name", # str - infocardish real name
"name", # str - ini name
"ship_class", # int
"typeof", # str - type
"hold_size", # int - cargo hold
"nanobot_limit", # int
"shield_battery_limit", # int
"capacity", # int - powercore capacity
"charge_rate", # int - powercore charge
"cruise_speed", # int - engine
"impulse_speed", # int - engine
"hit_pts", # int - health points
)
list_per_page = 1000
admin.site.register(Ship, ShipAdmin)
you can select attribute names
or even function names which get your data
from your model
no yes this register to the admin site
well, I want to Insert data from Select option to the database
@inland oak
I'm a beginner
What would you recommend
Django or Flask?
I would recommend Django
well depends upon what kind of program he wanna build
I think he is just getting started
Yeah Yeah
I have done basic Python and even OOP
Okay
How much time does it take to be expert in Flask
and kind of work can I do using it?
Btw I was practicing numpy and got stuck in a Matrix problem.
Can you help me in that problem too?
Help channels are not responding sadly
I didn't get too much in it actually
You can use it in the back-end for the web
Sorry I don't know about that library
Maybe they are just sleep or not online
Or can't help you that's it bro
im trying to make a navbar but the icon in the top isnt going to the left of the <h1>
how do i make it do that?
<a className="navbar-logo logo-text" href="/"><i className="pm-icon" />PartMatcher</a>
It's html-related question and you ask for the answer in Python discord 🙂
where else do i ask?
and it says in the channel description you can ask for help in HTML
float: left; gonna help you
k
thanks
i didnt know what to search exactly
the stuff that was coming up wasnt relevant
How to make <sth> left sided html + css
now im having trouble centring the text with the image
i want it to be like that (ignoring colour)
.pm-icon {
background: url("./img/logo64.png");
height: 64px;
width: 64px;
background-size: contain;
float: left;
}
.logo-text {
color: #11df94;
text-decoration: none;
font-size: 20px;
}```
```html
<a className="logo-text" href="/"><i className="pm-icon" />PartMatcher</a>```
It isn't html5 code, why do you use background instead of simple <img src="..." class="someclass" />
https://www.w3schools.com/howto/howto_css_center-vertical.asp
And here u are for vertical center your text.
so that its an icon
Try googling your questions before asking someone for help. Googling is a primary ability for coders.
I don't know wdyu such strange structures and can't find definition for <i> tag. It is html-based but I don't know its behaviour.
<i> is the icon tag
It is not pure html 🙂
In pure html that is the definition: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/i
The HTML Idiomatic Text element () represents a range of text that is set off from the normal text for some reason, such as idiomatic text, technical terms, taxonomical designations, among others.
I can't help you with that, the first time I see it :c
ah yes, that's easy, a moment
[Q] requests lib:
website has in html:
<form id="formLogin">
<div class="login">
<input id="inputName" placeholder="Enter your name" type="text"/>
<button type="submit">
... etc...
It's under url lets say abc.gg, I want to log in so I can access next page, I do:
url = 'http://abc.gg'
payload = {'inputName' : 'JohnDoe'}
r = requests.post(url, data=payload)
It says cannot post 404 error, so I do get:
url = 'http://abc.gg'
payload = {'inputName' : 'JohnDoe'}
r = requests.get(url, data=payload)
Still doesn't work. How do I access payload of inputName this html tag:
<input id="inputName" placeholder="Enter your name" type="text"/>
How to acces that inputName to set my value and send to website?
nginx: [emerg] duplicate upstream "django" in /etc/nginx/sites-enabled/short_url.conf:2 Does anyone know how to fix this error from nginx?
@app.route("/edit/<string:sno>",methods=["GET","POST"])
def editing(sno):
if 'uname' in session and session['uname'] == params['admin-user']:
if (request.method=="POST"):
__title__=request.form.get('title')
__subtitle__ = request.form.get('subtitle')
__content__ = request.form.get('content')
__slug__ = request.form.get('slug')
if sno == 0:
post = Posts(title=__title__,subtitle=__subtitle__,content=__content__, slug=__slug__)
db.session.add(post)
db.session.commit()
return render_template('edit.html',sno=sno,params=params,post=post)
else:
post=Posts.query.filter_by(sno=sno).first()
post.title=__title__
post.subtitle=__subtitle__
post.content=__content__
post.slug=__slug__
db.session.add(post)
db.session.commit()
redirect('/edit/0'+sno)
post=Posts.query.filter_by(sno=sno).first()
return render_template('edit.html',params=params,post=post)```
UnboundLocalError
UnboundLocalError: local variable 'post' referenced before assignment
return render_template('edit.html',params=params,post=post)```
post is only assigned if the request method is POST, what if it's GET?
good idea
also what's with the dunder variables? That's not the right way to name them, if you want them to be private use _variablename but even that is irrelevant because your variables do not extend your functions scope.
Hello how to add comment section in my existing app. Comment in CRUD
?????????????????????????????????????????????????????????????
nginx: [emerg] duplicate upstream "django" in /etc/nginx/sites-enabled/short_url.conf:2 Does anyone know how to fix this error from nginx?
hey anyone can help me with this??
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='styles.css') }}">
flask doesnt load the changes only once and then nothing
i can easily change elements in the template but in css nothing
I believe you need to do ctrl-shift-r to force refresh the page
or cmd-shift-r on mac
ye that worked thanks so much !!
Is there a general approach to force refresh the page at the client side? For example if a new version of the app is deployed? Had the same problem using nuxt.js
Because you cannot expect a user to force refresh the page himself after deployment
I’m not actually sure, sorry
is there a way to resize the flask form button in css ??
lets say I enclose it with a div tag then I target it but nothing happens
that changes only the box size of the div tag
Then do it on the actual button
It's still html code, right?
okay thanks anyway
You can add classes directly by doing form.submit(class="submit-field")
i have a question regarding cbv
how does the class know what template to use
or would i have to set it as an attribute before hand?
ouuu thank you very much 🙂
Has anyone succeeded in building a frontend app with svelte, parcel and typecript? The official svelte+typescript tutorial uses rollup, which seems a little bit too complicated for me
Or maybe I should just give up on parcel?
I haven't used it yet (I'm working on it), but I've heard that webpack is better for anything that's not an SPA (and even in general).
Idk about Rollup
hi! i have this code:
<a className="logo-text" href="/"><i className="pm-icon" />PartMatcher</a>
i'm trying to make "partmatcher" vertically aligned with the icon, but can't get it to work
.pm-icon {
background: url("./img/logo64.png");
height: 64px;
width: 64px;
background-size: contain;
float: left;
}
.logo-text {
color: #11df94;
text-decoration: none;
font-size: 20px;
vertical-align: center;
}
these are my CSS rules
.logo-text {
margin: 0;
position: absolute;
top: 50%;
transform: translateY(-50%);
}```
The way that works is that it makes the top margin 50% and then it maks it go up
its gone to the center of the screen
.pm-icon {
background: url("./img/logo64.png");
height: 64px;
width: 64px;
background-size: contain;
float: left;
}
.logo-text {
color: #11df94;
text-decoration: none;
font-size: 20px;
margin: 0;
position: absolute;
top: 50%;
transform: translateY(-50%);
}```
did i do something wrong
Can you show the html around that?
import React, { Component } from "react"
const menuItems = [
{
title: "Featured",
url: "/featured"
},
{
title: "Build Guides",
url: "/build-guides"
}
]
class Navbar extends Component {
state = { clicked: false }
render() {
return (
<nav className="navbar-items">
<a className="logo-text" href="/"><i className="pm-icon" />PartMatcher</a>
<div className="menu-icon">
</div>
<ul>
{ menuItems.map(
(item, index) => {
return (
<li key={index}>
<a className="navbar-item" href={item.url}>{item.title}</a>
</li>
)
}
) }
</ul>
</nav>
)
}
}
export default Navbar```
this is my jsx
im using react
Uh
Can you replace
<a className="logo-text" href="/"><i className="pm-icon" />PartMatcher</a>
with
<a href="/"><i className="pm-icon" /><p className="logo-text">PartMatcher</p></a>
ok
Instead of position: absolute;
anyone familiar with gunicorn here?
I'm trying to scale up my project on heroku and a bit confused
Well, I'm making an SPA
🙂
webpack has a very complicated configuration system, I don't really want to touch it
parcel is extremely simple because it needs zero configuration in the most basic case
hi all what is an easy way to change my measurements from px to % and everything look the same?
nvm i got it sorry
Parcel is supposed to be for for SPAs
At least from what my research on the internet says
can anyone recognize the auth method this website is using? im a total noob trying to build something that will sync this shitty wesites calender with mine
Can someone help me with a quick flask question?
someone told me if u got that u can use this to look further https://i.imgur.com/TXnIdzd.png
hello guys..
I'm getting "ImportError: No module named environ" this error
pip list:
django-debug-toolbar 1.11
django-email-extras 0.3.4
django-environ 0.4.5
django-forms-builder 0.14.0
django-heroku 0.3.1
django-jenkins 0.110.0
How to fix it?
environ is in module os, If I remember right, or may be I am mistaken
perhaps you missed import os
and called without os.environ
you have similarily named module though
django-environ, I have no idea what it is
hello
hı
i have made api using flask https://paste.pythondiscord.com/qojabijiwu.py current code plz check , server starts but code is not working
thanks in advance 
from django import forms
class MyModelForm(forms.ModelForm):
name_of_field = forms.ChoiceField(choices=[("john","john"), ("ivan","ivan"), ("carol", "carol"), ("albus", "albus")])
class CountryAdmin(admin.ModelAdmin):
form = MyModelForm
you probably meant to ask this
no wait I'll explain
it makes for the chosen field
selector
from admin interface
not sure if I remembered right the choices format though
so I want to build sth like this
and I want to build sth like when you expand author name then it should automatically dropdown the author name list
I hope you get it
can anyone help me in this ?
the last given code, does exactly that
for admin interface
yeah but they are just buttons with different functions
when I add a new book then that book should be able to include in that list
you know what I mean?
added more examples
Can you tell us what website that is?
Because that screenshot isn't really enough to know their auth method.
That website is just the content of the website.
But that's a very hard thing to gauge, even if we know the website.
i'm stuck in ajax pagination who can help me please?
bootstrap doesn't apply to my ajax pagination anyone can help?
Is it possible/a good idea to run a Flask app and mail server on the same server?
Allow: /```
Is this the correct way to allow everything in robots.txt?
Anyone can help with heroku plus gunicorn? I'm having some performance issues on my site not sure the best remedy
are you using django or flask as the backend? bc with django you dont need that. there are prebuilt function to check if you should paginate etc.
im using django , rly can i paginate without refreshing the page?
<a href="/"><i className="pm-icon" /></a>
<a href="/">PartMatcher </a>```
is this a janky solution?
oh you cant do that but why would you?
I need some help with Django rest framework
I have never worked with it before
but I need to use it for an internship
Can I ask here?
can some one explain parse_qs and explain what does this mean ```py
class RequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.log_message("Incoming GET request...")
try:
name = parse_qs(self.path[2:])['name'][0]
hello guys
Caren, jouw persoonlijke zorgportaal
i think it's the landing page
stopping me from using youtube guides to get in 😛
I don't think we can tell from that
Why do you need to know how they do auth?
it's the website they invited me to when i got sick and they have their own calendar
i wanna sync it with my google one
Then ask them
i did
Don't try to bypass their auth system
their team is on it but it could take months
well... it's autosigned in on my pc
can i use i that in any way?
But you're trying to get access to things they aren't giving you access too.
But you're still going around their auth system in a way that they didn't allow
And anyway, there's literally nothing I could tell you, except to maybe watch the "Network" tab in dev tools and see if you find anything. But without some advanced knowledge of how auth works, that's be hard.
im no expert
im an autistic fuck that wants his calendar synced thanks for the tips tho 🙂
any help can send me the right way
hi, i really need help with building a chat app in django. i built already the site now i need to make the chat with socket or django channels. can some one help me with it?
im very new to django so it is very difficult for me to do this app
(i tried lots of tutorials but its hard for me to understand when i cant ask questions)
If you can help me please send me a message
Thank you
@opaque rivet you know maybe work with django channels?
yeah I do, what's the issue?
does any one else know django channels?
Many people ask if they can make a website with only Python. The answer is usually no. It's much better to make a website frontend using HTML, CSS, and JS, and then use Python for the backend with a tool like FastAPI, Flask, or Django.
Why HTML, CSS, and JS are used
HTML, CSS, and JavaScript are better for front end web dev, simply because that's exactly what they were made for.
- HTML is a markup language made for creating the content of a website.
- CSS is a styling language, used to change colors, sizes, placement, and various other things on elements.
- JS is used for providing logic to the web. Neither HTML nor CSS have the logic required to be able to write complex logic that allows you to write custom, client-side scripts (at least, not easily). That's what JS provides, allowing you to have a dynamic and interactive website.
Is it possible to make a website with only Python?
Yes. Making a website with only Python is possible by compiling it to web assembly for the frontend or using Brython. However, that isn't viable for most people, since it's hard to set up and a hard thing to learn to do.
How you can add Python to websites
Although making a frontend with Python is rather hard, making the backend is possible using various tools. This includes interacting with the database, processing user data, and various other backend operations. A couple are:
FastAPI - A fast, modern framework built for API creation that's based on Python's type hinting.
Flask - A micro web framwork that has no database abstraction layer, form validation, or anything else that requires other tools or libraries (although you can use them).
Django - A high level web framework that is fast, secure, and scalable that's powered based on it's template language.
In short, although it's possible to make a website using only Python, it's a much better idea to use html/css/js for the frontend and make the backend using Python.
shrugs. I willl point only to the direction
where to seek for answers
don't expect from me answers
no It's default
wait, I'll show u my html page
IT's 3.1.7
This was random btw, I'll just refer to it sometimes
sure. just ask if its related to any of the topics that are listed next to the title
@zenith comet I guess you want to web scrap that site if you want to login with your credentials and then just iterate somehow through all events on the calendar (they all have the same class i guess) and store them in your db. Idk how you can synch with googles calendar bc i dont use/like it but i guess that can help and i hope you dont do smth illegal
it should be pinned 🙂
you can even tho idk why you would
What do you mean?
def one(num):
print(num)
def two(num):
print(num)
def three(num):
print(num)
arr= [one(1), two(2), three(3)]
print(arr[1])
This should print 2
But it print: 1,2 and 3
@native tide
@keen ravine i didnt call it like that instead i iterate throught it and passed the arguments. In my case i had a summarise,multiply etc. functions with 2 arguments and those i passed in
Are you fine with the official tutorial?
It's wonderful
Emmm so documentation it's the best choice?
when it comes to doing post and get methods what ip adress dou i need to put so people can use my web site ?
[<div class="trn-defstat__value" data-stat="CasualKills">
113
</div>]
anyone know how to get only text inside these tag ?
Example 113 is the text that i want

Thx
i puted my ipv4 ip and the web page didnt work for my friend in slovakia
but it works for me
@keen ravine You should check out #❓|how-to-get-help and claim a help channel, because this is an on-topic channel about web development.
What' you're doing is you're first calling one(1), two(2) and three(3), and each of them prints something, not returns something.
As you can see on the screenshot, f() doesn't return anythinig (it return None). Instead, it prints something on the screen when you call it. But g() does return the number 42.
For more info, check out https://www.youtube.com/watch?v=9Os0o3wzS_I
anyone ?
hey @manic frost could u explain me that with ip adress so every one can use my site
photoshop
what ?
Don't ping random people for help. I don't know how to solve your issue.
ok
How can i seperate 113 out of these tag
🙂
@calm plume u know Django?
Hey guys, I ran into a problem if anyone can help I’d be really great.
So I created a flask app and trying to make graph using Apexcharts.JS. I’ve got a json file feeded into the webpage under script tag but I can’t see the chart. I’m not sure if flask can provide variables inside script tag in a webpage
you can get it with javascript and store it there in a variable but if you dont mean that then idk what you want
thank
did you host it or are you running it locally?
for what?
locally
thats the problem. Only you can visit your page if you dont host it or send him the code and he runs it himself.
oh.
so i need to buy a host :[
But better would be hosting with heroku or smth. takes 5 minutes and is free
i runed the python code on my pc gave him the html code on his pc
hello ! i have a strange issue with a json i'm working on. i get the json from an api call no problem. but i cant access some part of the json but if i copy the json in another python file and try to access the data i can
Hey @quick schooner!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
heroku is free ?
yeah it is. I didnt pay a cent yet
see this only just want u to understand better the problem
this is the code i gave him
he downloaded
that is my ip
Did it not work?
and this is the python part
i can acces json['sections'] but not in my code. only if i copy paste it in another file
wich is also on my ip
so when i gave him the html code and run the python code from my pc the requests woudent work but it works from me
so yeah
u say i need to host it ?
its on your local ip. he needs to change it to his local ip. or just host it
when i put my local ip it doesnt work
why is that ?
bc its your local ip its the ip of that device in the current network and ips are kinda unique even tho they change. and sry i think you didnt even put your local ip rather your local default gateway and for that to work for him he needs to put his local default gateway or you host it
i puted a random now so my ip isnt revealed
ok so can u explain me how to use the heroku
how dou i transfer my python script and yeah i would have to get an ip adress so it connects to its server
kinda but idk if it works the same as with django. I can just help you get started
idk what you mean with that. You already got an ip adress you dont have to get one
dont i need to get an ip adress from the heroku site ?
i tought it works like that
no. u just upload the code and heroku has a server which serves your code and then you get the url and you send the url to everyone who should see it
btw thx for helping me and teaching me about how to use ip adress for web site developing
ok i may sound stupid but i tought this was logic im gona write u now wait 1 minute
np but that wasnt much. if you serious also with networking you should learn it with a course or with yt tutorials
k
i tought when u make an acc or get a host u get their ip adress, wich connects to the script u made ,wich then every one could use, wich makes this confusing to me why will it work when i put my ip adress on another lets say pc and work on my pc if u get what i say
thats what im confused XD rn
it works locally with your current local default gateway which is also kinda connected with your local ip and if the other perso isnt in the same network he also probably cant connect to that default gateway. And by creating an acc you kinda buy/reserve a place in their server with a specific ip-address which is covered with the url like google.com. bc you can also find google.com with their ip which is currently "172.217.23.46"
ok thx for letting me know that
can you show the command you used to install it.
could u tell me how to upload the py script on that server ? heroku
pip3 install goodbyecaptcha
sure ill text you. give me one sec
Hello, i have an issue with socket.io on python, please check #help-cake
[FLASK & HEROKU]
Hey folks.
i made a flask web app and i am now willing to deploy it on heroku.
The app works just perfectly on my machine. (LOL)
I did the whole process on Heroku, creating a Procfile, requirements.txt.
I am doing the deployment and it turns ok, but the app doens't load.
I checked almost anything. I didn't use the heroku git but doing directly with git command prompt.
Any idea on what could be the issue?
*2021-05-03T16:20:03.000000+00:00 app[api]: Build succeeded
2021-05-03T16:21:28.289934+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET
Can someone help me with some basic Django? I've got a views.py that goes like this:
from django.shortcuts import render
value = 1
def home(request):
return render(request, "monitor/index.html")
And an index.html in my templates/monitor that goes like:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<p>Value: {{ value }}</p>
</body>
</html>
When I visit the page I only see Value:
How would I write this correctly so it can print the variable?
pass the value into ur render object
it's called Django context. It's the object (dictionary) which is passed to your template.
def home(request):
value = 1
context = {'value': value}
return render(request, "monitor/index.html", context)
If the template you reference the keys in the context. So if you wanted to change it to {'value2': value} you would access it via {{value2}} within the template
hey guys, im building a flask website
and ive this piece of code
@app.route('/rooms/<int:room>/message/<int:id>/delete')
@login_required
def delete_msg(id, room):
msg = Message.query.get(id)
current_room = Room.query.filter_by(code=room).first()
if msg.sender == current_user.username:
db.session.delete(msg)
db.session.commmit()
return redirect(f"/rooms/{room}")
but it gives me this error:
AttributeError: 'scoped_session' object has no attribute 'commmit'
but i dont even understand why im in a scoped_session
can i somehow change that?
i'm front dev and do u have front-end server? i will sell my websites and buy full course of front-dev
for 5$
hey
Hi, when using a jsonify return in flask how do i use a result in html?
@app.route("/prices", methods=['GET'])
def get_prices():
test = 1
return jsonify(test=test)
<h1> {{test}}</h1>
^ gives a blank result
@app.route("/prices", methods=['GET'])
def get_prices():
test = 1
return render_template('file.html', test=test)
try this
<h1> {{test}} </h1>```
need jsonify as im pulling data from a database.
oh ok
@app.route("/prices", methods=['GET'])
def get_prices():
#database request that returns
test = "hello"
return jsonify(test=test)
{% if "h" in test %}
<h1>good</h1>
{% else %}
<h1>bad</h1>
{% endif %}
thats what im trying to achieve
@app.route("/prices", methods=['GET'])
def get_prices():
#database request that returns
test = "hello"
if "h" in test:
return "Good"
else:
return "Bad"
return jsonify(test=test)```
maybe like this?
it shows "Good" in my browser
@app.route('/', methods=['GET'])
def initialization():
for i in User.query.all():
ip = request.host
if ip in i.host:
return redirect(url_for('login'))
else:
return render_template('initialization.html')
@app.route("/login", methods=['GET', 'POST'])
def login():
if current_user.is_authenticated:
return redirect(url_for('doctor_information', name=user.name))
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(name=form.name.data).first()
if user and bcrypt.check_password_hash(user.password, form.password.data):
login_user(user, remember=form.remember.data)
next_page = request.args.get('next')
user = User.query.filter_by(name=form.name.data).first()
return redirect(next_page) if next_page else redirect(url_for('doctor_information', name=user.name)) # error: UnboundLocalError: local variable 'user' referenced before assignment
else:
flash('Login Unsuccessful. Please check email and password', 'danger')
return render_template('login.html', title='Login', form=form)```
How can I make this right?
Use global
global 'your variable'
This article is useful https://vbsreddy1.medium.com/unboundlocalerror-when-the-variable-has-a-value-in-python-e34e097547d6
In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within…
@terse vapor
Yes?
I just answered you
let's say that your variable name is count
All you have to do is type global count
I think you should use it for the variable user
If you still didn't understand, read the article I've sent
Guys, how can I scrape all those emails in this pic using selenium python?
I just want to print them in my console
select them with an with class or id which ever they have
for example: ```
mails = driver.find_elements_by_class("mail_class/id")
for mail in mails:
print(mail)
but dont ask me how to get the value bc u only get the selenium id/element and I'm stuck at that too
Am struggling find the correct class or id
wait why? you opened dev tools and look at the css class/id or at the tags and then play with it and try to find it
Hi, asked the same question before but still cant figure it out.
How do i use a jsonify return in html ?
@app.route("/prices", methods=['GET'])
def get_prices():
#database request that returns
test = "hello"
return jsonify(test=test)
html:
{% if "h" in test %}
<h1>good</h1>
{% else %}
<h1>bad</h1>
{% endif %}
Whatever I try it print very weird thing
Whatever I use css selector, x path, class or id
It print what I use and what I pass
emails = (By.CSS_SELECTOR, 'grid1cbd304ad-c72f-4e7e-b01e-503faa0ae02d > div > div > div > div.azc-grid-tableContainer.azc-br-muted > div.azc-grid-tableScrollContainer.azc-br-muted > div > table > tbody > tr:nth-child(1) > td:nth-child(4) > div') for email in emails: print(email)
the output: css selector
grid1cbd304ad-c72f-4e7e-b01e-503faa0ae02d > div > div > div > div.azc-grid-tableContainer.azc-br-muted > div.azc-grid-tableScrollContainer.azc-br-muted > div > table > tbody > tr:nth-child(1) > td:nth-child(4) > div
idk the answer but ill give you some examples i found:
https://stackoverflow.com/questions/23902596/how-to-use-flask-jsonify-and-render-a-template-in-a-flask-route/23902960
https://stackoverflow.com/questions/23038710/accessing-python-list-in-javascript-as-an-array/23039331#23039331
and the basically say use the tojson filter in the template.
idk if that helps but good luck
how do I make my website computer, ipad only using flask
For some strange reason my div elements won't show on my browser, nothing is wrong so far
Is there anything inside the div?
Yeah
Can you share the code?
It's a modal that's suppose to pop when button clicked. I was about to style it then I tested it didn't work sure
Sure 1 sec
<div class="modal" id="modal">
<div class="modal-header">
<div class="title"> Example Modal</div>
<div class="close-button"> ×</div>
</div>
<div class="modal-body">
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
</div>
</div>
<div id="overlay"></div>
.modal{
position: fixed;
top: 50%;
left: 50%;
}
``` not done styling but bothers me why it doesnt show?
The styling doesn't even work with fixed width
Thanks for the links.
I dont know if it would work
When I Run a HTML Code in vscode it shows me this. How to fix this?
That's not how you access an html file
Oh then?
ok
@cold ether I would also recommend using https://marketplace.visualstudio.com/items?itemName=ritwickdey.LiveServer
As you can perform hot reloading, which is a bonus.
couple of things. Your HTML isn't valid.
You need to put the actual path
Not the words pathtofile
Second, make sure to read the link I sent you. It shows you how to run it with live server if you'd rather that
also file type should be lowercase
ok i will do those things brb got some work.
can I display a metalabs graph into django?
I have no idea what metalabs graph is
but perhaps you can convert it to some image format (png)
then it would be not a problem to render it in django?
Yeah that’s what I’m going to do. Create the graph in python then save it as a ping and upload that
For those who need to build integration between teams and have a large amount of fake data, check out https://github.com/ghandic/jsf - it has a seamless integration with FastAPI
is it possible to serve remote html files in flask? in context, i want to serve discord attachments which are html. trying to avoid downloading them and then serving them
you could return a redirect?
Hello, can someone recommend me a way to generate refresh tokens for a web api?
Can a wtforms class, containing only a SubmitField, have a customer validator? (validator will check something in database)
I am new bee to python should I dive into django or flask inweb development?
Do you know HTML, CSS, or JS?
Also, if you're new to Python, I suggest you don't jump into web development yet.
You should focus on learning the basics of Python, not jump into a bunch of different libraries.
But to answer your question, Flask is probably better if you're new
Yeah
I also currently working on cakephp
Backend
Ok thanks for the insights
hello, is anyone can help me to figure out my problem? i'm making a website with django but when i'm making my models from model.py, and then, when i try to make the migrations, it fails and says: name "model" is not defined... been tryna check google to get some informations about it but still doesn't working...
for example, here is one of the class: ```py
from future import unicode_literals
from django.db import models
class PretReservation(models.Model):
id_groupe = models.IntegerField(null=True)
date_pret = models.DateTimeField(auto_now_add=True)
id_module = models.IntegerField(unique=True)
statut = models.IntegerField(null=True)
pret = models.ForeignKey(Composant, on_delete=models.CASCADE)
groupe = models.OneToManyField(Groupe, related_name="groupe", blank=True)
module = models.ManyToManyField(Module, related_name="module", blank=True)
composant = models.OneToManyField(Composant, related_name="composant")```
U are referencing the Composant model before you even create it. try changing the sequence of your model so that this cant happen
@native tide yep thanks, it works out!
np
I'm not happy with django async 😦
sure wrappers can be a solution but I find myself writing sync_to_async wrappers to everything ...
Use FastAPI 😄
@app.route("/delete-patient/<int:patient_id>", methods=['POST', 'GET'])
@login_required
def delete_patient(patient_id):
detail = Detail.query.get_or_404(patient_id)
patient = Patient.query.get_or_404(patient_id)
db.session.delete(patient)
db.session.delete(detail)
db.session.commit()
flash('患者已被删除!', 'success')
return redirect(url_for('patient'))```
Detailed information is connected with patient_id, so a patient_id = 1 will match with detail_id = 1, but if I did not create a detail_id for the patient, I cannot delete that patient. How do i fix it?
How can I change of context with selnium python ?
I have do:
seq = driver.find_elements_by_tag_name('iframe')
print("No of frames present in the web page are: ", len(seq))```
but he say there are one iframe
but in my console, he say there a many iframe
but i cant change the mimtype
Why would you change mime type?
cuz discord attachments autodownload, i want o serve them
how would i use a logged in users name for the file path like this?
<img src='{% static "assets/user_profile_pic/"+{{name.username}}+".png" %}'```
You should make your own filter tag for that, I think
Do you have an example url?
Oh, forget about the previous answer. You could make it like this: ```html
<img src='{% static "assets/user_profile_pic/"|add:name.username|add:".png" %}'
Fastapi with html templates?
yeah
just wanted to know if your supposed to do that
Kinda meh, I think it's overload
and not flask
No.
yea i see
FastApi is for developing, surprise, API asap 🙂
It is a good tool, but it doesn't have built-in template lang, orm and so on..
thanks ill try tha!
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_admin import Admin
from flask_admin.contrib.sqla import ModelView
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///admin.db'
app.config['SECRET_KEY'] = 'mysecret'
db = SQLAlchemy(app)
admin = Admin(app)
class Person(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(30))
admin.add_view(ModelView(Person, db.session))
if __name__ == '__main__':
app.run(debug=True)```
This work only like this, but if i seperated the code into init.py model.py, the code doesnt work anymore
The error says the admin.add_view(ModelView(Person, db.session)) the model is not defind
from flask_script import Manager
from flask_admin import Admin
from flask_admin.contrib.sqla import ModelView
app = Flask(__name__)
db = SQLAlchemy(app)
bcrypt = Bcrypt(app)
login_manager = LoginManager(app)
login_manager.login_view = 'login'
login_manager.login_message_category = 'info'
admin = Admin(app)
admin.add_view(ModelView(User, db.session))
from flaskblog import routes```
class User(db.Model, UserMixin):
__tablename__ = 'user'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(20), unique=True, nullable=False)
number = db.Column(db.String(11), unique=False, nullable=False) ```
admin.add_view(ModelView(Patient, db.session)) this is the problem u are searching for. Patient isn't imported in init.py file
so u want me to from app import Patient?
from .models import User
ok
but now it have ImportError: cannot import name 'db' from partially initialized module
Oh man I've seen what you've done totally. It is a bad structure at all. I can't help u with it, read about project organisation in Flask. The stuff you've done is kinda....awful
So I can describe how to finish this awful structure... TO MAKE IT MUCH MORE AWFUL.
Seriously, read the docs to make it beautiful 🙂
😅
I know the structure is... awful, but is there any way to make the admin work?😅
Yes. Place all in one file like b4. With separated like this modules you'll stuck rn
ok
Hi all. I have a question related to Django. I have a report script that I need to adapt into a django app.
The issue is the report can take a very long time (sometimes up to 8-14 hours)
I have a question in help-apple if anyone is interested in the report. But my question is any ideas on how to keep the session active? I am not well versed in async although I think this is the solution. Any places to start?
Read about celery.
ok thanks @north pollen
nvm, i fixed it, i add the line into the route.py and it worked😅 lol
Yet another awful, but working project, gooood job xD 👍
😁
How do I put the text on the same line:
<h1>
<p style="text-align:center;
font-family:Georgia;
font-size:50px;
color:#CC0000">Big Hero 6</p>
<p style="text-align:right">2015</p>
</h1>
I am new to html so please help
...
...
@
HELP
PLEASE
You can use css
On the element/div around it, you can do display: flex;
I have another question😅 , so the flask_admin shows all rows inside the page, is there anyway that we can reduce to only shows name?
Try to google that question if u don't find help here...
Sry mate, I can't help u there, my one and loved framework is Django 🙂
😅 good idea, lemme search on google rn
Can anybody here help@me with restapi’s ?
why would not logged in not all be on one line here
<div class="sidebar">
<a href="/home">Home</a>
<a href="#inventory">Inventory</a>
<a href="#did">DID Database</a>
<a href="#did">CER / 911</a>
<a href="#did">Admin</a>
<a class="active" href="/accounts/login">Login</a>
<div style="position: absolute;bottom:0%;left:50%;transform: translate(-50%, 0%);">
{% if user.is_authenticated %}
<img src='{% static "assets/user_profile_picture/"|add:user.username|add:".png" %}' height="100px" width="100px">
<p style="color:white;">{{ user.get_full_name }}</p>
<p><a href="{% url 'logout' %}">Log Out</a></p>
{% else %}
<img src="https://i.imgur.com/2nLLtVN.png" height="100px" width="100px">
<p style="color:white;margin-bottom:5px;">Not Logged In</p>
{% endif %}
</div>
</div>```
.sidebar {
margin: 0;
padding: 0;
width: 200px;
background-color: #363636;
position: fixed;
height: 100%;
overflow: auto;
box-shadow: 3px 3px 3px #000;
font-size: 20px;
}```
You have nothing saying that it shouldn't be on multiple lines
im brand new to html/css, what do i put so it doesnt?
when then code looked like this it was all on one line
<div style="position: absolute;bottom:0%;left:50%;transform: translate(-50%, -50%);">
<img src="https://i.imgur.com/2nLLtVN.png" height="100px" width="100px">
</div>
<div style="position: absolute;bottom:0px; left:20%;">
<p style="color:white;">Not Logged In</p>
</div>```
You can add display: inline; to make things be inline
<p style="color:white;display: inline;">Not Logged In</p>```
You need to have a space iirc
oh!
After the semicolon after white
sadly same issue
But if the text can't squish, it might break onto a new line
You can make the text smaller
Or decrease the margin/padding
i think padding and margin are 0 on the sidebar
Is it breaking on large screens as well?
this is a full screen window at 1080p
Then you should probably just make the text smaller
the text should fit though right? like i said, before i added in the if/else it fit
this is it without the if/else
Is tgere a way I could use django with react wothout using an api
yolo, gonna switch from django to fastapi and just main it over node.js, feels bad learning it for months and not getting a job as planned
Hi there , just a simple question How do I sync my project and the database between two devices regularly?
Is there any way to secure flask-admin dashboard like login_required thing? Most answers on google are using current_user and login_user, which I have been used on the User role, so what should i do?
make a custom wrapper function that checks if the user is an admin or something
Hey All, just wanted to share a short introduction to EasyAuth & FastAPI
https://joshjamison.medium.com/creating-secure-apis-with-easyauth-fastapi-6996a5e42d07
hi, i have a problem to solve but i don't know how 😄 let me explain :
i'm building a webapp to calculate your kalories, my webview :
my models :
class Product(models.Model):
name = models.CharField(max_length=200)
kalories = models.IntegerField(default=0)
protein = models.IntegerField(default=0)
glucide = models.IntegerField(default=0)
sugar = models.IntegerField(default=0)
lipide = models.IntegerField(default=0)
satured = models.IntegerField(default=0)
class Meta:
ordering = ("name", "kalories")
class Menu(models.Model):
name = models.CharField(max_length=200)
products = models.ManyToManyField(Product, through='TProductMenu')
instructions = models.CharField(max_length=1000)
def __str__(self):
return self.name
class TProductMenu(models.Model):
menu = models.ForeignKey(Menu, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
number = models.IntegerField(default=0)
weight = models.IntegerField(default=0)
i don't know how to calculate total kalories
my view code :
<ul>
{% for menu in menus %}
<ul>{{ menu.name }}</ul>
{% for TMenuProduct in TMenuProducts %}
{% if TMenuProduct.menu.name == menu.name %}
<li>{{ TMenuProduct.product.name }} | kcal : {{ TMenuProduct.product.kalories }}</li>
{% endif %}
{% endfor %}
<li>tt kcal : </li>
<br>
{% endfor %}
</ul>```
i can calculate with JS but i think there is a better way to do
Ok, If you need HTML help just message, just got on
@stable zinc is there more code that you aren't showing us
hmm oh, yes my view code :
def menu(request):
menus = Menu.objects.all()
TMenuProducts = TProductMenu.objects.all()
context = {
'menus': menus,
'TMenuProducts': TMenuProducts
}
return render(request, 'alimentary/menu.html', context)
is TMenuProducts collection of Product type objects
No Tproductmenu is a through table in bdd between Menu and Product
ok, are the total kalories taken from a collection of Products?
kalories are fields in the product table
there is no total kalories in BDD, but i don"t know if i can add a total kalorie field in the tmenuproduct
maybe an aggregate function ?
I don't know what framework, database, or what you are using but you could either
- use a function like sql's SUM at the database to aggregate a sum from all rows of interest from the table
- iterate over a list of objects of type Product in python to add all of the calorie fields of each object
I'm sorry I wish I could do more
Also, if you are using a client side technology like React or Angular you could aggregate it in the client before displaying, it's really up to you
at the moment i'm using sqlite for the dev, and if i use an iteration list on product i have to make an additionnal dictionary to link menu, product and tproductmenu in the backend to send in the context
but yeah i think i'll code the display in JS
thx for your time 😉
where would you store django signals? in project structure?
yeet
???
nothing
are you stupid?
no need for that
if auth and auth.password == 'secret':
token = jwt.encode({'user' : auth.username, 'exp' : datetime.datetime.utcnow() + datetime.timedelta(seconds=15)}, app.config['SECRET_KEY'])
return token.decode('utf-8')```
It shows:
`AttributeError: 'str' object has no attribute 'decode'`
but I did follow the instruction from the tutorial, so is there anything i did wrong or there is another format to write this😅 ?
Oh I recently overcame this problem
thanks to help of the users here
if auth and auth.password == 'secret':
token = jwt.encode({'user' : auth.username, 'exp' : (datetime.datetime.utcnow() + datetime.timedelta(seconds=15)).isoformat()}, app.config['SECRET_KEY'])
return token.decode('utf-8')
!e
import datetime
serialized = datetime.datetime.utcnow().isoformat()
print(repr(serialized))
deserialized = datetime.datetime.fromisoformat(serialized)
print(repr(deserialized))
@inland oak :white_check_mark: Your eval job has completed with return code 0.
001 | '2021-05-05T03:09:42.110323'
002 | datetime.datetime(2021, 5, 5, 3, 9, 42, 110323)
I tried your code and it still appears the AttributeError
I mean the first piece
!e
import datetime
date = (datetime.datetime.utcnow() + datetime.timedelta(seconds=15)).isoformat()
print(repr(date))
@inland oak :white_check_mark: Your eval job has completed with return code 0.
'2021-05-05T03:11:35.292740'
everything completely fine
that's not the problem
that should be token.encode
show the tutorial.
default encoder (import json) in jwt is not able to jsonify datetime
I was literally the one who helped you with that
In this video, I show you how to use JSON Web Tokens (JWT) to authenticate users of your API. First, a user will have to login using a specially created route which returns a token. Once a token is generated, it can be sent along with the rest of the request to other parts of your API to verify the user's identity without the user having to prov...
timestamp.
Hey @cunning crown!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
Hey @cunning crown!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
Hey @cunning crown!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
Can a Django (and probably JS) guru help me with a simple task? I want to update a variable on the front end dynamically that's pulling data from my API
AJAX/Jquery stuff, going to learn it too soon
elaborate?
wait... so if you have django on an asgi server you can use async/await to speed up tasks a lot. This will brings its performance closer to fastAPI?
How do I write test for a django viewset?
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
permission_classes = [permissions.IsAuthenticated, IsManagerOrSuperUser]
filter_class = FoodieFilter
you mean django rest framework viewset
you set url for that
you can make request to this url
with using
from rest_framework.test import APIClient
# arrange
client = APIClient()
# act
resp = client.post(
f"/api/main/ip?api={settings.APIKEY}",
format="json",
)
dict_ = resp.json() # data you get, you can assert it further
# assert
assert resp.status_code == 200
Can we call that a unit test? or is it more of a functional test?
it has all characteristics of unit test
functional testing is sub category of unit testing
I am so confused between all these types of tests: functional tests, unit tests, integration tests, e2e tests.
Any body can help me to make a bot dashboard in django
lets try to be less confusing then, if I get them right...
everything is test
but unit test is super duper fast test, which checks only your unit of code piece and runs isolated from other tests.
functional test is the same as unit test, but makes sure to test only results of the tested piece of code, using your part of code as black box. The most effective type of unit tests btw. Not always can be applied though, or can be but only after refactoring. It needs your code to be not having... 'secret'/'global' input/outputs to other app sections?
integration test is unit test which is not meeting one of criterias (being fast, not using dependencies, or checking too much of your code behavior), usually used to test work of app with integration of one of dependencies, database or file system and e.t.c. Usually can't be paralleled, because tests use only one existing dependency, which is hard to have isolatingly paralled. Filesystem? Database?
e2e is... like integrating test, but with all dependencies included. Instead of testing one dependency per time, it tests all of them at the same time. The category of this test should be as close to real user as possible perhaps. Using Seleinium to test web site deployed to hoster, should qualify as e2e?
Does it make sense that a cors library would close websocket connections if there is no "origin"?
Yes
Because websockets are initialised via a htto request
So the normal rules of cors still apply
Providing this is in reference to. Browser connection
I'm using Heroku to host a Flask application. The idea of the flask application is to manage a discord bot that I am coding. I can't figure out how to host an web application that runs this discord bot simultaneously (A worker dyno is used for the discord bot, and a web dyno - Gunicorn - is being used for the web app, and I can't get the discord app to run simultaneously with the web app - Using just a web dyno to run both). Any help available would be appreciated - I'm trying to keep to a free hosting option with Heroku :)
i personally hate heroku
it never works (for me)
i would use replit.com
for hosting
I just use rented vps, it is pretty cheap, 3$ per month
and enough space to run multiple pet projects
I get 25 GB SSD, 1 GB RAM, and 1 Core with an OS of my choice for this price
My problem with repl is that I found it really slow to develop in - it takes a lot of time t install dependancies, and when running a web app with flask, there are alot; I prefer to use pycharm instead. Is there any way to automatically pull into repl from github after every push, similar to heroku?
Unfortunately I don't really have any budget that I can spend :/
@thick cove since when did websockets have no origin?
which is more suitable for backend work, django , flask , or laravel (php)?
forexample non browser connections
how do i make a button in django?
Well for the websockets I'm working on you should be able to connect both from a browser and from a python script
I'm just thinking it's bad practice for a CORS library to automatically abort websocket connections just because there is no Origin header
How so, it doesn't deny requests with no origin?
Though generally cors is aborted by the client not the server
src/quart_cors/__init__.py lines 305 to 309
async def _apply_websocket_cors(*, allow_origin: Optional[Iterable[OriginType]] = None) -> None:
allow_origin = _sanitise_origin_set(allow_origin, "QUART_CORS_ALLOW_ORIGIN")
origin = _get_origin_if_valid(websocket.origin, allow_origin)
if origin is None:
abort(400)```
oh that's sick 👀
If I go to localhost:port/url will it return a value of a function with a decorator @app.route("/url") in Flask?
Try it and see
Has anyone come across a good clean solution for implementing django-style formsets in Flask with WTForms?
Is that aimed at me?
yes, just curious
It seems pretty obvious what the benefits of a formset are no?
From what I remember of using Django it allowed easily having a form-per-entity of which the user could fill in an arbitrary number and the backend was smart enough to know which ones needed handling
Maybe I've mis-remembered
Hey am working on portfolio website.
Can someone tell me how to divide code and give comments acc. In html file.
i see
Comments are done with <!-- commenthere -->
My use case is that I want to have a page which displays a "single" form, within which there is a field per object (from a reference table, lets call it R) which allows the user to adjust the number of that object which they "own". Changing this would create or update a row in another table (lets say U) which holds the id of the object from R and the quantity thew user "owns". I want the user to be able to edit all the related object quantities in a single page/form
has anyone used tailwindUI components?
With formsets you'd just have a form-per-object which were all neatly handled by django
I have
ooh, nice. what do you think of them? I'm on the verge of buying it now.
They're amazing. I've only used the free version, but it seems like a really nice thing to buy because the code is so clean and the components are really nice.
tailwind?
Yup
what is it
It's a framework with a bunch of predefined utility classes so you don't have to write custom css
well yeah but isn't that every css framework
@calm plume bro i was asking how to divide d code
is it special in any way?
No. Most are components, Tailwind is just utility classes
That's also components like navbars
https://tailwindui.com/#components
alright, I'll buy it then. hopefully i can reuse for future projects too.
i'm a bit surprised there's no leaks of them. I've used chakraUI and antd before, but I don't really like them too well.
Tailwind is things like w-1 for width: 0.25rem, h-4 for height: 1rem
Also, Bulma is no js
With Tailwind's JIT compiler, it's very flexible
interesting
Tailwind UI's React and Vue versions are rather new
And some of the better components are new too.
So I'm not surprised that there aren't leaks
what do you mean by "react and vue" versions? is it something similar to bootstrap-vue, for example?
yeah they provide react components instead of the html with css classnames
i believe
$315, hopefully it'll pay off 😄
oh ok, that's cool. i've tried using vue with things like bulma and bootsrtap, but tailwind sounds really exiciting from the looks of it :)
oh so tailwind has separate plans right? based on your needs?
welp, I just found you can go on a US vpn and the price drops to $250, nice to know
yeah, it's a one-time fee. You can choose from 2 sets of component, one for marketing and one for application.
but that's just tailwindUI, prebuilt UI components (as I'm lazy). tailwindcss differs
ohhh, so tailwindUI has all the builtin support for things like vue/react, while tailwindcss is just a raw css framework?
TailwindUI is a component library, TailwindCSS is utility classes.
ohhhhhh ok
if you guys wanna use it you can use my account, it works for react/vue
can anyone help me with a django query?
Hello friends
Anyone can help me with Visual Studio Code?
I'm working with a web page
Isn't that like, not legal
Hey yo, i have django and celery, and should i create task to every email sending, or should i deley only django.core.mail.send_mail
wich point is better?
free components are free components 🤷♂️ 😉
tailwindcss is just bootstrap, but with more classes
so far the component library is real good
Other than Tailwind doesnt have a direct dependency on JS
as well as being able to compile down to a much smaller size
Wdym?
Bootstrap last i checked has a dependency on JS which means if a browser doesn't support X JS version it'll break your components along with CSS
Bootstrap will always come with the extra bloat of JS
Yeah
Well, tailwind has a compiler too
And relies on PostCSS and PurgeCSS
Unless you use the CDN, which is very slow
the cdn is generally ~20ms
but yes it's slower because it's serving everything
and also the dependency on JS is for the compiler not in order to be user friendly on the deployed site.
I need help with apache on a vultr VPS. I installed apache, opened all the ports, made sure the configuration is correct and that the server is running, disabled the firewalls (And allows the ports through) and I still do not get the default splash page. I have already done a clean reinstall of apache. The server can be pinged fine, my postgresql database on the server works fine.
how do i get pictures, or animations like this.
@opaque rivet did you buy the tailwind ui
yeah, its looking much better than a layout i'd do myself
so i know in a table you can make it editable with this
<td contenteditable='true'>045FB9B6DEC5</td>
but how do i make it editable and it persists for all users or through refresh?
sounds like a use case for a database or some sort of way to store data!
yeah i was hoping to avoid a database, because while ive used sqlite with python a lot, i have 0 clear how to implement a database with a website
but i figured i might get that answer when i asked the question
@wooden ruin would i have to use mysql or would a simple csv or sqlite work well with django/html
it depends on how much data you want to store and how you plan on using it
are you using django?
django has builtin support for sqlite3 which is nice for quick database development
yea definitely going to need a database, django makes it easy to create databases without ever writing a line of SQL code, just python
oh nice! ill look up a tutorial, unless you know of a good one
django docs are always really helpful, here's a useful link for queries and models
https://docs.djangoproject.com/en/3.1/ref/models/querysets/
ok that makes it easy because you can represent your table as a table in your database
excellent! thanks, ill read up on it
React Native or flutter
why do I get column error when I have it? https://dpaste.org/PdP0#L4,52,57,65
I dunno
Why am I having trouble mapping things to the source m2m field? https://dpaste.org/JPGA#L3,63,67,112
when you .through you are accessing an intermediate table which django creates, it has the fields:
https://docs.djangoproject.com/en/3.2/ref/models/fields/#django.db.models.ManyToManyField.through
so in this case there isn't any name field.
I recently started learning about browser fingureprint technology and I have a doubt. Acc to my understanding, After getting all the identifiers like screen res, canvas, fonts and more the algorithm generates some hash string which is unique to that browser. So, my question is how is this fingur print passed to the servers? Via. Headers? Inside header cookies? As a body? And when? Does it go with each and every request or it has some other behaviour?
Pls @me before writing your answer. Thanks
You can store the hash as a cookie client-side. The easiest way to transport this to the server would be via a header (instead of the body of the request) so that the request can be GET, POST etc. to suit your needs.
It should be sent with every request, & you can enforce that with middleware on your server to ensure that header is present in every request.
how do I get started with django
what's a good resource to start a data extracting website
hi! im using react.js and i was wondering how to make my react page have multiple pages.
do i use react-router? or are there better options
react router. better option? next.js 🙂
ah
next.js
i always wondered what it did...
if im not using SSR, do i just use react-router?
honestly, my understanding of it isn't great either. next.js improves SEO compared to CRA because when a request reaches your frontend, it returns a blank html page and then hydrates the page by manipulating the DOM and changing the content. Thus web crawlers can't index your site too well (there's lots of parameters involved with it). Next.js pre-renders HTML pages with your page information (static generation) thus helping with SEO (and performance).
next.js also has it's own, really nice & simple routing.
yeah, if you're not using SSR use react-router - but using next.js will have SSR out of the box as it has its own express.js server
im not sure whether i should use SSR or not
i know that CSR is simpler but apparently you should use a mix of both for the best results
i have more research to do on the topic, but I think it's better to do due to the importance of SEO. with next.js there's SSR out of the box with no setup, so that's a bonus. But one downside is that if you're using modules which require client-side APIs like window, they need a bit of tinkering
they have a tutorial on their docs, and ask a question after each lesson. it's pretty decent. apart from that I would read articles / go on youtube - which i still need to do 😁
alright, thanks for all your help
it's not a big learning curve
i've been learning react and JS itself for about 15 days now and i've been doing pretty good so far
nice... you should join the reactiflux discord, they have some geniuses over there
will do
also if you ever get bored of making your own UI components, I can provide you with tailwindUI comps.
i've heard of tailwind, im fine with my own components for now
that might change when i need to make more complex ones
but for now im good
👍 also if you want any good resources for learning redux / typescript (which are a killer combo for react) codeacademy is quite good, i might have a few spare pro accs
password = forms.CharField(label="Password", widget=forms.PasswordInput, validators=get_default_password_validators())
any idea why it wont work?
django forms th.
what is the effient way to do the following?
# try:
# vulnerability_id = Vulnerability.objects.get(cveid=cve_objects.get('cveid'))
# except Vulnerability.DoesNotExist as err:
# pass
# try:
# exploit_id = Exploit.objects.get(vulnerability=vulnerability_id)
# except Exploit.DoesNotExist as err:
# pass
@sand glen found a good article explains why next.js is better than CRA for SEO, giving examples too.
I just runned a simple app made with flask and flask-socketio and it returned an error:
https://pastebin.com/BwxLtwkv
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
it shouldnt return any errors
this login form redirects me to an external website
this to be more precise
i don't know why it does that
which code extension is this 🤩
Hey guyz, plz have a look on it! I am totally confused about what I did wrong here 😢
which website?
from what I'm seeing, you are providing TaskForm an instance parameter of Task, which is a class. Django expects an instance
bcz in line 26 I am updating my form. I don't want to add new task
I only want to update the old task
right, so wouldn't it be task, not Task?
ohhh damn
It worked Thanks a lot
I have one problem will catch you if I found it again!
how can i make a simple site like https://paste.pythondiscord.com where my friends can paste things into it
wait are you serious?
😂
yes

trying to decide between vue and react.. i dont have much experience in js and really want to learn ts, and have more knowledge in backend like flask. any suggestions?
i don't think it matters that much whether you go with vue or react
Hey guyz, i am bit confused on choosing a vps(virtual private server) for deploying my django project, i want to know minimum system requirements for it? Is there some method to test the stress on my django website.
Hello guys, I have a challenge and I would be grateful if you could give me some clue...
I want to run a Dash-Plotly (a framework based on Flask) application inside a Django app. I know Dash has a framework called django-plotly-dash but what I want is a Django app that our developed Dash(aka Flask) apps can easily be imported and run
is there any idea???🙏 🙏 ♥️
Is it possible to use formset for just one specific field out of many fields when submitting a form having several fields with same name?
does anyone have experience with django websites and can help me? for the life of me i cant figure out how to load static files into a production website
use whitenoise
I tried using whitenoise but they require a lot of setup that doesnt seem to work with my website basically it asks me to use certain commands that dont line up with my files and what i have installed
no it doesnt need a lot of setup
"it asks me to use certain commands" what commands?
Maybe i set up wrong or followed a bad tutorial
just type whitenoise readthedocs on google then go to docs youll see how eazy it is
i think my problem is with gunicorn
procfile?
gunicorn.service
Why can't you serve static files from django in production?
My user is messed up i think
you can if you set debug = true
but it's bad practice
and im deploying the website live
I have it working locally
Yeah, but in production you'll want debug off. I'm just wondering why the production sever can't serve static files.
use whitenoise
Well i have njinx and I'm trying to have that serve the static variables but the .sock file wont generate
So the static-file settings in settings.py are only for development? e.g. STATIC_ROOT
no
not only
when a user uploads an image itll go to that folder
it can but you shouldn’t use it
it’s not secure
nor optimised
@nimble epoch do you have experience with gunicorn?
yes
i cant figure out why the .sock file wont generate
This is the tutorial ive been looking at
what does .sock do?
it indicates the file did not start correctly
gunicorn*
it would be something like this
aha never used it. so you think the problem is in here?
yea since that file never gets generated
so in here
i think i messed up one of the variables
because my project's file hierarchy is VERY different
this is the issue gunicorn tells me too
gunicorn.service: Failed to determine user credentials: No such process
im checking this if i could get something
never deployed one on linux. gotta try that.
do you know what im supposed to set user as?
nope
python manage.py collectstatic with gather them from all folders to your STATIC_ROOT
@summer grove does it through any error?
sudo journalctl -u gunicorn
returns with
@vestal hound not secure? In what way?
Also for static files, does nginx serve them in production?
setting it to that user crashes it and removing it has no effect