#web-development

2 messages · Page 149 of 1

nimble epoch
#

never tried that

opaque rivet
#

try it out

nimble epoch
#

then i think i gotta change some of codes i got tired but yeah ill try it out thanks alot

opaque rivet
nimble epoch
#

i changed my serializer

#

but wait... lol

#

why it doesnt save the picture

#

it deletes the picture but doesnt save the new pic

opaque rivet
nimble epoch
#

i mean i switched to AccountSerializer from UserSerializer

#

cause i didnt have profile picture field in it

opaque rivet
#

I don't think that will solve your issue. Your AccountSerializer still won't receive the username and the password, or does it?

nimble epoch
#

thats not actually a solution i been stupid

nimble epoch
opaque rivet
#

can you post the code?

nimble epoch
#
@api_view(['GET', 'POST'])
def register(request):
    serializer = UserSerializer(data=request.data)
    if serializer.is_valid():
        username = serializer.data['username']
        password = serializer.data['password']
        user = User.objects.create_user(username=username, password=password)
        return Response(True)
    return Response(serializer.errors)

@api_view(['POST'])
def upload_image(request, user_id):
    serializer = AccountSerializer(data=request.data)
    if serializer.is_valid():
        pic = serializer.data['pp']
        c_user = User.objects.get(id=int(user_id))
        account = Account.objects.get(user=c_user)
        account.pp = pic
        account.save()
        return Response(True)
    return Response(serializer.errors)
#

but there something wrong with it

#

AGAIN

#

it deletes the previous picture but doesnt save the new pic

#

and of course this is a kinda dirty code

#

this is actually a practice

#

you dont want to use it

opaque rivet
#

pass in all of your information through your request (instead of the query params) - then do serializer.save(), that will make it much cleaner.

nimble epoch
#

yeah

nimble epoch
#

not that important i just wanted to upload the image

lavish prismBOT
#

Hey @drowsy knoll!

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

inland oak
#
if not seralizer.is_valid():
    return('not valid')

In this way, your code will be more pytonish

At situation when there are a lot of checkers
It will keep your code from descending into multi nested if nightmare

(Plus think about changing status to 400 or something, 200 is not looking cool here)

#

Going to have soon same drf problem

vestal hound
#

there isn't one

hard lantern
#

Hey guys I need help with my socket program

#

This is the description: Your job is to create the special-purpose web server to provide the backend to this functionality. Due to
corporate requirements, you must use the socket interface, and cannot use any module implementing a web
server directly. The program will answer various web queries and return a result. Below is an example.
Example: With the web server running, enter in the following formula into any cell in Excel 2013 (or Excel
2016):
=WEBSERVICE(“http://localhost:1234/zip/98101)
Excel should then show a result of:
Seattle, WA

sleek crest
#
driver_path = r'C:\\StudentSquare\\resources\\webdrivers\\msedgedriver'
def ope(driver: webdriver.Edge):
    if driver == None:
        driver = webdriver.Edge(driver_path)
    driver.get(website)

def run():
    ope()
    time.sleep(1.5)
    print('Opening')```
``in run
    ope()
TypeError: ope() missing 1 required positional argument: 'driver'
``
#

?

grim leaf
#

Try default argument lol

sleek crest
#

which is?

#

@grim leaf

grim leaf
sleek crest
#

thanks

jovial mist
#

How do I tell my flask app that the resource I'm sending is css? Google says this Resource interpreted as Stylesheet but transferred with MIME type text/html and this is my code ```py
@app.route("/static/css/style.css")
def style():
with open("static/css/style.css") as file:
return file.read()

grim leaf
#

You can just put the CSS within the HTML and serve the HTML instead

jovial mist
#

Ok

#

How do I use flask.Response?

nimble epoch
nova nacelle
#

React page reloads and gives forbidden with django!

sonic pivot
#

Anyone know HTML for adding a chat bot window in the bottom right?

inland oak
#

in laziest choice, it could be inserted as some sort of iframe from another service

#

then it would be literally HTML only

slim maple
#
#POST-requests mechanics
    if request.method == 'POST':
        form = ReviewForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            name = data.get("name")
            email = data.get("email")
            review = data.get("review")
            rating = data.get("rating")
            Review.objects.create(name=name, email=email, review = review, rating=rating)
            return redirect('reviews')
    form = ReviewForm()
    #review_1 = Review.objects.get(id=1)
    #print(review_1.review)
    reviews = Review.objects.all()
    return render(request, 'reviews.html', {"form": form})

    form = ReviewForm()
    return render(request, 'reviews.html', {'form' : form})``` The above exception (table reviews_review has no column named review) was the direct cause of the following exception: is the error
#

pls help

nimble epoch
nova nacelle
#

Now i wanna know can react-django integration work without using rest api?

nimble epoch
#

unless you find a way to change it and itll get a bit complicated i think never used them without rest

nova nacelle
#

i did in js without api with ajax

nova nacelle
nimble epoch
#

never used firebase

nova nacelle
#

Can't define models ig

#

Can i just post data SOMEHOW to my backend?

#

Maybe ajax?

nimble epoch
nova nacelle
nimble epoch
#

dont think you can without changing your data to another type

nova nacelle
nimble epoch
#

in react its a type and django another. no difference you sending or getting data in both you gotta change the data type

nimble epoch
nova nacelle
#

Hmm, let me check rq, thanks

nimble epoch
#

yw

opaque rivet
#

@nova nacelle REST is just a specification for APIs. For your react and django backend to communicate you will have to make a django API and make requests to your endpoints from your frontend.

Just like python has the requests library, JS has Axios which is great for sending requests to your django backend.

nova nacelle
quasi relic
#

guys any idea what database should I go with with flask?

opaque rivet
#

@nova nacelle you're gonna have to show some code if you expect meaningful answer

nova nacelle
#

Post requests doesn't work

native tide
#

@quasi relic sqllite or mongoDB are both good

#

I think there is a tutorial out there that uses MongoDB

quasi relic
inland oak
# nova nacelle Post requests doesn't work

sqlite and mongoDB have completely different approaches
to answer which db to choose
you need to define, how much users you would have
and which... data are you going to store there

#

sqlite is general all around, good for starting development

#

postgresql/mysql is general all around, good for a more advanced web site
they are in their behavior actually almost sqlite, but more 'multithreading' friendly, more functional, more powerful than sqlite

nova nacelle
inland oak
#

mongodb is not... a regular sql database at all

nova nacelle
#

y ping me smh

inland oak
#

it is NoSQL database

#

it can work only for a very specific types of data, I usually see mongoDB as really big python dictionary

#

it has no regular relationship, which regular sql database uses

#

usually used for optimization of some... more bulker data storaging

native tide
#

I print this ```py
request.environ.get('HTTP_X_REAL_IP', request.remote_addr)

nimble epoch
#

probably your vpn trash

native tide
nimble epoch
#

google pretending. just want you to feel comfortable while there something else happening in the background

native tide
#

LOL

nimble epoch
#

I knew something wrong with google

native tide
#

EVERYTHING EXCEPT MY SITE

#

xDDD

nimble epoch
#

maybe because these all are published on google servers

native tide
#

ahh

nimble epoch
#

google is too powerful

native tide
#

XD

dapper tusk
dapper tusk
#

then the VPN will not do anything

#

VPNs don't apply to requests in our local network, since your local network is not accessible from the wide internet where the VPN server is

#

if you were to say, put your website on some crappy freehost and then connect to it, the VPN will work correctly

native tide
opaque rivet
#

@nova nacelle what is your forms enctype? If you show some code then you can help people help you.

#

@slim maple Review model has no column 'review', did you add the column and forget to migrate?

echo notch
#

uhh hi

#

I wanted to ask that I am new to webscrapping in b4soup

#

so can someone help me

#

I want to scrape a webpage

#

I am trying to scrape this page

#

it shows the HTML type when I like instpect element

#

but when I do view page source its something else

#

and In Beautfull soup its scrapping the page source

inland oak
#

i used xpath, I found it was comfortable to use

echo notch
#

will it help me in what I am trying to do?

honest dagger
#

I keep getting errors while trying to git push heroku master

#

remote: ERROR: Could not install packages due to an EnvironmentError: [Errno 2] No such file or directory: '/home/ktietz/src/ci/alabaster_1611921544520/work'
remote:
remote: ! Push rejected, failed to compile Python app.
remote:
remote: ! Push failed
remote: !
remote: ! ## Warning - The same version of this code has already been built: 55e*******************
remote: !
remote: ! We have detected that you have triggered a build from source code with version 55*****************
remote: ! at least twice. One common cause of this behavior is attempting to deploy code from a different branch.
remote: !
remote: ! If you are developing on a branch and deploying via git you must run:
remote: !
remote: ! git push heroku <branchname>:main
remote: !
remote: ! This article goes into details on the behavior:
remote: ! https://*********
remote:
remote: Verifying deploy...
remote:
remote: ! Push rejected to tabula-ludos.
remote:
To https://*********
! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://**********'

#

someone please help

native tide
#

code py for weapon_steam, weapon_nice in weapons: weapon_rows += "<tr><td>Stat</td><td>value</td><tr><td>Stat1</td><td>Value2</td>" why on the site it looks like this stat| 24564 | value| 17% | it should be like this stat1 | 24564 | Value2| 17% |

native tide
opaque rivet
native tide
#

true you could do it like that

<table>
 {% for weapon_steam,weapon_nice in weapons %}
 <tr>
  <td>Stat</td>
  <td>{{ weapon_steam }}</td>
  <td>value</td>
  <td>{{ weapon_nice }}</td>
 </tr>
 {% endfor %}
</table>

for example

opaque rivet
#

if I'm looknig to deploy, is it useful to learn nginx or should I just hop straight into learning AWS?

inland oak
wraith sierra
#

hi guys, i am trying to read .GBFF files and extract information out of it. has anyone ever worked with .GBFF files?

#

looking for something like gbff to json converter but unable to find anything useful

lime fox
#

hello good people, using php can i structure a query like this ?

$query = "SELECT * FROM university_table WHERE uni_nationalrank $NationalRank";
$result = mysqli_query($con, $query);
#

taking into account that the value $NationalRank holds is :

>=0 AND <11
#

would that work the same as just the normal query:

SELECT * FROM university_table WHERE uni_nationalrank >=0 AND <11
lime fox
#

And also how do i print the results from a search

#
        $query = "SELECT * FROM university_table WHERE uni_nationalrank >=0 AND <11";
        $result = mysqli_query($con, $query);
        echo ($result['uni_nationalrank']);

i tried using this

#

which resulted in this error

Warning: Trying to access array offset on value of type bool in C:\xampp\htdocs\Website\Websiteattempt (1).php on line 19
stone citrus
lime fox
#

This is the selection box, i set the value to that, does it mean that its a string and works correctly?

                   <select name="NationalRank" id="in_NR">
                      <option value=">=0">Don't mind</option>
                      <option value=">=0 AND <11">Top 10</option>
                      <option value=">=0 AND <26">Top 25</option>
                      <option value=">=0 AND <51">Top 50</option>
                      <option value=">=0 AND <101">Top 100</option>
                    </select>
stone citrus
#

That could potentially work, yes

#

However, i'd recommend not putting any sql inside your form values

lime fox
#

what other way do you recommend doing it ?

sonic pivot
#

Anyone able to help with making a chat pop up window on my website

stone citrus
#

You'd probably want to just set the values like this

<select name="NationalRank" id="in_NR">
    <option value="na">Don't mind</option>
    <option value="top_10">Top 10</option>
    <option value="top_25">Top 25</option>
    <option value="top_50">Top 50</option>
    <option value="top_100">Top 100</option>
</select>

Then in your backend construct the sql from these values

$NationalRank = $_POST["NationalRank"];
$RankLowerBound = 0;
$RankUpperBound = null;
switch ($NationalRank) {
    case "top_10":
        $RankUpperBound = 10;
        break;
    case "top_25":
        $RankUpperBound = 25;
        break;
    case "top_50":
        $RankUpperBound = 50;
        break;
    case "top_100":
        $RankUpperBound = 100;
        break;
}
$BaseQuery = "SELECT * FROM university_table WHERE uni_nationalrank WHERE uni_nationalrank > ". $RankLowerBound;
if($RankLowerBound) {
  $BaseQuery .= " AND <= ". mysqli_real_escape_string($RankUpperBound);
}
#

Then use $BaseQuery in place of your original one

#

Basically what we're doing here is removing the sql from the form value and instead constructing it on the backend

lime fox
stone citrus
# lime fox thank you very much but what is switch and case ive never seen that

Right yeah sorry, it's basically an alternative of doing a bunch of else ifs, so instead of doing

if($NationalRank == "top_10") {
  do something
}
else if($NationalRank == "top_20") {
  do something
}
else if...

we can do

switch($the_variable_you_want_to_check) {
  case "is it's value equal to this?":
    yes, so do this...
  case "is it's value equal to this?":
    ...
}
lime fox
#

i see, i have 5 of these boxes to do would i just copy and paste 5 times and change the variables ?

cedar mortar
#

Does anyone know of a good way of managing circular imports in django? other than 'apps' or importing the file instead of the model itself?

cobalt spruce
#

how do you reverse a string?

cedar mortar
cobalt spruce
opaque rivet
#

but I guess that is the "apps" way you're talking about

native tide
dawn heath
#

i have currently class Vulnerability(models.Model): links to product, and product to vendor , but then class Exploit(models.Model): links to Vulnerability , and I want to add sources . should this be in Exploit as a fk or class sources with fk to exploit?

viscid valley
#

@dawn heath I'd assume many exploits could have many sources no?

hard lantern
#

Hey guys im trying to convert html tables into csv but my csv doesn't come out right

#

can i get some help?

viscid valley
viscid valley
hard lantern
#
import requests 
from bs4 import BeautifulSoup

# set the url..
url = 'https://developer.mozilla.org/en-US/docs/Learn/HTML/Tables/Basics'

# Open the url and parse the html
req=requests.get(url)

soup = BeautifulSoup(req.content, 'html.parser')

# extract the first table
table = soup.find_all('table')[1]

# write the content to the file
File = open('PGRM4example.csv', 'w')
Data = csv.writer(File)

rowlist=[]

for row in table.findAll('tr'):
    celllist = []
    for cell in row.findAll (['th','td']):
        text=cell.text
        celllist.append(text)
    rowlist.append(celllist)
    Data.writerow(rowlist)

for item in rowlist:
    print(' '.join(item))
    
File.close()```
#

Only my print statement is good

viscid valley
hard lantern
#

@viscid valley thank you!!

toxic pivot
#

To get the owner of the guild, it's guild.owner correct?

viscid valley
# hard lantern <@!178563762972786688> thank you!!
import csv
import requests 
from bs4 import BeautifulSoup

# set the url..
url = 'https://developer.mozilla.org/en-US/docs/Learn/HTML/Tables/Basics'

# Open the url and parse the html
req=requests.get(url)

soup = BeautifulSoup(req.content, 'html.parser')

# extract the first table
table = soup.find_all('table')[1]

# write the content to the file
File = open('PGRM4example.csv', 'w')
Data = csv.writer(File)

rowlist=[]

for row in table.findAll('tr'):
    celllist = []
    for cell in row.findAll (['th','td']):
        text=cell.text
        celllist.append(text)
    rowlist.append(celllist)

for item in rowlist:
    Data.writerow(item)
    
File.close()```
#

I believe that's what you're trying to achieve?

#

I just replaced your print statement with Data.writerow()

hard lantern
#

yess!!!

#

ohh thats's where I messed up lol @viscid valley

viscid valley
#

Ya, happens to the best of us.

toxic pivot
#

To get the owner of the guild, it's guild.owner correct?

viscid valley
toxic pivot
#

One of my commands.

#

Too see the amount of servers my bot is in.

viscid valley
toxic pivot
#

Ahh wrong channel

keen ravine
#

Hey guys! I want to login to my outlook account by using selenium

#

I have an array of passwords, it contains wrong passwords and the correct password

#

I want to pass the passwords, if it finds it wrong, try the next one

#

Until it passes the correct password and sign in successfuly

viscid valley
keen ravine
#

this is my code

keen ravine
#

But do you think I explained it correctly?

viscid valley
#

!rule 5

lavish prismBOT
#

5. Do not provide or request help on projects that may break laws, breach terms of services, be considered malicious or inappropriate. Do not help with ongoing exams. Do not provide or request solutions for graded assignments, although general guidance is okay.

keen ravine
#

So, do you think there's anybody can help me?

#

Or recommend other discord channel

viscid valley
keen ravine
#

So, is there any discord channel I can find help in?

viscid valley
#

If you have questions about non-nefarious projects. People are more than willing to help you.

keen ravine
#

Where I can find them?

#

People who can help me.

viscid valley
#

Send them that code and explain what you're doing.

#

I'm sure someone there will help you.

keen ravine
#

Are you serious? You want me ask to FBI to help me?!

#

Thanks buddy

wispy quail
short brook
#

anyone here any good work with json?

#

I get this glorious error

wispy quail
#

which framework?

short brook
#

flask

wispy quail
#

i cannot see your code

#

^^

short brook
#

I can share it with you

wispy quail
#

Oh i mean normally the best way is to share a pastebin here

#

Then people can get a better idea

tight pike
#

guys this might be a stupid question but can I consider myself a front-end web developer if I can't add an email form to my website

fading bluff
#

Wait

#

Is Python used the same way as JavaScript in terms of interactivity?

viscid valley
native tide
#

hey

#

I'm having issues trying to figure out what i'm doing wrong here...

#
<div style="margin-left: 40px; margin-right: 40px; margin-top: 40px;">
    <div style="background-color: rgba(39, 41, 46, 0.95); border-radius: 3px; box-shadow: 0px 0px 3px #000; float: left; width: 100%; padding: 10px;">
        <h2 style="text-align: left; margin-left: 10px; color: white;">Coming Soon</h2>
        <hr style="width: 100%; margin-bottom: 10px;">
        {% for game in games %}
            <div style="color: lightgrey; width: 129px; height: 172px; float: left; margin: 5px;" onclick="imageClick('/game/{{game.game_id}}/')">
                <img src="{{game.url}}" style="width: 100%; height: 100%; object-fit: cover; border-radius: 2px; box-shadow: 0px 0px 3px black;">
                <p style="">Toegevoegd:<br>{{game.add}}</p>
            </div>
        {% endfor %}}
    </div>
</div>```
terse vapor
viscid valley
wooden ruin
#

any node.js gurus out there? i'm looking to learn a backend nodejs framework, and i've tried nest.js which doesn't feel my style and now i'm taking a look at sails.js, but i'd love any reccomendations on frameworks :)

viscid valley
wooden ruin
#

i already have, i'm just trying to expand my knowledge of web frameworks :)

hard lantern
#

I made a program that scrapes html table and converts them to csv files. My professor wants me to "End each line in the file with the two characters CR and LF "

#

idk how to do that

viscid valley
#

CR is \r
LF is \n

marble spade
#

how would I go about centering that

#

.main{
  text-align: left;
  background: mediumslateblue;
  height: 320px;
  color: whitesmoke;
  overflow-x: scroll;
}
#

thats the css

#

I don't want to scroll down every time

marble spade
vestal hound
marble spade
#

see how it's like hanging

#

down at the bottom

viscid valley
#

Sorry, I miss understood the question.

marble spade
#

hm it's hard for me to phrase

#

I want the image to be centered within the purple box

#

is the best way in which I can describe it

hoary sand
#

hi, i want help regarding bootstrap 5 navbar the font size of navbar items and brand is fine but in mobile its very small. if i increase font size, then its ok for mobile but bigger for laptop, can anyone help me. Images:

tribal pewter
#

<meta name="viewport" content="width=device-width, initial-scale=1">

#

make sure to add this inside your <head>

rancid oak
#

If im displaying data from my database with this:

<table class="table-content">
              <thead>
                <tr>
                  <th>Name</th>
                  <th>Surname</th>
                </tr>
              </thead>
              <tbody>
              <tr>
                <td>{value.Name}</td>
                <td>{value.Surname}</td>
                <td>
                <Button onClick={()=>{deleteWord(value.Name)}}>Delete</Button>
                <Button >Edit</Button>
                </td>
              </tr>
              </tbody>
            </table>

My current output is

Name Surname
John Peterson
Name Surname
Willy Wonka
Name Surname
Donald Trump

But I need the output to be

Name Surname
John Peterson
Willy Wonka
Donald Trump

What should i edit to achieve that?

#

@ me if u have advice pls

tribal pewter
#

and are you using django?

rancid oak
#

Nvm yea it was in a loop i got it fixed :p. Thanks

native tide
# tribal pewter make sure to add this inside your <head>

Try this : ```{% for value in value-list %}

<table class="table-content">
<thead>
<tr>
<th>Name</th>
<th>Surname</th>
</tr>
</thead>
<tbody>
<tr>
<td>{value.Name}</td>
<td>{value.Surname}</td>
<td>
<Button onClick={()=>{deleteWord(value.Name)}}>Delete</Button>
<Button >Edit</Button>
</td>
</tr>
</tbody>
</table>

{% endfor %}```

#

hello

#

how do i make my own google drive indexer?

#

hello guys

#

guys

#

help

zealous tinsel
#

hello

#

anybody knows how execute python app into webpage ?

native tide
#

I need help with python django. Can someone help?

#

I get an error

#

"decimal.Decimal"

#

And i want to try convert this to a flot value or something

native tide
#

A game database dashboard

hazy beacon
#

Hey if I have stuff imported in my webapp like python libs (pillow for example). Does the web host solve the dependancies or do u need to compile the libs yourself

vestal hound
#

and how

#

but generally you need to provide a requirements.txt at least

native tide
#

hey anyone online here?

#

i need some help

#

so the css file is not loading ...i migrated the assets ...even though it shows like this

#

any solution

terse vapor
terse vapor
#

did u change the url_for into ur folder?

#

and to ur file name?

native tide
#

i copied the scripts of the css file and added them inside the style tag in the html file itself and it worked

#

the styles and animations are okay but images are not loading

wheat skiff
#

hi, i need to make a chat in django, can some one help me?

terse vapor
opal portal
#

django, when i ran the runserver command i received an type error like this TypeError: XXXViewSet() received an invalid keyword 'method'

#

what is wrong here and how to fix it

native tide
# native tide any solution

U did declare the static and media root and url path in the settings.py,right? mby theres an error bc your file tree looks kinda messy. If not pls send a screen shot of the web dev tool console and network tab bc that often helps

native tide
wheat skiff
#

hi, i need to make a chat in django, can some one help me?

native tide
maiden tulip
#

Is it still required to validate an email pattern for a form or is <input type="email" sufficient?
From MDN docs:

The <input> element's value attribute contains a DOMString which is automatically validated as conforming to e-mail syntax. More specifically, there are three possible value formats that will pass validation:

so it is checked against a pattern already or not?

opal portal
# native tide does it show in which line the error is and if so pls show the code
#views.py
class ContributionViewSet(viewsets.ModelViewSet):
    queryset = Contribution.objects.all()
    serializer_class = ContributionSerializer
    permission_classes = [permissions.IsAuthenticatedOrReadOnly]
   
    # Get list of contributions by faculty_id. Example URL : api/contribution/contributions/by-faculty/1/
    @action(detail=False, method=['GET'], url_path='by-faculty/(?P<faculty_id>\d+)/$')
    def faculty(self, request, *args, **kwargs):
        queryset = Contribution.objects.filter(faculty=self.kwargs['faculty_id'])
        serializer = ContributionSerializer(queryset, many=True)
        if not queryset:
            return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
        return Response(serializer.data)
#
#urls.py
router = DefaultRouter()
router.register(r'contributions/', ContributionViewSet)

urlpatterns = [
    path('', include(router.urls)),
]

urlpatterns = format_suffix_patterns(urlpatterns)
#

this is my code

native tide
opal portal
#

oh

#

it should be methods instead of method

#

but now it raised new error

#

wrong regex at the url_path param

native tide
# native tide settings.py

@native tide that looks right. just to be sure you also added the static url in the urls.py? and pls show the dev tool console and network tab

native tide
native tide
opal portal
#

@native tide what do you means ?

#

by-faculty is not defined

maiden tulip
opal portal
#

@native tide this is the error

native tide
opal portal
#

oh no problem. appreciate your help

native tide
maiden tulip
#

@native tide no, to check if email is empty, you use required="true"

native tide
native tide
maiden tulip
#

question is basically: if the browser by standard already checks if it is a valid email, what is the upside of having an additional pattern?
Validation is done on Backend again of course

wheat skiff
native tide
maiden tulip
#

Basically: Do we trust the users brower on their email pattern matching

native tide
native tide
wheat skiff
native tide
#

@wheat skiff sure

native tide
# wheat skiff Can you send pls easy and good toutorials?

@wheat skiff for django-channels there are some old but still viable tutorials bc its didnt change that much mby the syntax a little bit.
A whole playlist. He explains it kinda fast so you goota have some knowledge atleast the basics.
https://www.youtube.com/watch?v=Wv5jlmJs2sU&list=PLLRM7ROnmA9EnQmnfTgUzCfzbbnc-oEbZ
I did skip through this and its almost identical to the first of the other series but slower
https://www.youtube.com/watch?v=wLwu1NqU1rE
and for socket.io another solution for an chat app
https://www.youtube.com/watch?v=ig1nqsKBydw
Hes gonna do a tutorial series about it if you can still wait some days

distant trout
#

is it bad that i prefer class based react components over functions?

native tide
# distant trout is it bad that i prefer class based react components over functions?

i personally think its never bad to prefer smth over another but u should atleast also know it if you are asked to use them
For example i personally prefer cbv(class-based-views) in django bc there are faster and easier to write and give you prebuild stuff but in react i think only the syntax changes if im not mistaking. (sry i dont rlly use react)

distant trout
native tide
#

yeah i dont rlly use react but when i did i didnt rlly saw the difference between those other than the syntax and mby the length of the code. its always good to know an alternative or extension to ur already existing knowledge

nimble epoch
distant trout
nimble epoch
#

true

shadow grove
#

Anyone here know anything about or have any experience with Fast API

#

Thinking about using it for an upcoming project, the automatic doc generation is probably the greatest appeal for me thus far

native tide
#

Python is only used for backend. Frontend is all html/css DerpPanda

#

And tbh it's fairly easy

buoyant shuttle
#

ive been meaning to ask, how to i immitate typing effect on my website

glad patrol
#

can any1 know how to fix it

lavish prismBOT
#

:incoming_envelope: :ok_hand: applied mute to @native tide until 2021-04-19 16:40 (9 minutes and 59 seconds) (reason: burst rule: sent 8 messages in 10s).

jagged lark
#

Please don't spam our channels, thanks

random lava
#

Hi, sorry in advance if this is the wrong channel however,
im trying to make a simple request with a username:pass@host:port proxy and getting errors.

import requests
import random
proxylist = []

url = "https://www.google.com/"

with open("proxies.txt", "r") as f:
    for line in f:
        line = line.replace("\n", "")
        tmp = line.split(":")
        proxies = {
            "http" : "http://" + tmp[2] + ":" + tmp[3] + "@" + tmp[0] + ":" + tmp[1], 
            "https" : "https://" + tmp[2] + ":" + tmp[3] + "@" + tmp[0] + ":" + tmp[1]
        }

        proxylist.append(proxies)

print(proxylist)


for proxy in proxylist:
    session = requests.Session()
    r = session.get(url, verify=False, proxies=proxy, headers={'User-Agent': 'Chrome'})
    print(r.status_code)
    print(r.json()["ip"])

Error:

Exception has occurred: ProxyError
HTTPSConnectionPool(host='www.google.com', port=443): Max retries exceeded with url: / (Caused by ProxyError('Cannot connect to proxy.', FileNotFoundError(2, 'No such file or directory')))
leaden carbon
#

hey i need some help with dash and plotly, my intention is to put a local image into the website but not know how
my initial idea whas this

import dash_html_components as html

app.layout = html.Div(children=[
    html.H1(myheading),
    html.Img(src=variableWithPath)
    ])
#

the html.H1(myheading) works fine, rendering a title in the site but the html.img dont

#

so, how can i import local image into my dash aplication?

native tide
#

Hello guys

#

Anyone have an idea of how I can bypass cloudflare with selenium

#

It keeps loading and i cant get to the site :(\

opaque rivet
#

and that also means you can write your own hooks and have whole functions as one liners in your component (without the need for a constructor)

distant trout
opaque rivet
#

yeah, you can use both - if you're new to React then it's taught as class components first. Over time you'll just transition to functional components.

#

and on that note if you continue to learn react, also learn redux and framer motion for animations 🙂 and take a look at some component libraries, chakra UI is the most popular and antd is awesome. speeds up design a lot.

distant trout
opaque rivet
distant trout
#

awesome, thanks 😄

mortal mango
#
                    <form action="/settings?guild={{ guild_id }}" method="get">
                        <label for="prefix">Prefix: </label>
                        <input id="prefix" type="text" name="prefix">
                        <input type="submit" value="OK">
                    </form>
```I have this form but the form redirects to settings?prefix=prefix_here. Is there a way to make it redirect to settings?prefix=prefix_here&guild=guild_id_here?
opaque rivet
mortal mango
opaque rivet
mortal mango
opaque rivet
#

🙂

mortal mango
#

if request.method == 'get': I have this if statement in my view but it's returning false. Do you know why?

#

the form is get

opaque rivet
#

anybody used spring boot? or unrelated to that, any packages which auto-generate api docs? (or would it be preferred to write your own api docs)?

opaque rivet
mortal mango
#

it bypasses the if statement if request.method == 'get':

opaque rivet
#

could you show code? could you print request.GET to see if you're actually making requests to that endpoint?

mortal mango
#

k

#

<QueryDict: {'prefix': ['exo.'], 'guild': ['705619297342455888']}>

opaque rivet
mortal mango
#

oh it worked

#

thanks!

opal portal
#
class Contribution(models.Model):
    author = models.ForeignKey(Info, 
                               on_delete=models.CASCADE, 
                               related_name='contributions')
    title = models.CharField(max_length=255)
    description = models.TextField()
    faculty = models.ForeignKey(Faculty,
                                on_delete=models.CASCADE,
                                related_name='contributions')
    slug = models.SlugField(max_length=255,unique_for_date='approval_date') 
    file = models.FileField(upload_to=get_path,
                            validators=[FileValidator(allowed_extensions=['doc', 'docx', 'pdf', 'png', 'jpg', 'jpeg'],
                                                      max_size=20*1024*2014)])
    approval_date = models.DateTimeField(default=None, blank=True, null=True)
    submission_date = models.DateTimeField(auto_now_add=True)
    update_date = models.DateTimeField(auto_now=True)
    status = models.CharField(max_length=10, 
                              choices=STATUS, 
                              default='pending')

So i have a model like this, when create a new instance, i only want user to be able to fill in title, description and file. update/submission date will automatically add when an instance is created/modified. author and faculty information will be retrieve from the current logged in user. so how can i make a serializer for that ? or may be multiple serializers ?

glacial orchid
#

Hello everyone,
I am so glad to be in this community where everyone is a passionate learners..!
Today I have made a small project with HTML5 SCSS and Vanilla JavaScript.
I just wish if you could see my work and give feedback, I would be very delighted..!
Live Project -> https://roctanweer.github.io/bookmark/
source code -> https://github.com/RocTanweer/bookmark
If you like this , a 🌟 at GitHub will be very much appreciated..!
Thank You in advance..!

mystic wyvern
#

Hi everyone, what is the point of use json or xml when we use api ?

#

why we aren't send the data directly without use json ??

sonic pivot
#

Is anyone able to help me with making a Chat bot Window on a website, using JS, HTML and CSS as I am not too familar with them

#

And how I would then embed my bot code that is already written into the chat window

viscid valley
#

@sonic pivot and @opal portal I'll help both of you here.

opal portal
#

thank you. i tried 2 serializer like this

class ContributionSerializer(serializers.HyperlinkedModelSerializer):
    file = serializers.FileField(max_length=None, allow_empty_file=False, required=True)
    submission_date = serializers.DateTimeField(format="%d-%m-%Y")
    approval_date = serializers.DateTimeField(format="%d-%m-%Y")
    update_date = serializers.DateTimeField(format="%d-%m-%Y")

    class Meta:
        model = Contribution
        fields = '__all__'
        

class ContributionCreateSerializer(serializers.HyperlinkedModelSerializer):
    file = serializers.FileField(max_length=None, allow_empty_file=False, required=True)

    class Meta:
        model = Contribution
        fields = ['title', 'description', 'file']
viscid valley
opal portal
#

i'm not sure what method i want to override since i dont fully understand them

#

serializer save is to save the instance into database ?

viscid valley
#

You're trying to update multiple models and such during the save of one model?

opal portal
#
class Contribution(models.Model):
    author = models.ForeignKey(Info, 
                               on_delete=models.CASCADE, 
                               related_name='contributions')
    title = models.CharField(max_length=255)
    description = models.TextField()
    faculty = models.ForeignKey(Faculty,
                                on_delete=models.CASCADE,
                                related_name='contributions')
    slug = models.SlugField(max_length=255,unique_for_date='approval_date') 
    file = models.FileField(upload_to=get_path,
                            validators=[FileValidator(allowed_extensions=['doc', 'docx', 'pdf', 'png', 'jpg', 'jpeg'],
                                                      max_size=20*1024*2014)])
    approval_date = models.DateTimeField(default=None, blank=True, null=True)
    submission_date = models.DateTimeField(auto_now_add=True)
    update_date = models.DateTimeField(auto_now=True)
    status = models.CharField(max_length=10, 
                              choices=STATUS, 
                              default='pending')

So i have a model like this, when create a new instance, i only want user to be able to fill in title, description and file. update/submission date will automatically add when an instance is created/modified. author and faculty information will be retrieve from the current logged in user. so how can i make a serializer for that ? or may be multiple serializers ?

viscid valley
#

Yes, you would override the save method and do all of this.

#

Then use super... save the model.

opal portal
#

in views.py i do this

class ContributionViewSet(viewsets.ModelViewSet):
    queryset = Contribution.objects.all()
    serializer_class = ContributionSerializer
    permission_classes = [permissions.IsAuthenticatedOrReadOnly]
    

    def create(self, request, *args, **kwargs):
        serializer = ContributionCreateSerializer(data=request.data)
        current_info = self.request.user.info
        serializer.is_valid(raise_exception=True)
        serializer.save(author=current_info, faculty=current_info.faculty)
        recipient = Info.objects.get(faculty_id=serializer.validated_data.get('faculty_id'), role_id=2)
        recipient_email = recipient.email
        send_mail(
            'New Contribution Notification',
            'A new contribution has been submitted within your faculty.\nPlease review within 14 days.',
            'no-reply@example.com',
            recipient_email, # coordinator emails here
            fail_silently=False,
        )
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
#

it get so clumpsy and messy

viscid valley
#
        if getattr(self, '_image_changed', True):
            small=rescale_image(self.image,width=100,height=100)
            self.image_small=SimpleUploadedFile(name,small_pic)
        super(Model, self).save(*args, **kwargs)```
opal portal
viscid valley
#

That's an example of overriding save method for a model.

opal portal
#

like this, i only want to show the title/description and file

viscid valley
#

You def save, do your logic then use super(ModelName, self).save(*args, **kwargs)

#

Oh set editable to false.

#

In the model.

opal portal
#

model or serializer ?

viscid valley
#

editable=False for the field.

#

DRF should hide it.

opal portal
#

things is more complicated than just hiding. let me explain from the beginning

viscid valley
#

Or take it out of fields in DRF view

#

Well there's a lot of things, so one thing at a time.

#

You want to hide those fields in the API?

#

Can you show me the view for it.

#

Got it

#

Where's the view for it?

opal portal
#

oh, cant paste the code

#
class ContributionViewSet(viewsets.ModelViewSet):
    queryset = Contribution.objects.all()
    serializer_class = ContributionSerializer
    permission_classes = [permissions.IsAuthenticatedOrReadOnly]
    

    def create(self, request, *args, **kwargs):
        serializer = ContributionCreateSerializer(data=request.data)
        current_info = self.request.user.info
        serializer.is_valid(raise_exception=True)
        serializer.save(author=current_info, faculty=current_info.faculty)
        recipient = Info.objects.get(faculty_id=serializer.validated_data.get('faculty_id'), role_id=2)
        recipient_email = recipient.email
        send_mail(
            'New Contribution Notification',
            'A new contribution has been submitted within your faculty.\nPlease review within 14 days.',
            'no-reply@example.com',
            recipient_email, # coordinator emails here
            fail_silently=False,
        )
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
#

this is what i have for now

humble oar
#

ok

opal portal
#

so i am trying to build an cms system that allow user to upload file and staff can set the status (pending/approved/denied), and the staff will receive mail noti whenever a new contribution is uploaded

#

yeah so messy

opal portal
#

well yeah, basically

humble oar
#

what's problem.

viscid valley
#

Ok, if you want to limit fields

opal portal
#

the uploading and mail noti not work as expectation

humble oar
#

I just start to learn python

viscid valley
#

We need to do that in def get_queryset(self):

opal portal
#

i want to limit fields when creating new instance through api, but when retrieve list of instances there will be all

humble oar
#

are using Django?

opal portal
#

yeah, Django and DRF

humble oar
#

ok

viscid valley
#

Can I see your serializers.ModelSerializer?

humble oar
#

have to tried Stack overflow ?

opal portal
#

from rest_framework import serializers
from .models import Contribution



class ContributionSerializer(serializers.HyperlinkedModelSerializer):
    file = serializers.FileField(max_length=None, allow_empty_file=False, required=True)
    submission_date = serializers.DateTimeField(format="%d-%m-%Y")
    approval_date = serializers.DateTimeField(format="%d-%m-%Y")
    update_date = serializers.DateTimeField(format="%d-%m-%Y")

    class Meta:
        model = Contribution
        fields = '__all__'
        

class ContributionCreateSerializer(serializers.HyperlinkedModelSerializer):
    file = serializers.FileField(max_length=None, allow_empty_file=False, required=True)

    class Meta:
        model = Contribution
        fields = ['title', 'description', 'file']

i tried this

viscid valley
#

Ok see fields?

#

fields = '__all__'

#

You want to limit that correct?

opal portal
#

yeah, that's for when retrieving a list of instances

#

like when method = post there will only be 3 fields but when method = get, i want all fields

#

also the uploaded file got renamed into something and lost the file extension

#

im not sure why is that but i guess because of the file validators

viscid valley
#

Ok, so you want to rename files upon upload?

opal portal
#

no

viscid valley
#

Files are losing their extension?

opal portal
#

like this

viscid valley
#

Ok, so one problem at a time.

opal portal
#

but let put that aside

#

yeah

viscid valley
#

I'm totally confused too.

#

Lets start from the top.

#

When users get a specific viewset you want information pre-populated?

opal portal
#

yeah something like that

#

do you want to teamviewer and have a look at my code ?

viscid valley
#

Here is fine.

#

So are you trying to populate a form?

opal portal
#

no form, just directly through api

viscid valley
#

That's not really the job of DRF.

#

Ok, so default value.

#

That can be handled in the create method.

#

The requests object has user information

#

You can use to query other models.

opal portal
#

so now we ovveride the create method of serializer ?

#

?

viscid valley
#

You can query/update/save other models.

opal portal
#

if my user have a foreign key like this fk1= models.ForeignKey(FK1), and FK1 have a fields, say fieldA. can i get the value of fieldA by request.user.fk1.fieldA ?

viscid valley
#

Assuming that's the foreign keys field name

opal portal
#

erm i dont want to get user id, so each user will is linked to a profile model which will have foreignkey. so how do i access the profile's foreignkey through user ?

#

or any fields of profile model ?

viscid valley
#

You want to query the profile model from request.user?

opal portal
#

yeah

viscid valley
#

Do dir(request.user)

#

Show me the profile model.

viscid valley
opal portal
#
class Info(models.Model):
    name = models.CharField(max_length=100)
    address = models.CharField(max_length=100)
    dob = models.DateField(auto_now=False, auto_now_add=False, blank=True)
    phone = models.CharField(max_length=11)
    email = models.EmailField(max_length=100)
    role = models.ForeignKey(Role, on_delete=models.CASCADE)
    faculty = models.ForeignKey(Faculty, on_delete=models.CASCADE, null=True)
    pass

    def __str__(self):
        return self.name
viscid valley
#

How do your user model point to this?

opal portal
#

you see, my contribution model also have a faculty foreignkey

viscid valley
#

Are you using djangos auth user?

opal portal
#

erm, a custom user model

viscid valley
#

Ok, paste it

opal portal
#
from django.db import models
from django.contrib.auth.models import AbstractUser
from ..info.models import Info


class User(AbstractUser):
    # username = models.CharField(max_length=50, unique=True, default='Anonymous')
    # password = models.CharField(max_length=100)
    # reference key to info
    info = models.ForeignKey(Info, on_delete=models.CASCADE, blank=True, null=True)

    REQUIRED_FIELDS = []
    # # session_token file t store token, default = 0 means it haven't already login
    # session_token = models.CharField(max_length=10, default=0)

this part is not mine, my friend did it, so im not very sure

#

all he did is just adding a foreignkey

viscid valley
#

Ok, so what field are you trying to update first in create method from request.user information?

#

In your settings.py is AUTH_USER_MODEL set to something?

opal portal
#

user.User

#

it is set to the model above

viscid valley
#

OK

#

So does request object have User?

opal portal
#

yes

viscid valley
#

OK, do dir(request.User)

opal portal
#

can you elaborate ?

viscid valley
#

Are you familiar with setting breakpoints?

#

If not, this will be life changing.

opal portal
#

not at all

viscid valley
#

Oh man, you've been flying blind.

opal portal
viscid valley
#

pip install ipdb

astral pagoda
#

Is this channel free to ask questions

viscid valley
#

@astral pagoda It is.

#

@opal portal Grab one of the help channels actually, this may be a while.

#

Mention me in it.

opal portal
#

kay

viscid valley
#

@astral pagoda What's your question?

astral pagoda
#

This is my file flaskblog.py
https://paste.pythondiscord.com/mumihugeyo.py
This is my file register.html
https://paste.pythondiscord.com/iqodogezeb.xml
This is my file forms.py
https://paste.pythondiscord.com/foqosihupo.py
I am trying to get the information from my register page but when I click submit nothing happens Can someone help? All the code compiles. I am using wtf forms and flask. Thanks for the help.
I am don't have github yet
I am new to coding
This is what the register page looks like https://imgur.com/a/mtzYrkr
By information I just mean request.form['username'], which is equivalent to form.username.data in wtf forms

I asked it in the lemon help channel but didn't get a response. Should I stay in the lemon help channel?

viscid valley
#

In your browsers inspect tab

astral pagoda
#

K thanks. I also screwed up and posted in an occupied channel. It won't happen again.

viscid valley
#

under network..

#

When you hit register.

#

Does it post to /register?

#

If so what's the response code and response?

#

Wait, looks like your submit button is messed up dude.

#
<input type="button"  Submit value="register" >```
#

Replace with <input type="submit" value="Submit">

astral pagoda
#

k let me test it.

viscid valley
#

Sure

astral pagoda
#

I think it works. Thank you very much. Now I get an error name 'bcrypt' is not defined. But I can just google it.

#

Just imports need fixing

viscid valley
#

@astral pagoda pip install Bcrypt-Flask

#

You're very welcome.

lavish prismBOT
#

@open tinsel :white_check_mark: Your eval job has completed with return code 0.

001 | [[['M', 10.652444444444445, 278.0], ['C', 10.652444444444445, 278.0, 17.500444444444447, 278.0, 22.06577777777778, 278.0], ['C', 31.500799999999998, 278.0, 36.218311111111106, 278.0, 45.65333333333333, 278.0], ['C', 54.78399999999999, 278.0, 59.349333333333334, 278.0, 68.48, 278.0]], []] 
002 |  **
open tinsel
#

I need to remove the extra dimension at the end of the output above.

#

Looking for d_list = [] rather than d_list = [[],[]]

#

I'm not clear how to use BeautifulSoup find_all with children

real mirage
novel horizon
#

Hi does any one know how to incorporate flask web apps with using es6 module notation. When I am using module.export in the javascript i am getting "module is not defined".

inland oak
#

set FLASK_APP=name_of_your_start_file.py

#

For windows

#

In Linux replace, set to export

distant trout
#

for react project structures, is this okay?

#

grouping folders with features and having css/scss files inside them

astral pagoda
#

https://paste.pythondiscord.com/egiguvawur.py
Flask dividing files question

In the link above I have some code in a file called flaskblog. What is it called when I want to divide the file above into a new folder called flaskblog? The different parts I would divide the file into would be the databases in models.py and the routes in routes.py etc. I also have a seperate file for the wtf forms inside the flaskblog folder.

#

Also is anyone free. I don't want to interrupt

#

Nevermind I found the answer

ionic coral
#

who is using flask for python web development

lavish prismBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

glad patrol
#

can someone help me regarding this I got this error on all crud operations in .net

glad patrol
native tide
#

@fair shale if you use virtual environments, have you activated it?

opal portal
#

my get_path doesnot work as i intended
instead of storing files into media_root/images/ or documents/ , it saves file as something like this media_root/images_xxcvbdfger
the original file name turned in to xxcvbdfger and the file extension is lost
does any one know why and how to fix it ?

#
class Contribution(models.Model):
    IMAGE_EXTENSION = ('.jpg', '.jpeg', '.png')
    DOCUMENT_EXTENSION = ('.doc', '.docx', '.pdf')
    STATUS = (
        ('pending', 'Pending'),
        ('approved', 'Approved'),
        ('denied', 'Denied'),
    )

    def get_path(instance, filename):
        file_ext = os.path.splitext(filename)[1]
        if file_ext in Contribution.IMAGE_EXTENSION:
            file_path = "images/"
        if file_ext in Contribution.DOCUMENT_EXTENSION:
            file_path = "documents/"
        return file_path

    author = models.ForeignKey(Info, 
                               on_delete=models.CASCADE, 
                               related_name='contributions')
    title = models.CharField(max_length=255)
    description = models.TextField()
    faculty = models.ForeignKey(Faculty,
                                on_delete=models.CASCADE,
                                related_name='contributions')
    slug = models.SlugField(max_length=255,unique_for_date='approval_date') 
    file = models.FileField(upload_to=get_path)
                            #validators=[FileTypeValidator(IMAGE_EXTENSION + DOCUMc=ENT_EXTENSION)])
    approval_date = models.DateTimeField(default=None, blank=True, null=True)
    submission_date = models.DateTimeField(auto_now_add=True)
    update_date = models.DateTimeField(auto_now=True)
    status = models.CharField(max_length=10, 
                              choices=STATUS, 
                              default='pending')
versed python
opal portal
#

oh yeah i tried and it still doest work as intended

#

i tried return os.path.join(file_path, filename) and it worked

shell heath
#

j

#

how do i remove line underneath header

#

it pops uo when scaling in inspectj

native tide
minor horizon
#

Hello. I using ngrok to serve my api. When an api function takes more than 5 mins, it returns a 504 error but the request keeps running in the background. I couldn't find how to set a longer timeout to ngrok. Any ideas?

tulip beacon
#

hey guys, I want someone who is good at react to help me in a startup project..if you are good at react, willing to work with me, please do dm me...🙂

glad patrol
#

Is this error mean that the store procedure doesn't exist?

#

@sturdy sapphire sorry to ping you here

#

can you elaborate this

marble spade
#

Hello! Does anyone know how to fix this in CSS

#

the overlapping

glad patrol
#

Msg 8101, Level 16, State 1, Procedure Tri_IUD_Users_HEC_Officers_Uni_tbl, Line 5 [Batch Start Line 7] An explicit value for the identity column in table 'HEC.dbo.Users_HEC_Officers_Uni' can only be specified when a column list is used and IDENTITY_INSERT is ON.

#

can someone know how to fix this

native tide
#

How do I webscrap this

#

they have the same class

tulip beacon
#

hey guys, I want someone who is good at react to help me in a startup project..if you are good at react, willing to work with me, please do dm me...🙂

native tide
#

@fair shale if it wasn't activated then that could have been a reason. How did you transfer the virtual env to your new machine?

#

Ah OK, so you didn't do anything like pip freeze requirements.txt?

fickle forum
fickle forum
#

🙂

keen ravine
#

Hey guys!

#

How can I check if element exists in a web page using selenium

wheat skiff
#

hi, i really need help with building a chat app in django. i built already the site now i need to make the chat with socket or django channels. can some one help me with it?
im very new to django so it is very difficult for me to do this app
(i tried lots of tutorials but its hard for me to understand when i cant ask questions)

fickle forum
# keen ravine Hey guys!

def get_element(self, by, selector, check_exists=False):
try:
if by == "xpath":
element = self.driver.find_element_by_xpath(selector)
elif by == "id":
element = self.driver.find_element_by_id(selector)
elif by == "partial_link_text":
element = self.driver.find_element_by_partial_link_text(selector)
else:
raise Exception("Unknown search operator")
except NoSuchElementException as e:
if check_exists:
return None
else:
raise e

    return element
wheat skiff
fickle forum
#

It must be easy 🙂

#

you can use django-channels/rabbitmq together

native tide
#

if a website have 3 same iframes ! ,then how can we automate them ? using selenium?

blazing sandal
arctic chasm
#

has anyone here ever used tweepy for any twitter related projects? I'm thinking i might try and make a twitter bot for my final exam project but idk much about the module and its capabilities

native tide
random lava
#

Hi, sorry in advance if this is the wrong channel however,
im trying to make a simple request with a username:pass@host:port proxy and getting errors.

import requests
import random
proxylist = []

url = "https://www.google.com/"

with open("proxies.txt", "r") as f:
    for line in f:
        line = line.replace("\n", "")
        tmp = line.split(":")
        proxies = {
            "http" : "http://" + tmp[2] + ":" + tmp[3] + "@" + tmp[0] + ":" + tmp[1], 
            "https" : "https://" + tmp[2] + ":" + tmp[3] + "@" + tmp[0] + ":" + tmp[1]
        }

        proxylist.append(proxies)

print(proxylist)


for proxy in proxylist:
    session = requests.Session()
    r = session.get(url, verify=False, proxies=proxy, headers={'User-Agent': 'Chrome'})
    print(r.status_code)
    print(r.json()["ip"])

Error:

Exception has occurred: ProxyError
HTTPSConnectionPool(host='www.google.com', port=443): Max retries exceeded with url: / (Caused by ProxyError('Cannot connect to proxy.', FileNotFoundError(2, 'No such file or directory')))

The proxies print out so it has to be an issue with requests or the proxies.
Ive also tested the proxies with a proxy tester and they are alive.

opaque rivet
#

@wheat skiff django channels is the way to achieve that

fickle forum
#

🙂

keen ravine
#

Guys I have a simple question

fickle forum
#

You welcome

#

Sure please shoot

keen ravine
#

Why this while loop don't work?

#

arr = ['0','1','2','3','4'] count = 0 while True: count+=1 print(arr(count))

fickle forum
#

arr is an array

keen ravine
#

yeah

fickle forum
#

arry[count]

#

not arr(acount)

keen ravine
#

True

#

Thanks again

fickle forum
#

🙂

native tide
#

Can i do a live terminal webpage?

mortal mango
#

query = db.execute(f"update prefix set prefix_name = {prefix} where guild_id = {guild_id}")

syntax error at or near "guild_id" LINE 1: update prefix set prefix_name = a. where guild_id = 70561929...

I'm getting this error from django, but I'm not sure why. I've tried converting guild_id to an int and stuff. But the error still pops up. Does anyone know why?

noble spoke
#

Dont use fstrings for sql queries

#

Use the api the module offers

warm fossil
#

so i made a front end for my website and I am trying to add a flask back end however only some of the css and images are loading. I have added my css and images into the static folder outside the templates folder however only some images are loading

For example

As you can see the top image loads however the background image does not load

#

I blocked out some sensitive information

quiet garden
#

Uh hey

jovial mist
#

How can I store sensitive information on a client's computer?

mortal mango
#

query = db.execute("update prefix set prefix_name = %s where guild_id = %s", (prefix, guild_id))

#

this is my code but it doesn't update the record in the database and doesn't return an error

#

do you know why?

jovial mist
#

You might want to surround the first %s with quotes

mortal mango
#

only the first?

jovial mist
#

I think so

mortal mango
#

k let me try it

opaque rivet
mortal mango
opaque rivet
# jovial mist please help

you can store information in cookies, it shouldn't be anything highly sensitive (e.g. username / password)

#

does anyone know the most popular backend framework?

jovial mist
opaque rivet
jovial mist
opaque rivet
jovial mist
#

Wouldn't that token be as sensitive as the username and password because it allows access to the user's account?

#

Sorry I'm kinda new to web development

opaque rivet
# jovial mist Wouldn't that token be as sensitive as the username and password because it allo...

Yes. Cookies can be stolen, e.g. by XSS (I don't really know much about security):
https://medium.com/@laur.telliskivi/pentesting-basics-cookie-grabber-xss-8b672e4738b2

However your server will also have CORS which restricts requests to your server made from other origins. (requests not made from your webpage). If the attacker stole your username/password cookies, they can simply log into your account and make any request they want, from the same origin.

Medium

In 2017, injection (attack) was identified by OWASP as the most serious web application security risk for a broad array of organizations…

mortal mango
#

query = db.execute("update prefix set prefix_name = %s where guild_id = %s", (prefix, guild_id))
This code isn't updating the record in the database. Django or psycopg2 isn't returning an error either. Does anyone know why?

jovial mist
#

Did you run db.commit()?

#

Also I think that update and set should be capitalized so that it looks more readable

mortal mango
#
query = db.execute("UPDATE prefix SET prefix_name = %s WHERE guild_id = %s", (prefix, guild_id))
db.commit()
jovial mist
mortal mango
#

db.commit() AttributeError: 'psycopg2.extensions.cursor' object has no attribute 'commit'

#

oh ok

mortal mango
jovial mist
#

How do I prevent CORS on my Flask server?

humble oar
#

Getting this, how to solve this?

jovial mist
humble oar
formal gull
#

when using react and django together, are you basically running 2 different servers essentially?

dull coral
distant trout
#

is express nescessary when using nextjs?

humble oar
dull coral
#

Does the ports work properly?

#

If it does, it might be the username and password

humble oar
humble oar
dull coral
#

I think the user of MySQL should be the root

opaque rivet
misty tulip
#

this the correct channel for talk about html

dull coral
#

Hmm I am not sure 😅

humble oar
dull coral
#

You are welcome!

opaque rivet
distant trout
#

also does anyone know if there is a way for me to just type in a component name and it being like this <Component /> instead of <Component></Component>

#

using vscode

misty dune
#

Hi, maybe this is a stupid question, but why would you use flask over something like express? I have used both and I can't really find any good answers for either one

delicate nest
#

idk cuz express is javascript

misty dune
#

well yeah true, but if one was "better" than the other or had some major feature/reason to use it then I would be more than willing to use either

delicate nest
#

just use whatever u want

#

lol use scratch if u wanted supatrol

delicate nest
misty dune
#

I'd honestly say it's about equal

delicate nest
#

use sanic

#

ez to use and it's not js

#

and its decently fast

misty dune
#

I mean

#

don't get me wrong I love flask

#

I use it all the time

#

I just keep seeing people use express

#

and it makes me wonder why they would chooose that over flask

delicate nest
#

cuz it works better for them

opaque rivet
opaque rivet
misty dune
#

got it @opaque rivet

#

is there any other benefit?

#

and I also have been looking into react and using it with flask

#

and it is really confusing me

#

if I use react with flask is the whole routing part of Flask obsolete?

#

I was watching miguel grinberg show a flask api with express where there was no more routing anymore and apparently a python server is not the best option, so is it even worth using python with react?

#

I guess I also just don't really get the point of react in genearl

#

sorry for the rambling, I'm just really confused

serene prawn
opaque rivet
# misty dune I was watching miguel grinberg show a flask api with express where there was no ...

React is an SPA. (single page application) How that works is you have a barebones HTML file, and the React JS content is hydrated onto the page. That means you only need to render one HTML page for the entire react app (e.g. you visit the root url /, it will render this page (rendering your whole React app)).

You will often do client side routing inside of server side routing, as now everything is client-side rendered (this is bad for SEO by the way).

serene prawn
#

So your backend app should provide it 😉

opaque rivet
#

I have been wanting to learn node.js and express for a long time, it's simple like flask, but I don't want to leave django 😦

misty dune
#

but I mean with my flask app i would be rendering the templates anymore

opaque rivet
#

nope

misty dune
#

or passing variables to my templates and stuff

#

so all I would do is return 1 empty page?

opaque rivet
#

well, you return one single page and the rest is done on the client-side

#

then your flask backend just serves as an API

misty dune
#

yeah so just api

opaque rivet
#

you can also sprinkle react is templates but i've never tried

misty dune
#

hmmm

serene prawn
#

Kinda like flask

misty dune
#

i think its easier tbh

#

so again maybe dumb question, but could i have multiple single page applications in react

#

and what would be flask's role in "routing" or whatever those pages

serene prawn
#

I think flask is obsolete now because of fastapi

#

And for js you can use something like nestjs

opaque rivet
misty dune
#

thats crazy to me

opaque rivet
#

you render your React app once, then that is your application.

misty dune
#

so you learn flask

#

a lot of stuff

#

then switch to react

opaque rivet
#

specifically the routing is done with React-Router

misty dune
#

and then you only use flask as an api server

serene prawn
opaque rivet
#

pretty much 😄 just like any backend framework, really

serene prawn
#

I wouldn't write any app that might have more that 50 lines of js code without some kind of framework

opaque rivet
#

I think I'm gonna move to node.js but I have no real reason behind it except that it's more popular

#

I learnt django for so long just to drop it... I am at a crossroad

serene prawn
#

So moving to node just to move? 😅

opaque rivet
#

For me its just because of popularity / employability

serene prawn
#

I like django but fastapi does things so much better 🤔 but sadly it misses some features

opaque rivet
#

Actually I think what I'll do is just learn node.js basics and stick with my stack, and probably try out fastapi

#

fastapi would be more like flask right? barebones?

serene prawn
#

@opaque rivet Not really, it's flask on steroids 🙂

native tide
#

hello, i'm making a web app in python, i'm a beginner in this language though (and in programming in general). I was wondering, what exactly this does : py app = Flask(__name__)

serene prawn
#

Creates an instance of Flask

#

Or you're wondering what __name__ does?

native tide
#

i'm wondering what __name__ does

serene prawn
#

name should be name of a current file

#

Or it would be __main__ if ran directly

#

Within a module, the module’s name (as a string) is available as the value of the global variable __name__.
Module = File

native tide
#

ok thx, i have another question

serene prawn
#

You either have to define schema by hand or write custom input/output serializers for each view

opaque rivet
#

openAPI is the thing used to write api docs right?

serene prawn
#

Yep

native tide
#

what is @spare ridge.route('/') ? and more generally, why some functions have this @instance.xxx() before their def ?

serene prawn
#

FastAPI would require more complex setup but it allows for more freedom i think

#

it's a decorator

#

@

#

Basically what @app.route does is registering route inside of your flask app

#

So if you access your flask from say browser it will return "Hello World"

#

Assuming you requested the root page

serene prawn
native tide
#

I get this after paste-ing the local address of my web app in my browser

#

this is my code (ignore the comments)

#

this is the error

#

what could be the problem ?

serene prawn
#

@native tide Share the actual error

native tide
#

do you want all the traceback ?

serene prawn
#

Sure

native tide
serene prawn
#

Template not found 🙂

#

flask is trying to find them in templates directory by default

#

So create one and put your template in it

native tide
#

i thought i did, let me see

#

ok

#

my app.py file was in a directory

#

and my html file in templates

#

it worked when i moved app.py in a directory "higher" than templates

#

how can I make it work while keeping app.py in an "equally high" directory ?

#

i can make a quick diagram to be clearer

serene prawn
#

you can pass templates_folder argument when creating flask instance

native tide
#

thanks for your help

serene prawn
#

np

#

Did you figure out what to pass as a parameter?

native tide
#

let me read the doc 🙂

serene prawn
#

try "../templates"

#

If that wouldn't work then it needs an absolute path

#

so you can try

from pathlib import Path
Path("../templates").absolute()
native tide
#

ok it works

#

thanks !

misty tulip
#

is anyone familiar with cpanel?

regal raven
#

yeah from like 15 years ago

jovial mist
#

How do I use CORS?

#

I put this header on my response, but it does nothing

marble spade
#

Anyone know how to fix this in CSS:

inland oak
jovial mist
#

Thanks!

native tide
#

<img src="Denis_Villeneuve_Cannes_2018" />
is this the wrong way of using image tag?

green snow
#

its is correct

#

but put file extension .png/.jpg

native tide
oak sky
#

just wondering if there is a way to "fake" a 404 error with flask

#

i have a /<module> url and if the module doesn't exist, i want to return a 404 error

#

does that make sense?

native tide
#

@native tide @green snow thanks there.

oak sky
native tide
oak sky
#

ok

native tide
# oak sky ok

i just read it and saw you dont need the answers, you need the question bc there it says you can call query.get_or_404 on everything

oak sky
#

i got it to work :)

#

with abort(404)

native tide
buoyant escarp
#

Hi guys, I'm creating a webapp using Flask and hosting it in the cloud. How would I properly log the application?

#

Do i create a log instance everytime somone accesses the index? so it can track their movements?

sleek crest
#

testing selenium stuff on my website:

    if driver.find_element_by_xpath('//*[@id="error"]'):
        driver.close()
    print('ok')
``` it doesnt print 'ok' even if there is no element
obtuse kite
rotund wagon
#

does anyone tried deploying their django app on heroku? I kinda need help rn thinkmon

sleek crest
native tide
#

hey

hollow cape
#

how do i make the webpage show in a side bar in vscode?

#

any1 knows?

native tide
#

did I do something wrong here?

native tide
native tide
# native tide

open the dev tool console and see if there are some css loading issues

rotund wagon
#

wait

potent lynx
#

Hi everyone. Let me ask about django-braces - is it still useful these days? The last update was 2019

native tide
opaque rivet
#

@jovial mist is that header in he response from your server?

native tide
#

Its because Debug = True

#

for some unknown reason it does that 😦

#

btw can someone help me fix this error (heroku)

native tide
# native tide

sry idk what varying is but it says the value is too long for that type. Can you show where you assigned that

sullen python
#

pls

#

i need help

native tide
# native tide I assigned it to the url

ok. idk if you know but you can also say URLField instead of CharField for an url. and just for understanding on my side. Why are you overriding the save method like that?

charred berry
#

are django-crontabs supported while deploying a website on heroku?

native tide
#

There is URL Field?

native tide
versed python
# native tide

This is probably because you are using sqlite database in local and postgresql in production

versed python
#

Sqlite doesn't enforce the max_length thing but postgresql does.

native tide
#

should I just delete this ?

versed python
native tide
#

when I pushed it to heroku

native tide
native tide
arctic sentinel
#

how to draw a web app architecture?

native tide
#

This is what I used : heroku addons:create heroku-postgresql:hobby-dev

terse vapor
golden reef
#

hey

#

i need some help with flask and heroku.

#

i am performing a web scraping operation with a flask web app , it runs fine locally but when i deploy it on heroku it throws internal server error.

#

logs:

#

2021-04-21T13:33:32.820285+00:00 heroku[web.1]: Idling
2021-04-21T13:33:32.822991+00:00 heroku[web.1]: State changed from up to down
2021-04-21T13:33:36.640970+00:00 heroku[web.1]: Stopping all processes with SIGTERM
2021-04-21T13:33:36.696362+00:00 app[web.1]: [2021-04-21 13:33:36 +0000] [8] [INFO] Worker exiting (pid: 8)
2021-04-21T13:33:36.696417+00:00 app[web.1]: [2021-04-21 13:33:36 +0000] [7] [INFO] Worker exiting (pid: 7)
2021-04-21T13:33:36.706230+00:00 app[web.1]: [2021-04-21 13:33:36 +0000] [4] [INFO] Handling signal: term
2021-04-21T13:33:36.713078+00:00 app[web.1]: [2021-04-21 13:33:36 +0000] [4] [WARNING] Worker with pid 8 was terminated due to signal 15
2021-04-21T13:33:36.713628+00:00 app[web.1]: [2021-04-21 13:33:36 +0000] [4] [WARNING] Worker with pid 7 was terminated due to signal 15
2021-04-21T13:33:36.808258+00:00 app[web.1]: [2021-04-21 13:33:36 +0000] [4] [INFO] Shutting down: Master
2021-04-21T13:33:36.921749+00:00 heroku[web.1]: Process exited with status 0

arctic sentinel
terse vapor
arctic sentinel
terse vapor
#

ya

#

or starUML

arctic sentinel
terse vapor
#

those are the app to draw diagram

arctic sentinel
terse vapor
arctic sentinel
terse vapor
#

no problem

native tide
#

Hi guys, i've a question

fickle forum
#

What's it?

#

I can ask 🙂

native tide
#

So I want to make a web app in Django, but i'm struggling with what Authantication and Authorization system I should use, can anyone point me in the right direction please? For authz I was thinking about JWT but not sure what I should use for authentication

fickle forum
#

are you using jwt authentication?

native tide
#

does JWT also authenticate? i thought that was for authorization only

terse vapor
#

or u can use like login required thing

native tide
#

I read something about djoser, which is kinda what I need

fickle forum
#

'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
'rest_framework.authentication.SessionAuthentication', # Required for Browsable API login
),

#

its for authentication

terse vapor
#

`from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
...`

native tide
#

okay that sounds good, thats build in right?

#

Also for email confirmation, password reset etc. etc. what do you recommend me to use?

fickle forum
#

It sounds like you are using backend and frontend separately

#

In this case, I don't use the built-in email confirm, password reset function

terse vapor
#

You can also use django auth to rest password

thin dome
#

these if statement are not working

#

but idk why?

native tide
#

API with JWT authorization, but should I handle the login, register as api aswell or

fickle forum
#

in this case, you don't have to use built-in password reset/email confirmation function

#

you should handle everything using API

native tide
#

doesn't make sense to me

fickle forum
#

built-in password reset/email confirmation is for django template

green snow
#

u need to put space

#

{% xyz %}

#

and not {%xyz%}

native tide
#

so to wrap it up, login / register should be done trough api calls aswell?

green snow
native tide
thin dome
native tide
#

np man

green snow
#

can anyone tell me how do i increase the size of the calendar

#

when i do with css only the box size increases not the drop down calendar

dawn citrus
#

Hey, is there any way to make subdomains with flask?

native tide
#

you usually do that trough the DNS no?

dawn citrus
native tide
#

there you go

thin dome
#

@native tide its not working 😐

native tide
thin dome
#

but its correct

native tide
dawn citrus
native tide
#

remove {% endif %} before {% elif %}

native tide
#

@thin dome is it working?

thin dome
native tide
thin dome
#

oh

thin dome
native tide
thin dome
#

but its not working too

native tide
thin dome
#

@native tide

native tide
# thin dome

ok and the view of that page pls bc it looks like your linter detects some errors

thin dome
#

@native tide

#

ohhhh fk

#

sorry

#

i m sooo dumb

#

@native tide thx for helping

#

i was seeing the home page while i was editing shop.html 😐 i m dumb sorry

#

lol

native tide
#

ok good that you fixed it but you should uninstall that linter u r using bc its bs or if you dont use a linter install one

thin dome
#

what is linter?

charred berry
#

is there a way to create a model in django whose instances automatically get deleted after some time from their creation?

inland oak
charred berry
#

celery doesn't work on windows ig

inland oak
#

But better start working in linux

#

It is better way anyway

charred berry
#

also if i deploy my site on heroku will it work there also or i will have to use their task scheduler?

inland oak
#

Not familiar enough with heroku

opaque rivet
#

i guess you can host on a VPS with nginx?

#

i have django channels celery redis in one and have no clue how to host it

charred berry
#

I am building a library system where there will be a waitlist for each book and as soon as a copy is available of the book the person on top of the waitlist will get it for 7 days and then it will automatically pass on to next person. So is there a way to do it without having to check if 7 days are over or not again and again?

opaque rivet
mortal mango
#

query = db.execute("select prefix_name from prefix where guild_id = %s", (guild_id))

TypeError: not all arguments converted during string formatting Django is giving me this error. Does anyone know what this means?

native tide
#

try

#
query = db.execute(f"select prefix_name from prefix where guild_id = {guild_id}")```
#

is guild_id a integer or a string btw

#

if it's a string try

#
query = db.execute(f"select prefix_name from prefix where guild_id = '{guild_id}'")
formal gull
#

im confused on when to use a REST API. i am trying to make basically a web UI that does a beautiful soup/requests get request. is this something that would use a REST API or it would not be needed because i am not storing my information?

manic frost
#

No no no no no @native tide, you shouldn't do that. That's prone to SQL injection.

#

@mortal mango (guild_id) is the same as guild_id. If you want a 1-element tuple, you should do (guild_id,).

dense slate
#

I'm interested in starting a new Django project and see that it now has been moving towards Async pretty heavily. I am hoping to also use React and GraphQL along with it (maybe Next also to optimize). Would it be good to use an ASGI server to later utilize the benefits of aysnc? Will I be able to generally build in a synchronous fashion as I'm used to and just pepper in async functions as I find it useful along the way?

native tide
#

always use prepare staments

#

😛

#

cc @formal gull

formal gull
native tide
#

was my bad

formal gull
#

wrong person 🙂

humble oar
#

Anyone suggest me best site to learn css?

scenic pendant
# charred berry I am building a library system where there will be a waitlist for each book and ...

If you are or can consider using an event loop, try using https://github.com/codemation/easyschedule

from datetime import datetime, timedelta
@scheduler.once(delta=timedelta(days=7))
async def foo():
    ## future work
    pass
#or
async def bar():
    ## more stuff
scheduler.once(delta=timedelta(days=7)(bar)

If not event loops to hook into, this can be pipe-lined using https://github.com/codemation/easyjobs

GitHub

Easily schedule single or recurring sync/async tasks - codemation/easyschedule

GitHub

A celery like jobs framework for managing and distributing async / non-async tasks - codemation/easyjobs

sleek crest
#

not sure wym by an else block tho

sleek crest
#

nvm i figured it out

find1 = driver.find_element_by_xpath('//*[@id="error"]')
    time.sleep(1.5)
    if find1==TRUE:
        ```
#

nvm now if it cant find the element

#

hmm

merry geyser
#

yo does django

#

works like jquery ?

inland oak
terse vapor
#

@app.route("/visit", methods=['POST', 'GET']) @login_required def visit(): amount_patient = Newpatient.query.first() from_date = datetime(year=datetime.now().year, month=datetime.now().month, day=datetime.now().day) current_month_expenses = Patient.query.filter_by(patient.id=patient_id).filter(Patient.create >= from_date).filter(Patient.create <= datetime.now()).all() return render_template('file.html', current_month_expenses=current_month_expenses)
I dont quite understand why this still has the error 'function' object has no attribute 'id'

native tide
#

hi

charred berry
grand shale
#

Can i use js vars in python with flask

#

Like i get an input from <input> and use the string in python?

tacit anvil
#

hi, im making a website and the css isnt working even though the items has the same class name
html

          <ul class="App-nav">
            <li class="Nav">Home</li>
            <li class="Nav">All Products</li>
            <li class="Nav">About me</li>
            <li class="Nav">Shopping Cart</li>
          </ul>

css

.App-nav {
  margin: 0;
  padding: 0;
  list-style-type: none;
}
.Nav {
  display: inline-block;
}```
sleek crest
#

who deleted their answer to my question?

#

i just got time to work on my code and now the help i needed is gone

thin dome
#

hey is this correct? html <a href="/"><h2 class="text-white title-font text-lg font-medium">{{dress.name}}</h2></a> {% a = dress.name %}

ionic coral
#

who is using flask to code site