#web-development

2 messages Β· Page 148 of 1

limpid python
#

I just made it into a flask app

#
from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def home():
    return render_template("index.html")
#

do I have to use jinja?

native tide
#

you need to write <link rel="stylesheet" href="../css/bootstrap.min.css" /> bc they arent in the same directory

limpid python
#

oh

#

nope

fast steeple
#

is there anyone who is familiar with Django frameworks?!

crude glen
fast steeple
native tide
limpid python
#

ok

native tide
native tide
# limpid python ok

Im not sure tho bc im not that familiar with flask just try asking someone else or try googling it

limpid python
#

ok

fast steeple
native tide
fast steeple
native tide
#

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...

β–Ά Play video

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...

β–Ά Play video
fast steeple
#

yes screen share would be cool @native tide

native tide
#

ok i add you

fast ether
#

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???

native tide
fast ether
#

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

native tide
#

i think i understand your problem but why arent you solving that with javascript. I think it would be simpler

fast ether
#

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?

tough harness
#

Hey guys, ES and Javascript are the same thing right?

native tide
native tide
# fast ether Hmm i don't have much knowledge on javascript

@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

fast ether
#

it's looks like it didn't work

native tide
#

are you sure? I just wrapped it in a <td> tag and it still works

fast ether
#

Yeah won't work i removed the <td> tag it works but i need it to be inside <td>

stray cypress
#

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);
}
native tide
fast ether
#
<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 %}
fast ether
digital portal
#

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

native tide
#

@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

native tide
digital portal
#

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

native tide
#

and what is your question about that assignment?

fast ether
native tide
#

@fast ether just add more css some margin or padding and some border and it should look great

lusty cloud
#
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")

surreal horizon
#

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?

limpid python
#
            <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.
native tide
rapid plinth
#

im trying to build a website with pyhton and have no idea what im doing or where to start lol where do I start?

tribal pewter
#

-learn the basics of html/CSS
-learn Python
-Choose a framework (Django/Flask )

#

start building

foggy bramble
#

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

formal axle
#

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

native tide
#

whats the difference between print and return in functions

native tide
native tide
#

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

uncut spire
#

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 '*'

formal axle
#

this is the file structure

native tide
#

@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 ?

formal axle
#

no lol didnt even know i should do that, ill do that rn and see if it works

native tide
#

that probably fixes it and if you ever use images do the same thing you did with static

formal axle
#

the root is the other thing than the app right?

#

just wanna make sure im doing it at the right place

native tide
formal axle
#

gotcha

#

hmm it says name static is not defined

native tide
formal axle
#

all good

native tide
#

those are the missing imports

from django.conf import settings
from django.conf.urls.static import static
formal axle
#

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

native tide
#

304 means its not modified and uses a cached version.
So clear the cache by pressing "Shift + F5"

formal axle
#

ok one sec

#

do u know what the command would be oin mac because that activated voice over

native tide
#

wait one sec

formal axle
#

ok

native tide
#

u can also press "Shift + R" so "Command + Shift + R" for you i guess

formal axle
#

ok ill try that

#

hmm weird still didnt do anything

#

it just put out "GET / HTTP/1.1" 200 3472

native tide
#

i updated my answer i think thats it

formal axle
#

oh ok ill try that

#

"GET /favicon.ico HTTP/1.1" 404 2584

#

this popped up now lol

native tide
#

do you have a favicon in your app or not?

#

if not it doesnt matter

formal axle
#

well no i dont rlly know what that is

#

is it that img on the tab thing

native tide
#

favicon is basically the icon you see next to the website title in the tab

native tide
formal axle
#

oh ok

#

hmm so why would that make the css not work lmao

native tide
#

it still doesnt work?

formal axle
#

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?

native tide
#

yellow just means your linter shows warnings but thats not rlly important

formal axle
#

ok

#

maybe im just not meant to learn django πŸ˜†

native tide
#

u wanna screenshare and show it? i would add you.

native tide
formal axle
#

yea sure i cant talk tho because my mic is broken

reef oasis
formal axle
#

yea im just joking lol

reef oasis
#

hehe

#

Maybe you just tried to jump some steps

native tide
#

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

reef oasis
formal axle
reef oasis
#

Under Firewall settings

reef oasis
formal axle
#

hmm interesting

#

ok i will

#

@reef oasis thanks

#

oh wait i thought it would give u points

#

wrong server

reef oasis
#

lol no need for that hehe it was a pleasure helping you. Feel free to dm me when you face a problem

formal axle
#

thanks

fast ether
#

is there any good resources to learn flask with python?

#

i can't find something good

meager sand
#

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

whole sierra
#

Can anyone tell me how to assign the exact same value of a text-area to an input form?

reef oasis
# fast ether is there any good resources to learn flask with python?

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 ...

β–Ά Play video
native tide
#

Hey

valid girder
#

How do you guys bootstrap / start a new Django project? Are there any good starter boilerplate projects out there you guys use?

native tide
# valid girder How do you guys bootstrap / start a new Django project? Are there any good start...

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...

β–Ά Play video
native tide
#

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 -

cosmic bramble
#

No

civic kiln
#

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

civic kiln
#

this is the for loop and the model area

cosmic bramble
#

Because you are using a development server

cosmic bramble
civic kiln
#

i wanted help in php, thanks though

ruby summit
#

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

ruby summit
tulip beacon
#

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...

native tide
# ruby summit

@ruby summit show the heroku logs and the devtool console if there are errors

ruby summit
native tide
dapper heath
#

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.

scenic pendant
#

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.

GitHub

Create a centralized Authentication and Authorization token server. Easily secure FastAPI endpoints based on Users, Groups, Roles or Permissions with very little database usage. - codemation/easyauth

inland copper
#

:wasowiski:

versed python
compact flicker
#

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...?

ruby summit
ruby summit
compact flicker
#

I already know that

ruby summit
#

umm
ya so ?

compact flicker
#

wait

#

is there a way to send without doing this

ruby summit
compact flicker
#

k...

#

πŸ‘

ruby summit
#

πŸ™‚

compact flicker
ruby summit
#

guys, i get this error in heroku
the dyno status is 400
what to do ?

distant trout
#

do u guys prefer Server side rendering or client side

distant trout
#

is it working on localhost?

ruby summit
#

code is error free

#

😐

distant trout
#

did u put heroku on ur allowed_hosts?

#

i mean heroku

ruby summit
#

yes

#

i put```py

allowed_host = ['*']```

distant trout
#

oh thats rly weird then...

#

umm

ruby summit
#

ikr

distant trout
#

maybe try explict allowed hosts

#

put in herokus domain instead of *

#

i rarely get issues with django and heroku

ruby summit
#

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 ?

ruby summit
#

😐

distant trout
#

not that i know of. most of my projects on heroku work seamlessly with django

#

more issues with frameworks like flask

ruby summit
#

this 5th one is becoming an issue idk y

distant trout
robust canopy
#

Can u guys giv me some opinion on how should I improve my website?

ruby summit
#

like depends on how it is now

robust canopy
#

Like portfolio

ruby summit
distant trout
#

u wanna improve design?

robust canopy
#

It's OK. I also need some perspective from other ppl

ruby summit
#

it means the same thing

#

'*' and '.herokuapp.com'

distant trout
robust canopy
ruby summit
distant trout
distant trout
#

for example the portfolio page could use some padding

#

the projects you are showing off are too large

robust canopy
#

BTW I also made some slight changes. I'm pushing the latest

distant trout
thick dock
#

hey guys can anyone here help me with something in selenium?

distant trout
#

css grids is awesome for grid layouts and etc

thick dock
#

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

distant trout
#

are u using a headless browser?

thick dock
#

what do u mean by that?

distant trout
#

does selenium actually open up the browser for u

#

on ur pc

thick dock
#

yes

distant trout
#

ah okay so its not headless

thick dock
#

i can get it to open the page

distant trout
#

umm it might be too fast, maybe set a delay? the page could be loading in the drop down asyncronously

thick dock
#

umm let me give it a try

distant trout
#

i think selenium has a wait method

thick dock
distant trout
#

hmm

thick dock
#

idk this is confusing me XD

distant trout
#

are u trying to scrape?

#

or automate something?

thick dock
#

automate

#

I want to select one of these options

distant trout
#

found this on a stackoverflow question

s1 = Select(browser.find_element_by_id('highlightunits'))
s1.select_by_visible_text('Inches')
#

most probably wont work

thick dock
distant trout
#

if u cant access the dropdown by class

thick dock
#

But theres no id

distant trout
#

yeah

thick dock
#

and i tried by class unless i did that wrong

distant trout
#

can u select other elements by class name?

thick dock
#

element = driver.find_element_by_class_name("js-pg-changemange-search-type")

#

This is correct right?

distant trout
#

yea

thick dock
distant trout
#

thats weird

#

can u select a simple p tag on the page?

thick dock
#

p?

past cipher
#

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.

distant trout
#

paragraph

thick dock
#

how would i do that

distant trout
#

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

past cipher
#

use xpath @thick dock

distant trout
#

but yeah, i usually have more success with xpath than class name

thick dock
#

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']")

past cipher
#

whats the website so I can check it out for you

thick dock
past cipher
#

there has been a lot of message, what are you trying to get

distant trout
#

oh yeah

#

this is a async load

#

most of the content is loaded in later with javascript

thick dock
#

oh

past cipher
#

maybe try sleeping for 20 seconds

#

whilst the js loads

distant trout
#

^

thick dock
#

oo

#

what would be the command for that?

distant trout
#

try time.sleep instead of selenium wait

past cipher
#

from time import sleep
sleep(20)

#

but 20 is maybe too long, 5 should be enough i think

thick dock
#

ok

#

guys i just wanna say

#

you are legends

distant trout
#

😳

past cipher
#

glad you got it working πŸ˜„

thick dock
#

so to select an option

#

i can do it by value?

distant trout
#

you should be able to, yeah

thick dock
#

how do i send a left click?

distant trout
#

.click on the element

#

one of my first automations with selenium, i just used pyautogui to do the mouse movements for me

thick dock
#

oo

distant trout
#

kinda inefficient but it worked xqcOmega

thick dock
distant trout
#

no problem

reef oasis
#

Try searching about Flask logging options, maybe changing logging level works for you

hidden ice
#

hello everyone, does anyone have info about control panel for routing system with google api?

native tide
#

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

lilac belfry
#

anyone know how to use mod_rewrite so like /test/a/b/c would goto /test/index.php/a/b/c

native tide
#

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?

dusky rock
#

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

wheat skiff
#

hi, can any one help me with a django project?
i need to create a DB for users

wheat skiff
#

thank you

native tide
#

@dusky rock I'm glad you mentioned FastAPI, it sounds interesting, impressive and of course, fast.

ocean dirge
#
.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

valid girder
tacit brook
#

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?

tacit brook
#

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.

dawn citrus
#

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.

tacit brook
#

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

dawn citrus
#

<link rel="stylesheet" href="{{ url_for('static', filename='css/main.css') }}">

tacit brook
#

nvm

dawn citrus
#

Anyone?

#

sigh looks like I'll be alone again

tacit brook
#

same

vestal hound
#

for the browser not to cache?

dawn citrus
#

Well I mean I would expect the page to reload with my changes instantly

vestal hound
#

my guess

#

is that

#

the CSS is being cached

#

do you want to disable that?

dawn citrus
#

Yeah I think that's happening

vestal hound
#

you're developing on localhost?

dawn citrus
#

Yeah I want to disable that

vestal hound
#

you know how to inspect CSS?

#

I presume you're using Django?

dawn citrus
#

Nope

#

Flask

#

@vestal hound

vestal hound
#

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

dawn citrus
#

Ok

haughty canopy
#

!d discord.on_command

lavish prismBOT
#

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.
haughty canopy
#

sorry wrong channel

sharp tiger
#

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

lapis inlet
#

Can someone tell me how to do oauth2 in django

native tide
lapis inlet
#

I want one for discord@native tide

native tide
native tide
hazy beacon
#

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

minor horizon
#

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?

wispy moss
#

hello guys how to sign XML payload with private key and certificate ???

native tide
stable ledge
#

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?

toxic matrix
#

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
dense slate
#

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?

native tide
native tide
nimble epoch
dense slate
#

Yea I really love Django. Is there anything new that's worth looking at as it relates to Django or upcoming python frameworks?

native tide
# toxic matrix i did

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

nimble epoch
#

i dont know what you looking for but yeah you can almost do anything using django

native tide
native tide
gritty cloud
#

you can use the command py -m venv env-name

#

at least on windows

#

then you can use pip easily

native tide
gritty cloud
#

also true

toxic matrix
gritty cloud
#

you may want to just open cmd

#

and cd into your project

native tide
#

just open cmd and cd into your project and then try django-admin startproject name again

toxic matrix
# gritty cloud you can use the command `py -m venv env-name`

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
native tide
#

u got pyhton installed and in your windows path?

toxic matrix
#

i installed python 9 times

#

because everyone said python was not installed

native tide
#

ok but also added it to the windows path thats essential

toxic matrix
native tide
#

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

native tide
#

i dont use repl but probably

toxic matrix
toxic matrix
native tide
#

are you in the right directory? you need to be in the directory with manage.py

native tide
#

then django isnt supported on repl bc u need atleast that file after you have created your django project

native tide
#
<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?
native tide
# toxic matrix

make a ls or dir to see in which director you are and what files you can call then

native tide
toxic matrix
native tide
#

thats how i mean it
Django is just the project title

toxic matrix
#

main.py poetry.lock pwhTutorials pyproject.toml got this in response

#

@native tide ???

native tide
#

yeah youre a directory above you need to cd into it. so type

cd pwhTutorials 

in your case

native tide
toxic matrix
#

@native tide ~/web$ cd pwhTutorials ~/web/pwhTutorials$

native tide
native tide
toxic matrix
native tide
#

dont run startproject again rather start the server

native tide
toxic matrix
native tide
toxic matrix
# native tide that
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.```
native tide
# native tide html;

you know basic vanilla javascript? bc you can get the value you want with javascript and then go on

native tide
toxic matrix
native tide
toxic matrix
native tide
native tide
# toxic matrix

that probably is bc of repl. why dont you make inot in repl

toxic matrix
native tide
toxic matrix
native tide
#

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

toxic matrix
#

i can give u repl link

native tide
toxic matrix
native tide
# toxic matrix dmed

ok but how does that solve your vscode error? bc i dont think it will work with repl

toxic matrix
native tide
toxic matrix
native tide
#

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

toxic matrix
native tide
#

ok

native tide
#

Hey, i need to get selected and submitted values that user selected in html <select> tag

merry geyser
#

yo can someone tell me

#

whats the issue with my game

#

i dont understand

toxic matrix
noble spoke
#

Only if you ask a question

native tide
#
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

noble spoke
#

Show us the url in your browser please

native tide
noble spoke
#

If you set the flask app to port 5000 and go there you see nothing?

native tide
#

nope

noble spoke
#

Remember to restart the app

native tide
#

wdym,

noble spoke
#

Kill it and rerun the flask app

native tide
#

im on replit

noble spoke
#

What

#

Why

#

How do you expect to reach that machine's localhost if its on a different machine

native tide
#

its, complicated. my device doesnt exactly support vsc or

noble spoke
#

You dont need vsc to make a flask app

native tide
#

rn, my port is set at 5000

#

and the url also says 5000

#

should i get a help channel

noble spoke
#

localhost is machine specific, you cant access some other pc's localhost

#

I suggest you get off replit and try it offline

candid urchin
#

how do i prevent this

ebon tulip
reef oasis
#

What command are you using to run the app?

#

python app.py or do you use flask-manager (python run.py runserver)?

native tide
#

How to get what user selected and submitted in html <select> tag?

nimble epoch
#

not remember exactly

#

and name or value attr to its options. play with it

nimble epoch
#

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

stray venture
#

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

nimble epoch
#

what is this?

#

i cant rec anything

native tide
hearty granite
#

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?

deft coyote
#

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>
opaque rivet
# deft coyote I'm using flask & wtforms to create a recipe site, mostly using Miguel Ginberg's...

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.

opaque rivet
#

!code

lavish prismBOT
#

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.

opaque rivet
deft coyote
#

@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'>```
opaque rivet
deft coyote
#

Yes that's right, I can paste code snippets from the working one if that would be useful.

opaque rivet
#

sure, I wouldn't expect that to be the case

deft coyote
#
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.

hearty granite
# opaque rivet !code

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.

opaque rivet
opaque rivet
deft coyote
#

<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 haven't been able to get that working yet though

#

it doesn't explain why it is working in the other context though

opaque rivet
#

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.

deft coyote
#

hmm

opaque rivet
#

e.g. form = EditRecipeForm("some_recipe")

deft coyote
#

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

foggy bramble
#

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

opaque rivet
#

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.

foggy bramble
deft coyote
#

thanks @opaque rivet I'll give that a shot

foggy bramble
opaque rivet
# foggy bramble can u please tell me how
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).

foggy bramble
#

I want to iterate it and print

#

for key in di:
  print(di[key])

#

something like this

opaque rivet
#

in your template:

{% for key in d1 %}
  {{ d1[key] }}
{% endfor %}
foggy bramble
#

this doesnt parse I've already tried

opaque rivet
#

could you try:

{% for value in d1.values %}
  {{ value }}
{% endfor %}
foggy bramble
#

this is the solution

#

key, value in dict.items

#

thanx

#

worked btw

deft coyote
#

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 : (

hearty granite
deft coyote
#

ah that feeling that can't be replicated.... the feeling of spending 5 hours troubleshooting an extra comma lol

opaque rivet
#

haha, that's tough πŸ˜„

opaque rivet
#

just pass a unique id to each.

hearty granite
umbral pivot
valid girder
#

Do you guys use REST or GraphQL?

inland oak
deft coyote
#

@pale crescent have you tried switching the validator for that form method from DataRequired() to FileRequired()?

pale crescent
#

oh

#

It still doesn't work

#

~~@deft coyote ~~

deft coyote
#

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

pale crescent
#

Oh, I'm sorry

deft coyote
#

i've been following his tutorial for all the other stuff i'm doing in flask

pale crescent
#

Oh okay

inland oak
#

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)

deft coyote
#

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

lavish prismBOT
#

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:

https://paste.pythondiscord.com

shell heath
#

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

pale crescent
#

@deft coyote, I forgot to put enctype="multipart/form-data" in <form>, that was all, I'm dumb-

manic frost
red star
#

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

craggy pulsar
#

I need Help on django

NameError : name 'os' is not defined

I put [os.path.join(BASE_DIR, 'templates')]

sand glen
#

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?

grim tiger
#

@sand glen By adding authorization to it.

sand glen
#

wdym by that?

grim tiger
#

Authentication means requiring the client to login, authorization controls what you have access to.

#

What are you using for authentication?

main night
#

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?

jade lark
main night
#

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?

jade lark
#

Yes, if Django is in debug mode

main night
#

yup

#

it is

jade lark
#

Turn it off if you're trying to do accurate testing.

#

What are you trying to determine?

main night
#

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

jade lark
#

Gotcha. Is this so you can find out what framework to go with?

main night
#

it's for thesis

jade lark
#

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.

main night
#

is gunicorn something like docker?

jade lark
#

No. gunicorn allows you to setup workers and threads so that your webserver isn't running on a single thread/process.

main night
main night
#

but still about my question, does this chart looks normal?

jade lark
#

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.

main night
#

ok, i was worried that there are spike when users count drops, but it seems like previous users are still waiting for response, right?

jade lark
#

Correct. They would be waiting for a response.

main night
#

ok, thank you very much πŸ™‚

jade lark
#

No problem! Best of luck

native tide
#

do you guys know what is the purpose of test.py in django?

lime fox
#

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"

main night
#

            mysqli_query(query ,[user_username, user_password, user_userid]);```
#

something like this?

lime fox
#

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

main night
#

oh, sorry, you're writing that in php right?

lime fox
#

yes

main night
#

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);

lime fox
#

my guy

#

thank you very much

#

where do i close connection?

#

after all the php right?

main night
#

after passing query

peak thicket
#

Does CORS policy apply to websockets?

jade lark
keen ravine
#

Hey guys! I am trying to automatically login to my Microsoft account by selenium - python

lime fox
#

How would i go about writing a function that creates a random number of a specific length like:

function random_num($length)

jade lark
keen ravine
#

This is my code

jade lark
keen ravine
#

But it gives me this error

lime fox
#

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

jade lark
#

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

keen ravine
#

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?

jade lark
# keen ravine 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

keen ravine
#

Am a beginner

#

So what should I do now?

jade lark
#

This isn't related to web development so I would look at a help channel or a different section

inland oak
#

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

lime fox
#
        $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 ?

inland oak
sand glen
lime fox
#

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

sand glen
#

oof PHP

lime fox
#

i cant begin to say how much i hate it

#

however its due monday so any help appreciated

inland oak
# lime fox however its due monday so any help appreciated

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

lime fox
#

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

inland oak
#

last time I used php, happened 3 years ago. And I did not reach databases

lime fox
#

ahhhhh well thanks for trying to help anyways

stone citrus
lime fox
#

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

stone citrus
#

Sorry, I was referring to the if(!empty($u_username) && !empty($u_password) && !is_numeric($u_username)) check

jade lark
#

The really bad part is it's literally using plain text passwords though...

lime fox
#

ok i see where you mean now, where would i use isset()?

stone citrus
jade lark
#

replace empty with isset

lime fox
#

now its returning "please enter some valid info"

#

instead of wrong user or pass

jade lark
#

also replace die; with die(); as it's supposed to be calling a function

lime fox
#

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

stone citrus
lime fox
#

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

lime fox
jade lark
#

it takes an array and dumps it or an object

lime fox
#

and how do i do that

jade lark
#

var_dump($user_data);

stone citrus
lime fox
#

where should i put that

jade lark
#

Below $user_data

stone citrus
lime fox
jade lark
#

Yeah it's not passing the conditional check

lime fox
#

if($result && mysqli_num_rows($result) > 0)

#

this one ?

stone citrus
#

put it above if($result)

#

So var_dump($result)

#

Because at the moment your code isn't making it past the if($result) check

jade lark
#

Assuming the form data is provided correctly

stone citrus
#

Which probably means there isn't any data being fetched from the db

lime fox
#

nothing happened again

jade lark
#

then the form data isnt valid

lime fox
#
            <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

jade lark
#

echo $u_username;
echo $u_password;
die();

stone citrus
#

I think you've mixed up your form value ids and database ids

#

So

lime fox
stone citrus
#

So $u_username = $_POST['user_username']; $u_password = $_POST['u_password']; should be $u_username = $_POST['u_username']; $u_password = $_POST['u_password'];

jade lark
#

basically in your form you have the name=""

stone citrus
#

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'];

jade lark
#

Those values need to match the keys for $u_username and $u_password

lime fox
# stone citrus To clarify, ` if($_SERVER['REQUEST_METHOD'] == "POST") { $u_use...
<?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

stone citrus
#

I think we should just start from the top, since it's getting confusing where exactly your code is being terminated at

lime fox
# jade lark Those values need to match the keys for $u_username and $u_password
<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" ?

jade lark
#
$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.

lime fox
#

thats what i entered yeah

jade lark
#

Good

#

remove the echo and die now

lime fox
#

and thats the db record

stone citrus
#

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

lime fox
#

under the

$u_username = $_POST['u_username'];
        $u_password = $_POST['u_password'];
``` ?
stone citrus
#

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))

jade lark
#

Just so you know tvanom if you use three tildas top and bottom it does the code block

#

`

lime fox
#

bool(false) Please enter some valid information

#

thats the message up top

stone citrus
#

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

lime fox
#

should i remove the isnumeric part

#

technically dont need it t here might be messing something up

stone citrus
#

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

lime fox
#

bool(true) bool(false) bool(true) Please enter some valid information

#

password?

stone citrus
#

Yup

lime fox
#

ok why is it failing?

stone citrus
#

So when you printed out password, you got kacper13542 right?

lime fox
#

yes

stone citrus
#

Oh, you need to replace !isset($u_password) with isset($u_password)

#

I.e. remove the !

lime fox
#

wait i think we made progress maybe ?

stone citrus
#

It should make it into the if statement now?

lime fox
#

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

jade lark
#

Remove:

echo $u_username;
echo $u_password;
die();

Replace with:

var_dump($results);
stone citrus
#

Ok great. Now before removing the die(); just do a var_dump($result)

jade lark
#

Ehh

stone citrus
#

Just incase there's a problem with the query results

lime fox
#

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)

stone citrus
#

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();```
lime fox
stone citrus
#

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();```
lime fox
#

bool(true) bool(false) bool(true) bool(false)

#

so false

stone citrus
#

Hmm, it should only be printing one value

#

Can you paste your entire code block again please?

lime fox
#

whole php or everything ?

stone citrus
#

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";
    }
}

?>```

lime fox
#
<?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";
        }
    }
?>
fast yoke
#

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!

jade lark
fast yoke
#

i have a logo on the left and clickable stuff on the right, but on one line

jade lark
#
@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;
    }
}
lime fox
jade lark
#

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

Master Flexbox layout: a game by geddski

fast yoke
deft coyote
#

ooh a zombie css game

fast yoke
#

ill google everything

deft coyote
#

nice link

stone citrus
lime fox
#

that was from the previous var dumps

#

ive removed them now and it just returns false

jade lark
stone citrus
# lime fox

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 ?

jade lark
#

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.

lime fox
jade lark
deft coyote
#

yeah im aiming my crossbow already

#

this is neat

lime fox
stone citrus
stone citrus
# lime fox yes

Okay, you probably need to change $query = "select * from users;"; to $query = "SELECT * FROM user_table;";

lime fox
#

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

jade lark
#

πŸ₯³

#

yes

lime fox
#

so what does this mean

stone citrus
#

I think we were selecting data from a non-existent table before, so no results were being returned

lime fox
#

i see

stone citrus
#

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;";

lime fox
#

should i remove tthe vardump now ?

stone citrus
#

You can remove the var_dump and die(), yes

jade lark
#

Just know ptak this script should not be used in production.

stone citrus
#

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){

jade lark
#

It's prone to SQL injection and a bunch more.

stone citrus
#

Yeah, you should look into mysqli_real_escape_string()

lime fox
#

its just for a basic assignment there isnt any marks for security and stuff

stone citrus
#

Or PDOs

#

Ah fair enough then

jade lark
#

I was going to say PDO now

lime fox
#

now im getting this :

Warning: Undefined array key "u_password" in C:\xampp\htdocs\Website\login.php on line 29
Wrong username or password!

stone citrus
#

Right, so if you make those above changes, what's the output looking like?

lime fox
#

this is line 29

jade lark
#

swap to user_password

#

and user_username

lime fox
#

which one the first or second

jade lark
#

as those are the column names

#

$user_data['user_password']

stone citrus
#

Yeah, so if($user_data['user_password'] === $u_password) {

lime fox
#

nothing happened

#

there was no error though

stone citrus
#

Ok, so that probably means that it ran as expected?

jade lark
#

It probably worked then

lime fox
#

should it not redirect me to websiteattempt (1).PHP?

jade lark
#

below the header(); add echo "Ran successfully";

stone citrus
#

You can remove the last die();

jade lark
#

Or that too

stone citrus
#

Probably best to do what magic said

lime fox
#

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";
        }
    }
?>
jade lark
#

wait whoops

#

add it before the header

lime fox
#

still nothing

jade lark
#

remove the header too

lime fox
#

i have a feeling i messed up on the session part

jade lark
#

probably is redirecting

#

You'd get an error if you did I believe

lime fox
#

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!
jade lark
#

cause it didnt die

#

so

#

echo "ran successfully!";
die();

lime fox
#

so it worked but whats the user id error

#
$_SESSION['user_userid'] = $user_data['user_id'];
jade lark
#

user_id doesn't exist in the result from sql

#

it's supposed to be

lime fox
#

i have a feeling this isnt real

jade lark
#

$user_data[''user_user_id"];

lime fox
#

user_userid but yeah did that

jade lark
#

Then it worked

lime fox
#

how do i make it redirect me to home page

#

and also make sure that im logged in

jade lark
#

remove the echo and die();

#

then re-add the header

lime fox
#

okay it works thats great but i need to make sure that it doesent work when i put the wrong stuff in

jade lark
#

so try putting invalid info

lime fox
#

how do i clear a session?

#

beacuse im perma logged in

stone citrus
#

Open a private browsing window

lime fox
#

moment of truth

#

omg

#

i actually cant believe it

jade lark
#

Now the important thing is do you understand what you had to change to get it to work?

lime fox
#

i think i did yes

stone citrus
#

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.

lime fox
#

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

stone citrus
#

Those situations are always rough

#

Is the assignment just a login system?

jade lark
#
Laracasts

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...

lime fox
#

its a whole website

jade lark
#

I highly recommend laracasts for PHP

lime fox
#

that was just the login system i was stuck on

jade lark
#

Better practices as well

lime fox
#

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

stone citrus
#

Happy to help

timid acorn
#

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

fast yoke
#

ist this little space normal? it's a flex box

opaque rivet
opaque rivet
fast yoke
opaque rivet
regal raven
#

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)```
nimble epoch
#

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>
)
}
}

opaque rivet
nimble epoch
#

its django rest problem

opaque rivet
#

e.g.:

.catch(res => {console.log(res.response.data})
nimble epoch
#

when i submit the form with image in part serializer.is_valid() seems like it doesnt accept it

opaque rivet
nimble epoch
#

ok let me check

#

how long you been working with react and django?

nimble epoch
#

and i checked the data all been there

opaque rivet
nimble epoch
#

wait..

#

the models are seperated

#

and im trying to get AccountSerializer data from UserSerializer can it be related?

#

while they are two seperated serializers

nimble epoch
#

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--

opaque rivet
# nimble epoch serializers.py```py class AccountSerializer(serializers.ModelSerializer): cl...

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?

nimble epoch
#

yes

#

i think thats bacause i have two different serializers

#

wait a minute i try a thing

opaque rivet
#

looks like DRF doesn't support nested serializers when it's multipart/formdata

nimble epoch
#

oh ok thanks ill check it

opaque rivet
#

I think this explains the problem exactly

#

And I think the DRF multipart parser would help. I haven't used it though

#

@nimble epoch

nimble epoch
#

i think i got it

#

i changed the serializer and its working

nimble epoch
opaque rivet
nimble epoch
#

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

opaque rivet
#

so the pp field did not exist in your Account model?

nimble epoch
#

no pp field doesnt exists in User model

opaque rivet
nimble epoch
#

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

regal raven
#

big pp hours

nimble epoch
regal raven
#

there is a reason "pfp" is the canonical abbreviation of profile picture, and not "pp"

opaque rivet