#web-development
2 messages Β· Page 148 of 1
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template("index.html")
do I have to use jinja?
you need to write <link rel="stylesheet" href="../css/bootstrap.min.css" /> bc they arent in the same directory
is there anyone who is familiar with Django frameworks?!
'..' is for folders that are in a directory above
the css folder is in the same directory as index.html
It would have to be './css /...'
i want to start working on this in linux...if anyone could guide!!
no ../ is for folders below and i suggested the ./css/ alread but also didnt work for him and he didnt say he uses flask which probably means he needs to have static folder or so and the jinja syntax
ok
yeah i am familiar but what kind of guide do you want? how to set it up or more?
Im not sure tho bc im not that familiar with flask just try asking someone else or try googling it
ok
yes setup and to make my first project
ok yeah i could guide you or suggest you some really good tutorials if you want
yes please...do any of the one ..which ever u feel comfortable with
some good tutorials are:
https://www.youtube.com/watch?v=xv_bwpA_aEA&list=PL-51WBLyFTg2vW-_6XBoUpE7vpmoR3ztO
https://www.youtube.com/watch?v=UmljXZIypDc&list=PL-osiE80TeTtoQCKZ03TU5fNfx2UY6U4p
and him for some advancer things or if the others are to slow
https://www.youtube.com/channel/UCRM1gWNTDx0SHIqUJygD-kQ/playlists
but i can also call you and tell you by screenshare what to do bc that takes max 10 min
Your choice
NOTE: Updated and compatible with Django 3.0
In this video I'll introduce my django crash course series. In these tutorials we will will be building a customer management app. Part one will cover installing django and getting our basic app setup.
Follow me on Twitter: https://twitter.com/dennisivy11
Linkedin: https://www.linkedin.com/in/dennis...
In this Python Django Tutorial, we will be learning how to get started using the Django framework. We will install the necessary packages and get a basic application running in our browser. Let's get started...
The code for this series can be found at:
https://github.com/CoreyMSchafer/code_snippets/tree/master/Django_Blog
Flask Tutorials to cr...
JustDjango is a dedicated learning resource for web development with a focus on Django. Our goal is to make learning Django as easy and accessible as possible while teaching people the necessary skills to use Django either in their job or as a hobby.
We teach here on YouTube but these videos were only made possible thanks to the support on our ...
https://learning.edx.org/course/course-v1:MichiganX+dj4e102x+3T2020/home @native tide i am thinking to go with this course...can u pl. goo through this and say should i do this or something else
yes screen share would be cool @native tide
ok i add you
the id should correspond based on what is the task_content is
{% for task in tasks %}
<tr>
<td><input type="checkbox" id=id></td>
<td><label for=id >{{ task.content }}</label></td>
how can i differentiate my id & for attributes within my loop???
Do you mean you want the id of the input/checkbox to be equal to your task one? bc if so you just need to pass in {{ task.id }}
Ahm I'm not sure but... its only strike out the first row always when i check the second checkbox it wont strike out the second row :p
It look like it is
i think i understand your problem but why arent you solving that with javascript. I think it would be simpler
Hmm i don't have much knowledge on javascript
I just copied it :p
document.addEventListener("change", e => {
if(e.target.matches("input[type=checkbox]")){
document.querySelector(`label[for=${e.target.id}]`).classList.toggle("strike");
}
})
what should i change here?
Hey guys, ES and Javascript are the same thing right?
they are kinda the same but theyre are more versions es6,es7,es8... Its basically just the syntax that changes on some things not on all i think
im not a js pro
@fast ether actually i found a solution without javascript
<tbody>
{% for task in tasks %}
<tr>
<td><input type="checkbox" class="check-with-label" id="{{task.id}}" /></td>
<td><label class="label-for-check" for="{{task.id}}">{{ task.name }}</label></td>
</tr>
{% endfor %}
</tbody>
with following css:
.check-with-label:checked + .label-for-check {
text-decoration: line-through;
}
i tested it and it works. only strikes the label of the clicked checkbox
it's looks like it didn't work
wont work in <td> tag
are you sure? I just wrapped it in a <td> tag and it still works
Yeah won't work i removed the <td> tag it works but i need it to be inside <td>
I'm using Flask to make a webapp that gets a random Reddit post from a specified Subreddit. Though it seems like JS won't redirect me, I want to change the args of the page from 0.0.0.0:8000/?sub=memes to 0.0.0.0:8000/?sub=unixporn.
Here's my JS:
function changeQS(key, value) {
let urlParams = new URLSearchParams(location.search.substr(1));
urlParams.set(key, value);
console.log("http://0.0.0.0:8000?" + urlParams.toString());
let nexturl = "http://0.0.0.0:8000?" + urlParams.toString()
window.location.replace(nexturl);
}
function submit_new_sub() {
console.log(document.getElementById("subreddit_to_get_memes_from").value);
changeQS("sub", document.getElementById("subreddit_to_get_memes_from").value);
}
@fast ether can you send the code you are using?
<table>
<tr>
<th>Done</th>
<th>Task</th>
<th>Added</th>
<th>Actions</th>
</tr>
{% for task in tasks %}
<tr>
<td><input type="checkbox" class="check-with-label" id="{{task.id}}"></td>
<td><label class="label-for-check" for="{{task.id}}">{{ task.content }}</label></td>
<td>{{ task.date_created.date() }}</td>
<td class="col-md-3">
<div class="col-md-3">
<button type="button" class="btn mb-2 mb-md-0 btn-secondary btn-block"><span><a href="/delete/{{task.id}}"onclick="return confirm('Are you sure?')">Delete</a></span>
<div class="icon d-flex align-items-center justify-content-center">
<i class="ion-ios-trash"></i>
</div>
</button>
</div>
<br>
<button type="button"><a href="/update/{{task.id}}">Update</a></button>
</td>
</tr>
{% endfor %}
</table>
{% endif %}
.check-with-label:checked + .label-for-check {
text-decoration: line-through;
}
List of lecturers (1 point)
When you go to the "/ create-lecturer" link, a form should appear in which we can add it to the lecturer's database (1 point)
When going to the "/ add-lecturer" link by post method, we should add it to the lecturer's database (1 point)
"/ Shuffle" - will print lecturers in a chaotic manner (1 point)
"/ Random" - randomly selects one lecturer and displays it on the screen. (1 point)
"/ Filter" - displays a lecturer whose phone number is the last digit 3
@fast ether ok yeah it was working for bc i didnt wrap it in a <table> tag lol bc havent used them in years but if you make it like that
{% for task in tasks %}
<tr>
<td><input type="checkbox" class="check-with-label" id="{{task.id}}" />
<label class="label-for-check" for="{{task.id}}">{{ task.title }}</label></td>
</tr>
{% endfor %}
So basically label and input into one <td> tag it works
Is that a question or what are you trying to say?
List of lecturers (1 point)
When you go to the "/ create-lecturer" link, a form should appear in which we can add it to the lecturer's database (1 point)
When going to the "/ add-lecturer" link by post method, we should add it to the lecturer's database (1 point)
"/ Shuffle" - will print lecturers in a chaotic manner (1 point)
"/ Random" - randomly selects one lecturer and displays it on the screen. (1 point)
"/ Filter" - displays a lecturer whose phone number is the last digit 3
and what is your question about that assignment?
oh thanks good idea finally solved it now
@fast ether just add more css some margin or padding and some border and it should look great
import pymysql
db = pymysql.connect(host='xxxxt', port=xxx, user='xxx', passwd='xxx', db="px")
cursor = db.cursor()
sql = """INSERT INTO testprov
(provinces)
VALUES
(%s, %s, %s, %s)"""
values = ['Nova Scotia', 'Alberta', 'Ontario', 'Quebec']
cursor.execute(sql, values)
db.commit()
cursor.execute("SELECT * FROM testprov")
data = cursor.fetchall()
trying to insert values into one column, since its relevant
but i get
pymysql.err.OperationalError: (1136, "Column count doesn't match value count at row 1")
i am trying to make a login with github using flask dance and it worked once, but now i am not able to logout or switch accounts or anything like that. it only uses one account. can someone please help? this is the code ```py
@app.route('/github_login')
def github_login():
if github.authorized:
userinfo = github.get('/user')
if userinfo.ok:
userinfo = userinfo.json()
return redirect('/dashboard')
return redirect(url_for('github.login'))
or if u know another way to login with github, could you please let me know?
<li class="nav-item">
<a class="nav-link" href="#features">Features</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Documentation
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="#">Commands</a>
<a class="dropdown-item" href="#">Tutorials</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="#">Server settings</a>
</div>
</li>
</ul>
<a class="btn btn-outline-secondary my-2 my-sm-0 btn-round btn-sm" href="https://discord.com/oauth2/authorize?client_id=828612857880903681&permissions=2617371767&scope=bot%20applications.commands">Invite</a>
</div>
</nav>
<div class="heading text-center" id="#features">
``` I have this, but the button does not work, it changes the url, but does not move the the featurs part of page.
@limpid python dont write in the id #features rather just feature
and it should work then
the "#features" means navigate to that id.
im trying to build a website with pyhton and have no idea what im doing or where to start lol where do I start?
-learn the basics of html/CSS
-learn Python
-Choose a framework (Django/Flask )
start building
thanks
Hello everyone my django app, logs out automatically when I close the tab even if I didnt specified in the settings
How can I fix it
does anyone know why my css isnt connecting to django
Failed to load resource: the server responded with a status of 404 (Not Found) it says this in the console and my css doesnt update in the sources
@formal axle show the code where you connect it bc there's probably the error and mby show your folder structure and "settings.py" and "urls.py" bc of the static connection there as well
whats the difference between print and return in functions
with print you actually print it to the console and return gives it back and you can access it then or assign a variable to it
oh ight ty
Hey, so i have this API and i want to basically bind their computers HWID or UUID to their account name so they can only acess it from one computer. How would i identify a computer uuid or hwid from over a flask API?
please ping me if you can answer, thanks
I have a react app making a GET request that's CORS erroring, and I'm not sure how to fix it the correct way--Chrome says PreflightInvalidAllowCredentials, the request is submitted via
axios.get('http://localhost:8080/myroute', {headers: {Authorization: jwt}, withCredentials: true})
and the resource itself is a flask_restx resource decorated with flask_cors.cross_origin, with origin specified as my react app i.e. https://localhost:3000. What does this error intend me to do differently? I can post more code if it helps, I'm looking at the mozilla docs that I think are relevant but my origin is not '*'
this is the code connecting it <link rel="stylesheet" href="{% static 'css/main.css' %}"> This is the settings ```import os.path
STATIC_ROOT = ''
STATIC_URL = '/static/'
STATICFILES_DIRS = ( os.path.join('ecom_site/static'), )```
this is the file structure
@formal axle ok that looks actually right but did you add
urlpatterns += static(settings.STATIC_URL,
document_root=settings.STATIC_ROOT)
in the root urls.py ?
no lol didnt even know i should do that, ill do that rn and see if it works
that probably fixes it and if you ever use images do the same thing you did with static
the root is the other thing than the app right?
just wanna make sure im doing it at the right place
root is the project u created with "django-admin startproject name" so in name/urls.py
oh sry some imports are missing wait a sec
all good
those are the missing imports
from django.conf import settings
from django.conf.urls.static import static
in the terminal the "GET /static/css/main.css HTTP/1.1" 304 0" is turquoise now witch is good but it still doesnt do anything
304 means its not modified and uses a cached version.
So clear the cache by pressing "Shift + F5"
ok one sec
do u know what the command would be oin mac because that activated voice over
wait one sec
ok
u can also press "Shift + R" so "Command + Shift + R" for you i guess
ok ill try that
hmm weird still didnt do anything
it just put out "GET / HTTP/1.1" 200 3472
i updated my answer i think thats it
favicon is basically the icon you see next to the website title in the tab
yeah
it still doesnt work?
yea still not lol
weird, its updating in the sources now and showing no errors
some of my files are yellow could that be it?
yellow just means your linter shows warnings but thats not rlly important
u wanna screenshare and show it? i would add you.
dont say that everyone meant to learn everything they want
yea sure i cant talk tho because my mic is broken
Don't talk like that
yea im just joking lol
Hey, so i have this API and i want to basically bind their computers HWID or UUID to their account name so they can only acess it from one computer. How would i identify a computer uuid or hwid from over a flask API?
please ping me if you can answer, thanks
A good way to avoid errors when you're trying to develop something with Django / Flask / FastAPI [...] is having a good understanding of HTTP Requests, HTML Tags, CSS and CSS Frameworks (Bootstrap, for example) and JS (for web)
yea i got css and html and bootstrap im learning js, and gonna read up on http requests
You can do this in the cloud platform you're using to deploy the app
Under Firewall settings
Niceeee. Try developing small projects first, like file compression and decompression or text file word counting
hmm interesting
ok i will
@reef oasis thanks
oh wait i thought it would give u points
wrong server
lol no need for that hehe it was a pleasure helping you. Feel free to dm me when you face a problem
thanks
if you like videos, the Corey Schafer Flask series is supposedly good
it's on youtube
but I haven't personally watched it
you can also try reading the official docs, iirc they're not bad
Can anyone tell me how to assign the exact same value of a text-area to an input form?
Its nice to start little projects to learn Flask, like the ones I just mentioned up here.
For Python tutorials, I really recommend Sentdex, because he has a hands-on approach. I learned Flask with the docs (and stackoverflow) while I was developing an web app for my previous company, but if you need, Sentdex has a Flask playlist too:
https://www.youtube.com/watch?v=Lv1fv-HmkQo&list=PLQVvvaa0QuDc_owjTbIY4rbgXOFkUYOUB
Digital Ocean Hosting: https://www.digitalocean.com/?refcode=d1c4c6e66979
Linode Hosting: https://www.linode.com/?r=b417bc672ff52d6c055fd7a56e024939c667b0fd
Welcome to the introduction to the practical Flask web development tutorial video. In this video, we're going to be talking about our goals of this series, which are mainly surrounding the ...
Hey
How do you guys bootstrap / start a new Django project? Are there any good starter boilerplate projects out there you guys use?
Improve your Django skills by building 3 complete projects. In this course you will lean how to use Python and Django to build a URL shortener, a to-do list, and an English dictionary.
Course developed by Code With Tomi. Check out his channel: https://www.youtube.com/c/CodeWithTomi
Tomi on Twitter: https://twitter.com/TomiTokko3
Here are the p...
when using flask is there a way to get all of this gone
* Serving Flask app "miner" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [14/Apr/2021 20:17:35] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [14/Apr/2021 20:17:39] "GET / HTTP/1.1" 200 -
No
hey guys i have an issue although its with php
im trying to show players in a table form, but in the table there is an extra column whereby is a user clicks view details a model pops up showing them about the players information. the table works but when i click on any player model the information shows for player 1
Not really
this is the for loop and the model area
Because you are using a development server
I don't know php, sorry, but I use Django.
i wanted help in php, thanks though
Hi
ive a django site on heroku
but since my last deploy
whenever i make a request i get Bad Request (400) error
can anyone tell what to do
hey guys, I have webapp startup idea where I'm 30% done.. I would love to collab with other people here, dm me if interested...
@ruby summit show the heroku logs and the devtool console if there are errors
The logs donβt show any out put when I make an request to the app
@ruby summit then show those logs
Hi I am using kivy to design an app, I want to connect my android app to my firebase but don't want to expose the credentials inside it. I believe to design an API for the same will be the best practice. It might require to send a HTTP req. Need some help as I am unable to understand further process.
Not using a development server.
If you want to use Waitress as production server: https://flask.palletsprojects.com/en/1.1.x/tutorial/deploy/#run-with-a-production-server
Other options: https://flask.palletsprojects.com/en/1.1.x/deploying/wsgi-standalone/
Hi All,
For any FastAPI devs out there, Just completed a major upgrade to https://github.com/codemation/easyauth - now complete with an Admin GUI, client cookie management, automatic login redirects & default error pages. - Try it out, let me know if you have issues, eager to here what you think.
:wasowiski:
Depending on where you are running the kivi app on, you can store the credentials as an environment variable
to send an automated email through code we need to do some changes to our google account's settings.
is there a way to send mails without changing any settings...?
this is where it's stuck
ig u can
but then ur account would be at risk
I already know that
umm
ya so ?
umm
tbh idk but i dont think so
π
confirmed we can't do it...
a personal account is not meant to do that...
π
guys, i get this error in heroku
the dyno status is 400
what to do ?
do u guys prefer Server side rendering or client side
ikr
maybe try explict allowed hosts
put in herokus domain instead of *
i rarely get issues with django and heroku
umm
ok but idk how this causes an error
since my last update only this has been happening
and ive not even touched allowed_hosts
is there any request limit for a heroku web app ?
even ive never had such an error
π
not that i know of. most of my projects on heroku work seamlessly with django
more issues with frameworks like flask
even me
ive 4
this 5th one is becoming an issue idk y
Can u guys giv me some opinion on how should I improve my website?
what is ur website
like depends on how it is now
Like portfolio
hmm
never done that so idk π
u wanna improve design?
It's OK. I also need some perspective from other ppl
ill do that
but idk how that causes an issue
it means the same thing
'*' and '.herokuapp.com'
yeah true, but maybe being explicit will fix it? i usually just leave it as "*"
idk
ill try and let u know if it solved the error
ah okay
looks neat, you can make it a bit more cleaned up
for example the portfolio page could use some padding
the projects you are showing off are too large
BTW I also made some slight changes. I'm pushing the latest
hey guys can anyone here help me with something in selenium?
css grids is awesome for grid layouts and etc
what is it
Ok so bascially i am trying select a dropdown
but whatever i try it cant seem to find it
I have tried by class name, xpath, css selector
are u using a headless browser?
what do u mean by that?
yes
ah okay so its not headless
i can get it to open the page
umm it might be too fast, maybe set a delay? the page could be loading in the drop down asyncronously
umm let me give it a try
i think selenium has a wait method
hmm
idk this is confusing me XD
found this on a stackoverflow question
s1 = Select(browser.find_element_by_id('highlightunits'))
s1.select_by_visible_text('Inches')
most probably wont work
if u cant access the dropdown by class
But theres no id
yeah
and i tried by class unless i did that wrong
can u select other elements by class name?
element = driver.find_element_by_class_name("js-pg-changemange-search-type")
This is correct right?
yea
p?
Anyone here switched from Flask to Django? How did you find it? I've built about 4 massive projects in Flask that are successful today. I'm wondering what benefits Django has over Flask.
paragraph
how would i do that
find any other element on the page with different class name
i think most of its content is being loaded in later by javascript, so it cant find it
use xpath @thick dock
but yeah, i usually have more success with xpath than class name
i have tried xpath
element = driver.find_element_by_xpath("//input[@data-translate-key='sidebar.select_timetable_type']")
element = driver.find_element_by_xpath("//select[@class='js-pg-changemange-search-type']/option[text()='Module']")
whats the website so I can check it out for you
there has been a lot of message, what are you trying to get
oh yeah
this is a async load
most of the content is loaded in later with javascript
oh
^
try time.sleep instead of selenium wait
from time import sleep
sleep(20)
but 20 is maybe too long, 5 should be enough i think
π³
glad you got it working π
you should be able to, yeah
how do i send a left click?
.click on the element
one of my first automations with selenium, i just used pyautogui to do the mouse movements for me
oo
kinda inefficient but it worked 
got it all working thanks for the help
no problem
That doesnt work
Try searching about Flask logging options, maybe changing logging level works for you
hello everyone, does anyone have info about control panel for routing system with google api?
for pure backend i would suggest learning django bc it has so many features pre build, theyre are so many packages and still kinda easy
anyone know how to use mod_rewrite so like /test/a/b/c would goto /test/index.php/a/b/c
Hey there! I've been onto GUIs for quite a few years now, and wish to start making web pages, and responsive websites. What library would you suggest me to begin with? Also, im quite keen on getting started with Web UI (Canvases,Text Boxes,etc). What would you guys suggest me for both?
there's no "pure backend" tbh. especially with django and flask since they both involve templating which is kinda frontend (unless you only learn the rest frameworks that compliment them).
i'd recommend learning both of them and seeing which one suits you better. flask has an easier learning curve, but django is more powerful since it has a philosophy "batteries included".
also just my opinion, if youre considering learning flask, you should look into FastAPI as well
hi, can any one help me with a django project?
i need to create a DB for users
ill try my best
thank you
@dusky rock I'm glad you mentioned FastAPI, it sounds interesting, impressive and of course, fast.
.navbar {
position: relative;
float: right;
width: 50%;
height: 50%;
text-align: right;
padding-right : 150px;
}
.navbar-item {
display: inline;
list-style-type: none;
line-height: 500%;
padding: 10px;
}
.navbar-link {
text-decoration: none;
font-size: 36px;
color: cornsilk;
}
.navbar-link :hover {
text-decoration: none;
font-size: 100px;
color: rgb(17, 126, 80);
}
why is my navbar link not changing colour?
fixed it
turns out css is space-sensitive
I can help. If you describe your schema, I can create a starter project with the orm models code as well as crud APIs of your choice (rest/graphql). 100% tests too. π
No strings attached, you get the code in 15 minutes
So with flask the session data is encrypted in a unbreakable way right?
A tutorial sets session['logged_in'] = True and then checks that later
theirs no way for someone to just set a cookie 'logged_in' = True right?
I'm going to include an auth token in the session variables which will be checked at high security end points anyway.
Also I am trying to follow the accepted answer on this https://stackoverflow.com/questions/35540885/display-the-contents-of-a-log-file-as-it-is-updated
@app.route('/logstream')
def logstream():
def generate():
if not session['logged_in']:
return "unauthorized"
with open(f'{session["id"]}.log', 'w+') as f:
while True:
yield f.read()
sleep(1)
return app.response_class(generate(), mimetype='text/plain')
however I need variable file names
and realized that the way it is called it does not have a session
Any solution?
alternatively I can just capture output of the running process directly but it would need to always do this even when the page is not open.
Hi, I'm not sure if this is just my web browser being stupid, or me being stupid (most likely the latter), but when I make changes to the css and reload the web page, there are no changes. Usually, I would have to delete the site cache and site settings for the css to load again, and debug mode is on, so I'm not sure what's causing this problem.
are you certain the css is being loaded?
href="{{ url_for('static',filename='styles/bootstrap.min.css') }}"
thats the way I ended up getting it to load
Yep it's definitely loaded
<link rel="stylesheet" href="{{ url_for('static', filename='css/main.css') }}">
nvm
same
so what do you want to happen?
for the browser not to cache?
Well I mean I would expect the page to reload with my changes instantly
Yeah I think that's happening
you're developing on localhost?
Yeah I want to disable that
use your browser
right click -> inspect
first, make sure the up-to-date CSS rules are not being loaded
you can also see the requests being made
and you will be able to tell
if the stylesheets are loaded from cache or not
Ok
!d discord.on_command
discord.on_command(ctx)```
An event that is called when a command is found and is about to be invoked.
This event is called regardless of whether the command itself succeeds via error or completes.
sorry wrong channel
Can anyone tell me how to add authentication to flask post request
There is a website who send post request. So I wass trying to make a webhook kinda thing.
I can successfully get the post request data
but there is a part of authorization in the website which allows to verify the post request is from them
How Can I set the authorization for flask
Can someone tell me how to do oauth2 in django
there is a pretty popular 3rd-party package called "django-all-auth" with default login(email,username,password) and Social Login(facebook,google,twitter)
I want one for discord@native tide
@lapis inlet there is also discord auth
I use 'Incognito mode' or 'Private mode' to avoid issues with the cache and stylesheets. Another technique is to do a hard refresh on the page by pressing ctrl+shift+r or ctrl+f5 (for Ubuntu or Windows, not sure about Mac)
Hi, have a Django question. Basically in one of my views I'm generating a word cloud (https://github.com/amueller/word_cloud). After generating it, im saving it to the static directory as a .png and only then returning the render with a template that uses the static load for the img src. It works fine but im wondering is there a problem with parallelism? Like would it be possible for the view to return the render prematurely (before saving the .png) and then the images wont show up on the page because they havent finished saving yet? Or should i not be worried about it? Also wondering if this is a sub-optimal solution. Thank you
Hello. I'm using FastAPI with Uvicorn and serve it to internet via ngrok . The problem is that the requests are broken with 504 Timeout error after 5 minutes but I can't figure it out which of these tools cause it. Any ideas?
hello guys how to sign XML payload with private key and certificate ???
for mac its command + shift + F5 or command + shift + r
quick question: can I use flask to act as a webserver for my chrome extension? Like send data between the Javascript client and Flask server?
i m getting this error ```django-admin : The term 'django-admin' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the
spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
- django-admin startproject pwhTutorials
-
+ CategoryInfo : ObjectNotFound: (django-admin:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException``` while installing `django-admin startproject pwhTutorials` anyone help plz
Hey guys, I've working with React for about 6 months on a strictly JS project but want to get back to using python. Are Django and Flask still looking like the best options? Are there new tools emerging to consider aside from the REST-django-react setup?
i dont know flask but im also currently implementing react into an django project and it think drf is still the best and easiest to implement option
@toxic matrix u did install django right? if you dont know check it by typing that
pip freeze > requirements.txt is the usual name but u can name it whatever you want
into your commandline and it doesnt matter if you are in a virtual env or not
django is one of the most popular outhere and you can use django-rest-framework
i did
Yea I really love Django. Is there anything new that's worth looking at as it relates to Django or upcoming python frameworks?
try the command and just check it. i had that a while ago too even tho i installed django globally and in my virtual env
i dont know what you looking for but yeah you can almost do anything using django
i did its not doing anything
it didi nothing bc it should have created a file with all pip install packages.
so how to fix
are you in a virtual env or not? bc if just delete it create a new one and install all dependencies again
i m on vsc
if you don't hae a virtual environment
you can use the command py -m venv env-name
at least on windows
then you can use pip easily
vsc doesnt always have the permission for some commands just try it in the normal command line
also true
how its my first project with py
just open cmd and cd into your project and then try django-admin startproject name again
py : The term 'py' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name,
or if a path was included, verify that the path is correct and try again.
At line:1 char:1
- py -m venv env-name
- ~~
- CategoryInfo : ObjectNotFound: (py:String) [], CommandNotFoundException
- FullyQualifiedErrorId : CommandNotFoundException
i did thirce
u got pyhton installed and in your windows path?
yes
i installed python 9 times
because everyone said python was not installed
ok but also added it to the windows path thats essential
can i use this on repl
theres an option in the installer to add it to the path and for the keyword "py" if you dont check those you have to use python and add it to the windows path manually
can i use it on repl??
i dont use repl but probably
on repl i got stuck on this python message.py runserver python: can't open file 'message.py': [Errno 2] No such file or directory
its python manage.py runserver not message.py
python: can't open file 'manage.py': [Errno 2] No such file or directory```
i got this error on repl
then django isnt supported on repl bc u need atleast that file after you have created your django project
but the file is there
<form action="/action_page.php">
<label for="cars">Choose a car:</label>
<select name="cars" id="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<br><br>
<input type="submit" value="Submit">
</form>
``` how would i get selected value. For example if user will select "volvo", i can get it and my `generate_graph` function will generate datas with choosen value?
make a ls or dir to see in which director you are and what files you can call then
uh??? i did not got that
ls worked for me
i did not got what do u mean
mby i said it not understandable. go into the shell on repl and type ls then you see all files in the current directory
thats how i mean it
Django is just the project title
main.py poetry.lock pwhTutorials pyproject.toml got this in response
@native tide ???
yeah youre a directory above you need to cd into it. so type
cd pwhTutorials
in your case
ok done
with php or in what web language?
@native tide ~/web$ cd pwhTutorials ~/web/pwhTutorials$
ok now run python manage.py runserver
yeah thats what you want. you need to be in the django-project folder
CommandError: '/home/runner/web/pwhTutorials' already exists
~/web$ django-admin startproject pwhTutorials```
dont run startproject again rather start the server
uh
that
ok lemme try
html;
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
April 16, 2021 - 13:29:51
Django version 3.2, using settings 'pwhTutorials.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.```
you know basic vanilla javascript? bc you can get the value you want with javascript and then go on
and now run python manage.py migrate to migrate
what does this command means
you migrate basic django settings, configurations. you just need to do it
aoh okok its being installed or migrate
migrated and another useful command is python manage.py makemigrations
that probably is bc of repl. why dont you make inot in repl
it does not work on vsc
you mean vscode? it works in vscode
yes vscode for me it gives errors
should i add you, and you stream it and i just guide you through i think it would be easier then writing here and sending screenshots
hmmmm, my pc will crash
i can give u repl link
ok
dmed
ok but how does that solve your vscode error? bc i dont think it will work with repl
idk i want it to work on repl
ok even tho i dont understand why
:/
the code isnt wrong its bc of repl and i dont use it with repl and dont know if it can work with repl sry
lemme download the code as zip file froom repl and then use it on vsc
ok
and? is it working?
Hey, i need to get selected and submitted values that user selected in html <select> tag
idk my pc is crashing alot i m re-booting major files it might take time π¦
Only if you ask a question
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return "Hello! This is the main page. <h1>HELLO<hi>"
@app.route("/<name>")
def user(name):
return f"Hello {name}!"
if __name__ == "__main__":
app.run(port=8080)
``` Im trying out a basic flask webpage, but whenever i try to open it i get this error
at first i had it at default port, but it still didnt work. then i changed to 4996, still didnt work. adn finally i tried 8080. still no luck
Show us the url in your browser please
If you set the flask app to port 5000 and go there you see nothing?
nope
Remember to restart the app
wdym,
Kill it and rerun the flask app
im on replit
What
Why
How do you expect to reach that machine's localhost if its on a different machine
its, complicated. my device doesnt exactly support vsc or
You dont need vsc to make a flask app
localhost is machine specific, you cant access some other pc's localhost
I suggest you get off replit and try it offline
app.run(port=8080) but the url is 127.0.0.1:5000 (localhost, port 5000)
What command are you using to run the app?
python app.py or do you use flask-manager (python run.py runserver)?
How to get what user selected and submitted in html <select> tag?
i think you gotta add value or name to <select> tag
not remember exactly
and name or value attr to its options. play with it
dont remember exactly but i think you use them in different situations
i dont use flask anymore
but as i remember if you had a piece of code you should use one and if not you should use another BUT not sure
oh my f god why does stretching a background over <body> is so hard.... i just want it to stretch diagonally so it covers up the whole device height but i just get this
i tried everything
add a name tag to the options in the select and then you can get the value in the views.py if youre using Django. In Flask could it be the same but never rlly used it so Idk
Hello there, i'm with some problem with inheritance.
class Person:
CPF unique_field
class BoardMember(Person):
meta proxy=true
class student(Person):
some_field
class Instructor(Student): "cuz in the future a student can be a instructor"
another_field
a member exists with a CPF(unique_field), when i try to create a student with the same CPF, python show me an error. How can i create a student with the same CPF, just getting the person by a filter in the form?
I'm using flask & wtforms to create a recipe site, mostly using Miguel Ginberg's flask mega-tutorial as a base to work from.
I'm working on a page to edit existing recipes, which is very similar to a page to edit existing user profiles. The user edit_profile form works fine, but the edit_recipe one does not.
When I open the edit_recipe page (/recipes/Cereal/edit_recipe for example) I get a stack trace with this error: File "/home/wurzle/projects/recipeasy/app/routes.py", line 112, in edit_recipe
form.name.data = recipe.name
AttributeError: 'tuple' object has no attribute 'data'
Can anyone help me understand why in this context it is treating the form fields as tuples?
Form class:
class EditRecipeForm(FlaskForm):
name = StringField('Recipe Name', validators=[DataRequired()]),
submit = SubmitField('Add Recipe')
def __init__(self, recipename, *args, **kwargs):
super().__init__(*args, **kwargs)
self.original_name = recipename
def validate_name(self, name):
if name.data != self.original_name:
check_existing_recipe = Recipe.query.filter_by(name=self.name.data).first()
if check_existing_recipe is not None:
raise ValidationError(f'A recipe named {{ form.name.data }} already exists.')
Edit recipe route:
@app.route('/recipes/<recipename>/edit_recipe', methods=['GET', 'POST'])
@login_required
def edit_recipe(recipename):
recipe = Recipe.query.filter_by(name=recipename).first_or_404()
form = EditRecipeForm(recipename)
if form.validate_on_submit():
recipe.name = form.name.data
db.session.commit()
flash(f'{{ recipe.name }} updated.')
elif request.method == 'GET':
form.name.data = recipe.name
return render_template('edit_recipe.html', title=f'Edit {{ recipe.name }}', recipe=recipe, form=form)
A snippet of the template:
<form action="" method="post" novalidate>
{{ form.hidden_tag() }}
<p>
{{ form.name.label }}<br>
{{ form.name(size=120) }}<br>
{% for error in form.name.errors %}
<span style="color: red;">[{{ error }}]</span>
{% endfor %}
</p>
<p>{{ form.submit() }}</p>
</p>
</form>
Error form.name.data = recipe.name
So form.name is a tuple, I haven't use WTForms so take this with a grain of salt, but since the form isn't populated it may have no data attribute. I'd print form.name and type(form.name) to see its structure.
If you want to show a default value for the recipe name, take it as a parameter in __init__ of your form and give your field a default attribute to that parameter.
CPF is a unique field, you can't have duplicates and it can't be null. What are you trying to achieve?
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
have you tried:
background-size: contain / cover
You might want to use cover, it will mean the image will take all of the parent's width (even if it requires to be cut). Contain will always contain the image in the parent, but can allow for blank spaces because its aspect ratio is kept.
@opaque rivet Thanks for the tip. I'm actually trying to prepopulate the form with existing values (dynamic defaults?). I am copying that behavior from my user class, which has the same pattern of setting form.field.data to values when it is a get request. The biggest difference I can spot between the two is that the user class uses flask-login's current_user proxy, vs looking up the recipe in my db for the recipe page.
>>> form.name
(<UnboundField(StringField, ('Recipe Name',), {'validators': [<wtforms.validators.DataRequired object at 0x7f21864eea90>]})>)
>>> type(form.name)
<class 'tuple'>```
well that confirms that when forms are not populated, the fields have no data attributes, and you said that you have another form which populates a field on GET request?
Yes that's right, I can paste code snippets from the working one if that would be useful.
sure, I wouldn't expect that to be the case
class EditProfileForm(FlaskForm):
username = StringField('Username', validators=[DataRequired()])
about_me = TextAreaField('About me', validators=[Length(min=0, max=140)])
submit = SubmitField('Submit')
def __init__(self, original_username, *args, **kwargs):
super().__init__(*args, **kwargs)
self.original_username = original_username
def validate_username(self, username):
if username.data != self.original_username:
user = User.query.filter_by(username=self.username.data).first()
if user is not None:
raise ValidationError('Please choose a different username.')
@app.route('/edit_profile', methods=['GET', 'POST'])
@login_required
def edit_profile():
form = EditProfileForm(current_user.username)
if form.validate_on_submit():
current_user.username = form.username.data
current_user.about_me = form.about_me.data
db.session.commit()
flash('Your changes have been saved.')
elif request.method == 'GET':
form.username.data = current_user.username
form.about_me.data = current_user.about_me
return render_template('edit_profile.html', title='Edit Profile', form=form)
So when you go to /edit_profile, it prepopulates the form with the values for the currently logged in user.
The user part is almost character-for-character copied from https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-vi-profile-page-and-avatars (Profile Editor section)
hi, thats right.
I'm trying to register students(Person),instructors(Student),BoardMember(Person)
The same Person can be a member and a student and in the future a student can be an instructor.
I'm not getting do this. if I register a member with a CPF and try to register a student with this same CPF, doesn't work.
hmm, that's really strange and I'm not seeing anything any differenes. could you also print form.username and its type just to see its structure?
you said it yourself - CPF is a unique field, right? That means it can't be duplicated. If you have student A with CPF 1, you can't make another student with the same CPF of 1. You should make the field not unique.
<input id="username" name="username" required type="text" value="">
it clearly knows its a form field there...
at the very least it is reassuring someone else looked at it and wasn't able to spot the issue within 3 seconds (which is how it usually works)
i'm going to dig into the wtforms docs some more... one thing i saw was passing the form an object to pre populate fields... https://wtforms.readthedocs.io/en/2.3.x/forms/
i haven't been able to get that working yet though
it doesn't explain why it is working in the other context though
from what I'm looking up on, unbound fields are seeming to come from the form not being initialized
e.g. if you go into the python console and instantiate your form, and access one of its fields, I believe it shouldn't be unbound.
hmm
what you did here:
was the form instantiated already?
e.g. form = EditRecipeForm("some_recipe")
Instantiating the form in the console/flask shell will require me doing some learning, it is complaining about me doing it outside of a request context.
I tried printing out details of the form immediately after instantiating it:
form = EditRecipeForm(recipename)
print(form)
print(type(form))
print(form.name)
and when I tried to load the page those prints didn't show up in the console, and the stack trace in my browser was the same. I just went to add the same print statements after instantiating the edit_profile form for users, and I got the console print... so whatever I'm doing wrong, it seems to be preventing those lines in the edit recipe form route from being executed
can I pass dictionary into django template?
I have a dictionary smth like this di = {'English': '130.00', 'Italian': '200.00', 'French': '150.00'}
I want to use it in the template
hmm, real strange. I don't know what the solution is. But you could have a workaround.
class EditRecipeForm(FlaskForm):
def __init__(self, recipename=None, *args, **kwargs):
super().__init__(*args, **kwargs)
self.original_name = recipename
name = StringField('Recipe Name', validators=[DataRequired()], default=self.original_name),
submit = SubmitField('Add Recipe')
@deft coyote if you have a recipe already, this will set the default as the recipe name and might avoid that issue.
yep, you can
can u please tell me how
thanks @opaque rivet I'll give that a shot
when I use smth like dict['item'] it cant parse
def your_view(request):
d1 = {...} # your dict
context = {
"d1": d1
}
return render(request, 'your_html_file.html', context)
In your view you can access context through
{{d1['English']}}
(as an example).
I dont use specific name
I want to iterate it and print
for key in di:
print(di[key])
something like this
in your template:
{% for key in d1 %}
{{ d1[key] }}
{% endfor %}
this doesnt parse I've already tried
could you try:
{% for value in d1.values %}
{{ value }}
{% endfor %}
I would like to print out the number of votes that each choice got. I have this code in a template:
{% for choice in choices %}
{{choice.choice}} - {{votes[choice.id]}} <br />
{% endfor...
this is the solution
key, value in dict.items
thanx
worked btw
oh god
i feel like such a moron
welp... sorry for wasting your time @opaque rivet ... the problem was a trailing comma... first 3 lines I pasted: ```py
class EditRecipeForm(FlaskForm):
name = StringField('Recipe Name', validators=[DataRequired()]),
submit = SubmitField('Add Recipe')
the extra comma on the end of the second line : (
Yes. But student is a subclass from Person. If i try to register student and the person exists, the form try to insert another person and set it FK to this student.
ah that feeling that can't be replicated.... the feeling of spending 5 hours troubleshooting an extra comma lol
haha, that's tough π
yeah - because when you inherit a model you implicitly have a OneToOne field between models. Saving a subclass will ultimately save the parent class.
just pass a unique id to each.
How to do this? If i do not want duplicated persons.
hi so, i made this flask app: https://paste.gg/p/anonymous/d2539795d520415d8b59f69e7ecae258
and the post method on line 152, is failing due to CSRF Verification, but i dont even have CSRF enabled, what am i doing wrong?
Do you guys use REST or GraphQL?
I started using Django Rest Framework, it is cool
@pale crescent have you tried switching the validator for that form method from DataRequired() to FileRequired()?
I'm reading docs right now, I haven't done file uploads in flask but I've been working with flask-wtf validators all day today
Oh, I'm sorry
np... this is what im reading https://blog.miguelgrinberg.com/post/handling-file-uploads-with-flask
i've been following his tutorial for all the other stuff i'm doing in flask
Oh okay
cool tutorial ;b
it made my beginning in Flask as well
it is heavily outdated though, but that's the bonus of it
instead of copy pasting, you are forced to discovery how it should be really done)
i've been implementing a food recipe site instead of the microblog from the tutorial
it has been more difficult but also probably better for learning to try to do my own thing
Hey @shell heath!
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 someone please write quick 1 line per class css code comments on the css above
I would have done it myself but I have been overwhelmed by the amount of work
@deft coyote, I forgot to put enctype="multipart/form-data" in <form>, that was all, I'm dumb-
Are you asking for someone to annotate 600 lines of CSS for you?
If you have a specific question about something, ask it.
how to download the screenshot of a particular node of a website if i know the class of it
using python.
pls inform me if it's against ToS coz i don't know if it's against it
I need Help on django
NameError : name 'os' is not defined
I put [os.path.join(BASE_DIR, 'templates')]
im making a website with flask and react. the react client will send requests to the flask API to fetch information and display it to the user. i will also make a public API. how do i prevent people from using the API designed for the react client?
@sand glen By adding authorization to it.
wdym by that?
Authentication means requiring the client to login, authorization controls what you have access to.
What are you using for authentication?
hi, I'm running spike tests on django app with jmeter, can anyone tell me if that's how it should look like?
i mean shouldn't resposne time getting lower if there's less users over time?
Are your queries or data increasing in size over time? As well are you testing in debug mode or with gunicorn?
it's a simple page with one line of text on it, only thing increasing is users trying to visit that page
@jade lark
by debug mode you mean if djagno is still in debug mode?
Yes, if Django is in debug mode
Turn it off if you're trying to do accurate testing.
What are you trying to determine?
ipmact of spike on response time
i'm doing comparision between flask and django
it's my first time doing tests
i'm running jmeter in cli
Gotcha. Is this so you can find out what framework to go with?
it's for thesis
Alright. Try running both in a production environment with gunicorn as that will be the most realistic approach.
Django will be slower and have a higher response time due to middleware.
is gunicorn something like docker?
No. gunicorn allows you to setup workers and threads so that your webserver isn't running on a single thread/process.
that's what i thought but i still need to run tests for few scenarios and write something 'bout this
oh, great, i'll do that
but still about my question, does this chart looks normal?
Sounds good. Here's a guide to get your started: https://medium.com/analytics-vidhya/dajngo-with-nginx-gunicorn-aaf8431dc9e0
If you're doing more requests per second overtime absolutely.
The server wouldn't be able to handle requests as quickly and the event loop would be blocked. When that happens the response time will increase because you're waiting for the server (django/flask) to process your request.
ok, i was worried that there are spike when users count drops, but it seems like previous users are still waiting for response, right?
Correct. They would be waiting for a response.
ok, thank you very much π
No problem! Best of luck
hey guys does anyone know why with this code,
i get this error ?
ah thats a little hard to see wait
mysqli_query($query);```
and the error i get = "Fatal error: Uncaught ArgumentCountError: mysqli_query() expects at least 2 arguments, 1 given in C:\xampp\htdocs\Website\signup.php:20 Stack trace: #0 C:\xampp\htdocs\Website\signup.php(20): mysqli_query('insert into use...') #1 {main} thrown in C:\xampp\htdocs\Website\signup.php on line 20"
mysqli_query(query ,[user_username, user_password, user_userid]);```
something like this?
what is the "%s" ?
is that just placeholders?
ohhh and then you give the varaibles below i see, thanks
@main night im given this error?
Parse error: syntax error, unexpected token "=" in C:\xampp\htdocs\Website\signup.php on line 18
oh, sorry, you're writing that in php right?
yes
you need to pass connection to database in mysqli_query
$con=mysqli_connect("localhost","my_user","my_password","my_db");
$query = "insert into user_table (user_username,user_password,user_userid) values ('$user_username','$user_password','$user_userid')";
mysqli_query($con, $query);```
i think that should work
and remember to close the connection with mysqli_close($con);
after passing query
Does CORS policy apply to websockets?
Writing unit tests.
Hey guys! I am trying to automatically login to my Microsoft account by selenium - python
How would i go about writing a function that creates a random number of a specific length like:
function random_num($length)
There is many different ways. What are you using it for?
This is my code
There is many different ways. What are you using it for?
But it gives me this error
creation of a user id
i tried a way but it just returned a random 1 digit number so i dont think i know how to correctly append a number onto a variable if that makes sense
If you're using a db with a primary key it will auto increment
else if you want it to be a sting use a uuid/guid
with the secrets module
selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document (Session info: chrome=89.0.4389.128)
Why it gives me this error?
How can I solve it?
I wouldn't try and do this if you don't have much selenium experience. Microsoft has measures in place against it. They do have an API though so what you're trying to do might be supported that way
This isn't related to web development so I would look at a help channel or a different section
in built unittest
launches with python manage.py test
you write there... suprise, unit tests to check that your project works correctly)
this can be read for basics how to do it
or at least there I learned how to do it for Django
it is a big topic though
recommending to read some book about it
I wish to read Test Driven Development with python from O'reilly as one of next ones
$u_password = $_POST['user_password']; ```
so i copied some code off of a tutorial and im slightly confused, what does this part do ?
does it take variables from my database and set them as $u_username and pass, or does it take the user data that was entered during login and makes them $u_username and pass ?
without more context it is just guessing
but more likely the last choice
flask_login
ok ill post the whole login php section, beware its a mess
<?php
session_start();
include("connection.php");
include("functions.php");
if($_SERVER['REQUEST_METHOD'] == "POST")
{
$u_username = $_POST['user_username'];
$u_password = $_POST['user_password'];
if(!empty($u_username) && !empty($u_password) && !is_numeric($u_username))
{
//if the input fields arent empty + username isnt a number
//read from database
$query = "select * from users where user_username = '$u_username' limit 1";
$result = mysqli_query($con, $query);
if($result){
if($result && mysqli_num_rows($result) > 0)
{
$user_data = mysqli_fetch_assoc($result);
if($user_data['u_password'] === $u_password){
$_SESSION['user_userid'] = $user_data['user_id'];
header("Location: Websiteattempt (1).php");
die;
}
}
}
echo "Wrong username or password!";
}else
{
echo "Please enter some valid information";
}
}
?>```
basically no matter what i enter, correct or incorrect, it doesent work if anyone could help that would be fantastic
it just keeps returning "Please enter some valid information"
Ive finished the registration part and its all working perfectly but stuck on the Login
oof PHP
as I said, pretty much data from form form
although more precisely would be said...
...well... if we translate it to python language...
weird hybrid language
$user_username = $_POST['user_username'];
$u_password = $_POST['user_password'];
python:
def handling(request):
user_username = request.get['user_username']
u_password = request.get['user_password']
or may it was query parameter, not sure
probably query parameter
so how would i make it check the data that was entered against the username and password from the database, ive been at this really long just want to get it done very frustrated with it
last time I used php, happened 3 years ago. And I did not reach databases
ahhhhh well thanks for trying to help anyways
I guess if it's reaching the first else block, then the is empty check must be failing. Have you tried using isset() instead?
sorry im struggling to see where youre talking about @stone citrus
there are the line numbers if you can tell me where youre reffering to
Sorry, I was referring to the if(!empty($u_username) && !empty($u_password) && !is_numeric($u_username)) check
It already seems to be checking the information against the database
The really bad part is it's literally using plain text passwords though...
ok i see where you mean now, where would i use isset()?
In place of empty()
replace empty with isset
also replace die; with die(); as it's supposed to be calling a function
im pretty sure some of the variables are in the wrong places since i was messing around with them to see if that would fix it and i kind of lost track
Okay, it might be worth just doing var_dump for the variables to see where the logic isn't lining up
these are what the variables are meant to be:
username entered by user into login = u_username
pass entered by user into login = u_password
username in database = user_username
password in database = user_password
im not familiar with this what is this
it takes an array and dumps it or an object
and how do i do that
var_dump($user_data);
where should i put that
Below $user_data
I'm not sure if it's making it to that block
nothing happened what is it meant to do
Yeah it's not passing the conditional check
put it above if($result)
So var_dump($result)
Because at the moment your code isn't making it past the if($result) check
Assuming the form data is provided correctly
Which probably means there isn't any data being fetched from the db
nothing happened again
then the form data isnt valid
<form method="POST">
<label for="fname">Username:</label>
<input type="text"
name="u_username"
maxlength="16"
style="font-size: 25px"
>
<br><br>
<label for="lname">Password:</label>
<input type="password"
name="u_password"
maxlength="16"
style="font-size: 25px">
<br><br>
<input type="submit"
style="height: 30px;
width: 200px;">
</form>
thats the form for login
echo $u_username;
echo $u_password;
die();
njothing
So $u_username = $_POST['user_username']; $u_password = $_POST['u_password']; should be $u_username = $_POST['u_username']; $u_password = $_POST['u_password'];
basically in your form you have the name=""
To clarify,
if($_SERVER['REQUEST_METHOD'] == "POST") { $u_username = $_POST['user_username']; $u_password = $_POST['user_password'];
should become
if($_SERVER['REQUEST_METHOD'] == "POST") { $u_username = $_POST['u_username']; $u_password = $_POST['u_password'];
Those values need to match the keys for $u_username and $u_password
<?php
session_start();
include("connection.php");
include("functions.php");
if($_SERVER['REQUEST_METHOD'] == "POST")
{
$u_username = $_POST['u_username'];
$u_password = $_POST['u_password'];
if(!empty($u_username) && !isset($u_password) && !is_numeric($u_username))
{
//if the input fields arent empty + username isnt a number
//read from database
$query = "select * from users where user_username = '$u_username' limit 1";
$result = mysqli_query($con, $query);
echo $u_username;
echo $u_password;
die();
if($result){
if($result && mysqli_num_rows($result) > 0)
{
$user_data = mysqli_fetch_assoc($result);
if($user_data['u_password'] === $u_password){
$_SESSION['user_userid'] = $user_data['user_id'];
header("Location: Websiteattempt (1).php");
die();
}
}
}
echo "Wrong username or password!";
}else
{
echo "Please enter some valid information";
}
}
?>
i think i already changed it to that
I think we should just start from the top, since it's getting confusing where exactly your code is being terminated at
<form method="POST">
<label for="fname">Username:</label>
<input type="text"
name="u_username"
maxlength="16"
style="font-size: 25px"
>
<br><br>
<label for="lname">Password:</label>
<input type="password"
name="u_password"
maxlength="16"
style="font-size: 25px">
<br><br>
<input type="submit"
style="height: 30px;
width: 200px;">
</form>
<p style="margin-left: 30px">Please note: Username and password maximum characters is 16</p>
<a href="signup.php">Not a member? Register here</a>
</div>
so i change the name="u_username" to "$u_username" ?
$u_username = $_POST['u_username'];
$u_password = $_POST['u_password'];
echo $u_username;
echo $u_password;
die();
Try this and make sure it's working first. This will make sure the provided form values are there.
Ok, so now under that do a var_dump(!empty($u_username) && !isset($u_password) && !is_numeric($u_username))
That'll show you the value in the if statement
under the
$u_username = $_POST['u_username'];
$u_password = $_POST['u_password'];
``` ?
So
if($_SERVER['REQUEST_METHOD'] == "POST") { $u_username = $_POST['u_username']; $u_password = $_POST['u_password']; var_dump(!empty($u_username) && !isset($u_password) && !is_numeric($u_username))
Just so you know tvanom if you use three tildas top and bottom it does the code block
`
Ah cheers. I haven't used discord for code blocks that much!
Okay, so that means that one or more of the three conditions in the !empty($u_username) && !isset($u_password) && !is_numeric($u_username) is false
should i remove the isnumeric part
technically dont need it t here might be messing something up
If you do ```
var_dump(!empty($u_username));
var_dump(!isset($u_password));
var_dump(!is_numeric($u_username));
above the if statement
Then we can see which one is failing
Yup
ok why is it failing?
So when you printed out password, you got kacper13542 right?
yes
Oh, you need to replace !isset($u_password) with isset($u_password)
I.e. remove the !
wait i think we made progress maybe ?
It should make it into the if statement now?
yep i got this back
bool(true) bool(false) bool(true) kacperptak01kacper13542
which means it made it past the if ```
<?php
session_start();
include("connection.php");
include("functions.php");
if($_SERVER['REQUEST_METHOD'] == "POST")
{
$u_username = $_POST['u_username'];
$u_password = $_POST['u_password'];
var_dump(!empty($u_username));
var_dump(!isset($u_password));
var_dump(!is_numeric($u_username));
if(!empty($u_username) && isset($u_password) && !is_numeric($u_username))
{
//if the input fields arent empty + username isnt a number
//read from database
$query = "select * from users where user_username = '$u_username' limit 1";
$result = mysqli_query($con, $query);
echo $u_username;
echo $u_password;
die();
if($result){
as it echod the user and pass
Remove:
echo $u_username;
echo $u_password;
die();
Replace with:
var_dump($results);
Ok great. Now before removing the die(); just do a var_dump($result)
Ehh
Just incase there's a problem with the query results
which die(); ?
if(!empty($u_username) && isset($u_password) && !is_numeric($u_username))
{
//if the input fields arent empty + username isnt a number
//read from database
$query = "select * from users where user_username = '$u_username' limit 1";
$result = mysqli_query($con, $query);
echo $u_username;
echo $u_password;
die();
if($result){
if($result && mysqli_num_rows($result) > 0)
{
$user_data = mysqli_fetch_assoc($result);
if($user_data['u_password'] === $u_password){
$_SESSION['user_userid'] = $user_data['user_id'];
header("Location: Websiteattempt (1).php");
die();
}
}
}
number 1 or 2
i put it before the first one and got this :
bool(true) bool(false) bool(true) kacperptak01kacper13542bool(false)
so it came out with bool(false)
The first one. So ``` if(!empty($u_username) && isset($u_password) && !is_numeric($u_username))
{
//if the input fields arent empty + username isnt a number
//read from database
$query = "select * from users where user_username = '$u_username' limit 1";
$result = mysqli_query($con, $query);
var_dump($result);
die();```
yes i did that and it came out with false
Right. Just temporarily change your query to select * from users so we can check if it's a connection issue or a filtering issue. So
{
//if the input fields arent empty + username isnt a number
//read from database
$query = "select * from users;";
$result = mysqli_query($con, $query);
var_dump($result);
die();```
Hmm, it should only be printing one value
Can you paste your entire code block again please?
whole php or everything ?
Just the current version of ```<?php
session_start();
include("connection.php");
include("functions.php");
if($_SERVER['REQUEST_METHOD'] == "POST")
{
$u_username = $_POST['u_username'];
$u_password = $_POST['u_password'];
if(!empty($u_username) && !isset($u_password) && !is_numeric($u_username))
{
//if the input fields arent empty + username isnt a number
//read from database
$query = "select * from users where user_username = '$u_username' limit 1";
$result = mysqli_query($con, $query);
echo $u_username;
echo $u_password;
die();
if($result){
if($result && mysqli_num_rows($result) > 0)
{
$user_data = mysqli_fetch_assoc($result);
if($user_data['u_password'] === $u_password){
$_SESSION['user_userid'] = $user_data['user_id'];
header("Location: Websiteattempt (1).php");
die();
}
}
}
echo "Wrong username or password!";
}else
{
echo "Please enter some valid information";
}
}
?>```
<?php
session_start();
include("connection.php");
include("functions.php");
if($_SERVER['REQUEST_METHOD'] == "POST")
{
$u_username = $_POST['u_username'];
$u_password = $_POST['u_password'];
if(!empty($u_username) && isset($u_password) && !is_numeric($u_username))
{
//if the input fields arent empty + username isnt a number
//read from database
$query = "select * from users;";
$result = mysqli_query($con, $query);
var_dump($result);
die();
if($result){
if($result && mysqli_num_rows($result) > 0)
{
$user_data = mysqli_fetch_assoc($result);
if($user_data['u_password'] === $u_password){
$_SESSION['user_userid'] = $user_data['user_id'];
header("Location: Websiteattempt (1).php");
die();
}
}
}
echo "Wrong username or password!";
}else
{
echo "Please enter some valid information";
}
}
?>
hey, im new to html & css and im creating a navbar, that's my current HTML:
<body>
<div class="navbar">
<div class="navbar-logo">
<a href="#">Falk<span>Cool</span></a>
</div>
<div class="navbar-raster">
<a href="#">Features</a>
<a href="#">Buy VIP</a>
<a href="#">Weiteres</a>
</div>
</div>
</body>
</html>
and that's my current (S)CSS:
@import url('https://fonts.googleapis.com/css2?family=Poppins&display=swap');
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;600&display=swap');
.navbar {
height: 3.5em;
position: relative;
background-color: rgb(0, 99, 145);
a {
font-weight: bold;
font-size: 1.1em;
}
.navbar-logo {
padding-left: 2em;
a {
font-size: 1.7em;
}
span {
color: rgb(255, 255, 255);
}
}
a {
font-family: poppins;
color: black;
text-decoration: none;
}
}
I don't know how i can move the "navbar-raster" to the right and center them vertically, i appreciate every answer!
Such as a sidebar? Or a navbar with some elements on the left and some on the right
i have a logo on the left and clickable stuff on the right, but on one line
@import url('https://fonts.googleapis.com/css2?family=Poppins&display=swap');
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;600&display=swap');
.navbar {
height: 3.5em;
position: relative;
width: 100%;
display: flex;
align-items: center;
justify-content: space-between;
background-color: rgb(0, 99, 145);
a {
font-weight: bold;
font-size: 1.1em;
}
.navbar-logo {
padding-left: 2em;
a {
font-size: 1.7em;
}
span {
color: rgb(255, 255, 255);
}
}
a {
font-family: poppins;
color: black;
text-decoration: none;
}
}
@stone citrus my message is up there above this all btw incase you missed it
I highly recommend learning flexbox as it is super helpful and useful: https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Flexbox
Game to learn it from: https://flexboxzombies.com/p/flexbox-zombies
so the position: relative says that everything child element is relative to the parent element? and what does the width 100% do? 100% to what? what does display flex mean? What does justify-content do?
ooh a zombie css game
ill google everything
nice link
It's weird that it's printing 4 values. Do you have 4 user records in your users table?
position: relative; just means all child elements will be relative to the parent element. This is useful if you used position: absolute; on child elements. You can remove this if you'd like as you're probably not using it.
Ah okay. I think that means that you haven't connected to the database properly
I'm assuming you're doing that in connection.php ?
align-items: center; means to align items vertically. justify-content: space-between; means to space the content on opposite sides of the parent element. In this case it would be the two child div elements.
yes these are the contents of connection.php
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "website_db";
if(!$con = mysqli_connect($dbhost,$dbuser,$dbpass,$dbname))
{
die("faiied to connect!");
}
Thanks. Give it a go it's free and actually really helpful.
my database name is website_db and the table for login is called user_table
okay thanks for the help
Oh, so the table that stores the usernames and passwords is called user_table ?
yes
Okay, you probably need to change $query = "select * from users;"; to $query = "SELECT * FROM user_table;";
uhh
object(mysqli_result)#2 (5) { ["current_field"]=> int(0) ["field_count"]=> int(3) ["lengths"]=> NULL ["num_rows"]=> int(3) ["type"]=> int(0) }
is that a good thing ?
@stone citrus
so what does this mean
I think we were selecting data from a non-existent table before, so no results were being returned
i see
Okay, now you can replace the query with the conditions you had before, so $query = "SELECT * FROM user_table WHERE user_username = '$u_username' limit 1;";
should i remove tthe vardump now ?
You can remove the var_dump and die(), yes
Just know ptak this script should not be used in production.
So that block should look like this
$query = "SELECT * FROM user_table WHERE user_username = '$u_username' limit 1;";
$result = mysqli_query($con, $query);
if($result){
It's prone to SQL injection and a bunch more.
Yeah, you should look into mysqli_real_escape_string()
its just for a basic assignment there isnt any marks for security and stuff
I was going to say PDO now
now im getting this :
Warning: Undefined array key "u_password" in C:\xampp\htdocs\Website\login.php on line 29
Wrong username or password!
Right, so if you make those above changes, what's the output looking like?
which one the first or second
Yeah, so if($user_data['user_password'] === $u_password) {
Ok, so that probably means that it ran as expected?
It probably worked then
should it not redirect me to websiteattempt (1).PHP?
below the header(); add echo "Ran successfully";
You can remove the last die();
Or that too
Probably best to do what magic said
same again, and it didnt return anything
<?php
session_start();
include("connection.php");
include("functions.php");
if($_SERVER['REQUEST_METHOD'] == "POST")
{
$u_username = $_POST['u_username'];
$u_password = $_POST['u_password'];
if(!empty($u_username) && isset($u_password) && !is_numeric($u_username))
{
//if the input fields arent empty + username isnt a number
//read from database
$query = "SELECT * FROM user_table WHERE user_username = '$u_username' limit 1;";
$result = mysqli_query($con, $query);
if($result){
if($result && mysqli_num_rows($result) > 0)
{
$user_data = mysqli_fetch_assoc($result);
if($user_data['user_password'] === $u_password){
$_SESSION['user_userid'] = $user_data['user_id'];
header("Location: Websiteattempt (1).php");
echo "Ran successfully";
}
}
}
echo "Wrong username or password!";
}else
{
echo "Please enter some valid information";
}
}
?>
still nothing
remove the header too
i have a feeling i messed up on the session part
hahaha
a bit of a mixed message
Warning: Undefined array key "user_id" in C:\xampp\htdocs\Website\login.php on line 31
Ran successfullyWrong username or password!
so it worked but whats the user id error
$_SESSION['user_userid'] = $user_data['user_id'];
$user_data[''user_user_id"];
user_userid but yeah did that
Then it worked
okay it works thats great but i need to make sure that it doesent work when i put the wrong stuff in
so try putting invalid info
Open a private browsing window
Now the important thing is do you understand what you had to change to get it to work?
i think i did yes
Yeah, debugging code is definitely a process that you'll get better at over time
I like to do it systematically, so go from top to bottom, checking if your if statements are passing, checking the value of variables etc.
yeah im used to doing it just that this is my first ever html/php project and i missed every single class we had on it in school due to an injury so everything i have it from w3schools or youtube
and ive been sitting here for 6 hours
We all start somewhere. When it comes to web development with PHP, well, your first stop is this series. Designed specifically and exclusively for beginners, here, you'll learn the fundamentals of PHP - all the way down to defining variables and arrays.
If you feel somewhat unprepared for the content at Laracasts, this "PHP for beginners" serie...
its a whole website
I highly recommend laracasts for PHP
that was just the login system i was stuck on
Better practices as well
yeah ill check it out thanks alot magic and tvanom you saved me
its likely ill be back tommorow because ill need to figure out how to do stuff with foreign keys and everything
Happy to help
Hello can I talk with someone with experience in React.js or an experienced HR
I'm struggling in my job search and would appreciate a conversation
ist this little space normal? it's a flex box
nope - go into dev tools and check if there's extra padding / margin which you didn't expect. You can then modify your css to remove it.
i've got some experience with react, i doubt you'll find anyone in hr here. but whats up?
this are the styles: ```css
height: 3.5em;
position: relative;
width: 100%;
display: flex;
-webkit-box-align: center;
align-items: center;
-webkit-box-pack: justify;
justify-content: space-between;
background-color: #24252A;
sure - did you check devtools?
heyo, why does flask's redirect and url_for always send you to localhost instead of the same URL you're already on when using relative paths
i tried setting SERVER_NAME but that just gives me a 404 no matter what
this is the relevant section from my app.py
from flask import Flask, redirect, render_template, request, url_for
app = Flask(__name__)
app.config["SERVER_NAME"] = "https://blahblah.githubpreview.dev/:5000"
@app.route("/", methods=["GET"])
def index():
if "interviewee" not in request.args or request.args["interviewee"] not in interviewees:
return redirect(url_for("select"))
else:
return render_template("index.html")
@app.route("/select")
def select():
return render_template("select.html")
if __name__ == "__main__":
app.run(host="https://blahblah-8x8x-5000.githubpreview.dev/", port=5000)```
anyone in here uploaded images using reactjs and django. Whats wrong with it? pp field means profile picture.
models.py```py
class Account(models.Model):
pp = models.ImageField(upload_to='profile-pictures')
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='account')
serializers.py```py
class AccountSerializer(serializers.ModelSerializer):
class Meta:
model = Account
fields = ['pp']
class UserSerializer(serializers.ModelSerializer):
account = AccountSerializer(read_only=True)
class Meta:
model = User
fields = ['username', 'password', 'account']
views.py```py
@api_view(['GET', 'POST'])
def register(request):
serializer = UserSerializer(data=request.data)
if serializer.is_valid():
username = serializer.data['username']
password = serializer.data['password']
pp = serializer.data['pp']
user = User.objects.create_user(username=username, password=password)
account = Account(pp=pp, user=user)
account.save()
return Response(True)
return Response('not valid')
urls.py```py
urlpatterns = [
path('register/', views.register, name='register'),
]
App.js```js
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
username: '',
password: '',
pp: ''
}
this.register = this.register.bind(this)
}
register(event) {
event.preventDefault()
var form = new FormData()
form.append('username', this.state.username)
form.append('password', this.state.password)
form.append('pp', this.state.pp)
axios.post('http://localhost:8000/register/', form, { headers: { 'content-type': 'multipart/form-data' } }).then(res => {
this.setState({
username: '',
password: ''
})
})
}
render() {
return (
<form onSubmit={this.register}>
<input type="text" name="username" placeholder="Username" value={this.state.username} onChange={e => {this.setState({ username: e.target.value })}} required />
<br />
<input type="password" name="password" placeholder="Password" value={this.state.password} onChange={e => {this.setState({ password: e.target.value })}} required />
<br />
<input type="file" name="pp" onChange={e => {this.setState({ pp: e.target.files[0] })}} />
<br />
<input type="submit" value="Register" />
</form>
)
}
}
print serializer.errors or see error response codes (not 2xx) with axios using the .catch() block. That will tell you exactly what's wrong.
its django rest problem
e.g.:
.catch(res => {console.log(res.response.data})
when i submit the form with image in part serializer.is_valid() seems like it doesnt accept it
okay - so print serializer.errors
i think i got some stupid errors json { "username": [ "This field is required." ], "password": [ "This field is required." ] }
and i checked the data all been there
so what is the structure of request.data?
wait..
the models are seperated
and im trying to get AccountSerializer data from UserSerializer can it be related?
while they are two seperated serializers
username: username
password: passwrod
pp: (binary)
and the source => ```
------WebKitFormBoundaryw5VIe3qAQArAE3K4
Content-Disposition: form-data; name="username"
username
------WebKitFormBoundaryw5VIe3qAQArAE3K4
Content-Disposition: form-data; name="password"
passwrod
------WebKitFormBoundaryw5VIe3qAQArAE3K4
Content-Disposition: form-data; name="pp"; filename="avatar7.png"
Content-Type: image/png
------WebKitFormBoundaryw5VIe3qAQArAE3K4--
Yes you can nest serializers. If it's a one-to-many relationship give it the kwarg many=True
class UserSerializer(serializers.ModelSerializer):
account = AccountSerializer(read_only=True)
class Meta:
model = User
fields = ['username', 'password', 'account']
serializer.data would result in:
{'username': 'x',
'password': 'y',
'account': [{'pp': 'z'}, {...}]
The issue is that the username and password fields aren't detected. but the pp field is?
yes
i think thats bacause i have two different serializers
wait a minute i try a thing
looks like DRF doesn't support nested serializers when it's multipart/formdata
oh ok thanks ill check it
I think this explains the problem exactly
And I think the DRF multipart parser would help. I haven't used it though
@nimble epoch
yes?
what did you change?
i have two serializer
i been using field that didnt even exists in UserSerializer
class AccountSerializer(serializers.ModelSerializer):
class Meta:
model = Account
fields = ['pp']
class UserSerializer(serializers.ModelSerializer):
account = AccountSerializer(read_only=True)
class Meta:
model = User
fields = ['username', 'password', 'account']```
i been getting 'pp' field directly from UserSerializer
so the pp field did not exist in your Account model?
no pp field doesnt exists in User model
but... you're not trying to access the pp field in the User model, you're accessing it from the Account model
yes but in the last example i been trying to set image to pp field from UserSer while UserSer didnt even have that field name
ok thanks @opaque rivet appreciate your time
big pp hours
lol
there is a reason "pfp" is the canonical abbreviation of profile picture, and not "pp"
well, the pp field is coming from the AccountSerializer, but read_only=True. So setting read_only=False should allow you to set that
wow
maybe