#web-development
2 messages · Page 149 of 1
try it out
then i think i gotta change some of codes i got tired but yeah ill try it out thanks alot
so, what is your final code? what is your solution?
i changed my serializer
but wait... lol
why it doesnt save the picture
it deletes the picture but doesnt save the new pic
yes, but what did you do to the serializer? I know that you changed it, but in what way?
i didnt change the serializer
i mean i switched to AccountSerializer from UserSerializer
cause i didnt have profile picture field in it
I don't think that will solve your issue. Your AccountSerializer still won't receive the username and the password, or does it?
thats not actually a solution i been stupid
it does i just created new users and it was working
can you post the code?
@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
pass in all of your information through your request (instead of the query params) - then do serializer.save(), that will make it much cleaner.
yeah
this is a practice
not that important i just wanted to upload the image
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:
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
the term for this is "guard clause"
there isn't one
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
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'
``
?
Try default argument lol
thanks
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()
You can just put the CSS within the HTML and serve the HTML instead
ok thanks i got you anyway
React page reloads and gives forbidden with django!
Anyone know HTML for adding a chat bot window in the bottom right?
just making sure, you know that it would involve more than HTML?
CSS, javascript for sure (some backendish)
in laziest choice, it could be inserted as some sort of iframe from another service
then it would be literally HTML only
#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
what you trying to do?
i fixed it somehow
Now i wanna know can react-django integration work without using rest api?
you should use rest cause you gotta use json data type to get or post data to react
unless you find a way to change it and itll get a bit complicated i think never used them without rest
i did in js without api with ajax
Problem is am using firebase
never used firebase
using rest yeah
smh without it
dont think you can without changing your data to another type
like what type
in react its a type and django another. no difference you sending or getting data in both you gotta change the data type
like when you want to show data in react from django you gotta change the data type to json. this is what what i know
Hmm, let me check rq, thanks
yw
@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.
Unexpected token < in JSON at position 0 this is all i get as a response when i post somthing
guys any idea what database should I go with with flask?
@nova nacelle you're gonna have to show some code if you expect meaningful answer
Am atm trying to find a way, that's it
Post requests doesn't work
@quasi relic sqllite or mongoDB are both good
I think there is a tutorial out there that uses MongoDB
ah okay thank you 🙏 I will check mongo then
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

mongodb is not... a regular sql database at all
y ping me smh
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
I print this ```py
request.environ.get('HTTP_X_REAL_IP', request.remote_addr)
probably your vpn trash
google shows vpn ip
google pretending. just want you to feel comfortable while there something else happening in the background
LOL
I knew something wrong with google
even this shows my vpn ip https://nordvpn.com/what-is-my-ip/
EVERYTHING EXCEPT MY SITE
xDDD
maybe because these all are published on google servers
ahh
google is too powerful
XD
are you connecting to your website you host locally
yea
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
ahh, yea, i understand, thank you!
@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?
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
i used xpath, I found it was comfortable to use
will it help me in what I am trying to do?
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
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% |
bc you made a new table row with "tr" in the middle but instead you should just close it at the end and then it should look like what you want
apart from that, why append html to your file like that? use jinja2 templates 🤦♂️
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
if I'm looknig to deploy, is it useful to learn nginx or should I just hop straight into learning AWS?
#tools-and-devops sort of this section question
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
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
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
If you want a quick and dirty way to do it, you should just concatenate in the variable e.g.
$query = "SELECT * FROM university_table WHERE uni_nationalrank" . $NationalRank;
providing $NationalRank is a string literal of ">=0 AND < 11"
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>
That could potentially work, yes
However, i'd recommend not putting any sql inside your form values
what other way do you recommend doing it ?
Anyone able to help with making a chat pop up window on my website
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
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?":
...
}
i see, i have 5 of these boxes to do would i just copy and paste 5 times and change the variables ?
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?
how do you reverse a string?
string_name[::-1]
Thanks
pretty sure the "usual" way about this is going into the module's AppConfig, and adding:
def ready(self):
# import stuff here
but I guess that is the "apps" way you're talking about
yup the same err
@opaque rivet if its a test deploy or u already got a domain i would deploy it on heroku bc its easy to setup and to upload bc of the github connection. and if you like you can automate it even with some github actions
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?
@dawn heath I'd assume many exploits could have many sources no?
ys
Hey guys im trying to convert html tables into csv but my csv doesn't come out right
can i get some help?
Use manytomanyfield.
Can you paste the html and code you're using?
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
Let me fire it up and give it a shot.
@viscid valley thank you!!
To get the owner of the guild, it's guild.owner correct?
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()
Ya, happens to the best of us.
To get the owner of the guild, it's guild.owner correct?
What's this for?
I'm guessing this is for Discord? This is #web-development . You'll want to ask in #discord-bots
Ahh wrong channel
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
Sus, I'm personally not going to help with that. Sorry.
this is my code
Thanks man anyways
But do you think I explained it correctly?
No, it just seems like you're trying to dictionary attack someones poor outlook account.
!rule 5
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.
With this project. I certainly hope not.
So, is there any discord channel I can find help in?
No, what you're doing is mean. You're trying to hack into someones outlook account.
If you have questions about non-nefarious projects. People are more than willing to help you.
@keen ravine https://www.fbi.gov/
Send them that code and explain what you're doing.
I'm sure someone there will help you.
Why Choose Flask Over FastAPI
https://www.pythonkitchen.com/why-choose-flask-over-fastapi/
Given the number of articles that goes one way, this throws up some info
which framework?
flask
I can share it with you
Oh i mean normally the best way is to share a pastebin here
Then people can get a better idea
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
It can be.
You can also use Python in the browser, via.. say... Brython
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>```
It depends on what kind of email form you are using, it can be backend request form or by adding some specific smtp mail server(maybe just action="mailto:someone@example.com")
use html <p style="word-wrap:break-word">Toegevoegd:<br>{{game.add}}</p>
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 :)
This is a Python Discord. You should look into learning Python/Django :).
i already have, i'm just trying to expand my knowledge of web frameworks :)
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
Using writerow?
CR is \r
LF is \n
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
add overflow-y: hidden;
centering what
Sorry, I miss understood the question.
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
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:
smaller in mobile:
<meta name="viewport" content="width=device-width, initial-scale=1">
make sure to add this inside your <head>
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
is there any loop?
and are you using django?
Nvm yea it was in a loop i got it fixed :p. Thanks
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
??
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
I figured the issue was I set the width/height to the div in stead of thr img 
A game database dashboard

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
depends on where you’re hosting
and how
but generally you need to provide a requirements.txt at least
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
U can load css file like <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='file.css') }}">
nope didnt work
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
hi, i need to make a chat in django, can some one help me?
Im not really into django but this can be a introduction of a chat app https://getstream.io/blog/realtime-chat-django-angular/
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
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
does it show in which line the error is and if so pls show the code
hi, i need to make a chat in django, can some one help me?
u already got an answer above but as alternative u can use django-channels
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?
#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
in the error message it says unexpected keyword "method" so you probably need to remove/or change the syntax of the method parameter in the action decorator.
hope that helps
oh
it should be methods instead of method
but now it raised new error
wrong regex at the url_path param
@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
@opal portal can you show the other urls or rather where "by-faculty" is defined
@maiden tulip i tried it and it does only check for "@" but not if its empty or a ends with .com or sth like that
yeah, "" is an allowed input, meaning the user didnt enter an input. https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email#value
elements of type email are used to let the user enter and edit an e-mail address, or, if the multiple attribute is specified, a list of e-mail addresses.
@native tide this is the error
ok sry but im not good with regex so i cant help you anymore
oh no problem. appreciate your help
yeah thats why you should probably check it yourself too and dont rely on smth.
@native tide no, to check if email is empty, you use required="true"
np but i dont understand regex nor i understand what you fully want to do so its better to not help than giving you wrong info
yeah ok you can do it like too but i would never
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
Can you help me with doing this? im new to django
ok i thought you meant backend as well but sure you are right with that
no, only validating in frontend would be stupid as sb could just send the manipulated form over REST/GraphQL
Basically: Do we trust the users brower on their email pattern matching
yeah i tried it myself and kinda succeeded but i would rather suggest you good tutorials you could benefit much as a beginner with django-channels
yeah thats what i meant you should always check it again with some kind of 3rd party package or coded yourself
Can you send pls easy and good toutorials?
@wheat skiff sure
Did my solution work ?
@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
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)
ahh i see. Yeah i am going familiarize myself with functional components aswell.
I think functional components is just a little bit less code to type.
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
class base views in some frameworks like react are more verbose. you can customize it. you can add more functionality to it which is function based views in django.
Interesting, yeah when i use class based components, it feels like i am being more explicit with the code
true
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
ive been meaning to ask, how to i immitate typing effect on my website
can any1 know how to fix it
: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).
Please don't spam our channels, thanks
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')))
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?
Hello guys
Anyone have an idea of how I can bypass cloudflare with selenium
It keeps loading and i cant get to the site :(\
functional components 100%. Not all JS libraries support react classes (some are functional-components only - due to hooks). You get access to hooks. Much less repeating yourself (e.g. binding each function in your class in the constructor - yikes).
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)
ah i see. am i able to use both? for example some components class based and some functional? or is that a bad practice?
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.
oh great, yeah I haven't looked at other react libraries yet, besides nextjs. I'll take a look at redux
mhm redux is a must, a majority of large react apps use it for state management (plus it's pretty simple once you actually understand the concept over time).
also good choice on next 😉
awesome, thanks 😄
<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?
you'll need another input which contains the guild_id data, it can be hidden and can have a value which you pass from your view, then it should also be in the URI
what type would the input be?
hidden
it worked. Thanks!
🙂
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
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)?
you are making a GET request to /settings?guild={{ guild_id }}&prefix=...&..., does your view handle that endpoint?
yeah
it bypasses the if statement if request.method == 'get':
could you show code? could you print request.GET to see if you're actually making requests to that endpoint?
I'm pretty positive that request methods must be uppercase, GET.
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 ?
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..!
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 ??
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.
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']
I believe you want to override the save method?
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 ?
You're trying to update multiple models and such during the save of one model?
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 ?
Yes, you would override the save method and do all of this.
Then use super... save the model.
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
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)```
That's an example of overriding save method for a model.
like this, i only want to show the title/description and file
You def save, do your logic then use super(ModelName, self).save(*args, **kwargs)
Oh set editable to false.
In the model.
model or serializer ?
things is more complicated than just hiding. let me explain from the beginning
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?
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
ok
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
so that's your project.
well yeah, basically
what's problem.
Ok, if you want to limit fields
the uploading and mail noti not work as expectation
I just start to learn python
We need to do that in def get_queryset(self):
i want to limit fields when creating new instance through api, but when retrieve list of instances there will be all
are using Django?
yeah, Django and DRF
ok
Can I see your serializers.ModelSerializer?
have to tried Stack overflow ?
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
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
Ok, so you want to rename files upon upload?
no
Files are losing their extension?
Ok, so one problem at a time.
I'm totally confused too.
Lets start from the top.
When users get a specific viewset you want information pre-populated?
no form, just directly through api
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.
Here? See the create method?
You can query/update/save other models.
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 ?
requests.user.id will simply give you the users id.
you can then do Model.get(userid=request.user.id)
Assuming that's the foreign keys field name
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 ?
You want to query the profile model from request.user?
yeah
Also, you can do dir(object) in Django by setting break points in your django code then making request.
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
How do your user model point to this?
you see, my contribution model also have a faculty foreignkey
Are you using djangos auth user?
erm, a custom user model
Ok, paste it
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
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?
yes
OK, do dir(request.User)
can you elaborate ?
not at all
Oh man, you've been flying blind.

pip install ipdb
Is this channel free to ask questions
@astral pagoda It is.
@opal portal Grab one of the help channels actually, this may be a while.
Mention me in it.
kay
@astral pagoda What's your question?
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?
Let me take a look.
In your browsers inspect tab
K thanks. I also screwed up and posted in an occupied channel. It won't happen again.
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">
k let me test it.
Sure
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
@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 | **
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
https://www.viperfangs.tech/Rhetorical-Analysis.html
why does the embed refuse to connect?
Coming Soon.
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".
set FLASK_APP=name_of_your_start_file.py
For windows
In Linux replace, set to export
for react project structures, is this okay?
grouping folders with features and having css/scss files inside them
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
who is using flask for python web development
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.
can someone help me regarding this I got this error on all crud operations in .net
https://paste.pythondiscord.com/erimuhayuz.pl (this is my update query )
can someone come in #help-lemon
@fair shale if you use virtual environments, have you activated it?
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')
the get_path function should not be inside the model definition. Just move it out
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 probably u got a media query on some screen width and theres a border defined for your header
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?
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...🙂
Is this error mean that the store procedure doesn't exist?
@sturdy sapphire sorry to ping you here
can you elaborate this
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
anyone?
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...🙂
@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?
you can get a list of same elements and use index to get the proper one
thanks, I will try
🙂
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)
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
you can use django channels
i tried to look for tutorials but i dont understand them
if a website have 3 same iframes ! ,then how can we automate them ? using selenium?
selenium is a good option. I prefer
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
qs was about how can make selenium work for same iframes?
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.
@wheat skiff django channels is the way to achieve that
Thanks buddy
🙂
Guys I have a simple question
Why this while loop don't work?
arr = ['0','1','2','3','4'] count = 0 while True: count+=1 print(arr(count))
arr is an array
yeah
🙂
Can i do a live terminal webpage?
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?
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
Uh hey
How can I store sensitive information on a client's computer?
oh ok
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?
You might want to surround the first %s with quotes
only the first?
I think so
k let me try it
if you're just using raw queries to learn sql, go for it, but in reality we should be using the django orm.
please help
I'm using sql because it's easy to understand. Models and orm kind of confuse me so that's why I'm just using psycopg2.
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?
Is there any way to store them?
cookies are saved in the user's browser. I don't really know what you're asking, yes you store information within the cookies - they are a key value pair
Sorry I meant is there a way to store the username and password in the browser?
yes, but you don't want to do that. (again, by using cookies). Instead, you can store a token which is unique to each account in the browser to be able to identify each request (instead of relying on their account information to be sent as cookies)
you can set cookies from backend, from your server's response:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie
or using JS, look at the js-cookie library
The Set-Cookie HTTP response header is used to send a cookie from the server to the user agent, so the user agent can send it back to the server later. To send multiple cookies, multiple Set-Cookie
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
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.
Thanks!
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?
Did you run db.commit()?
Also I think that update and set should be capitalized so that it looks more readable
it says that the cursor object doesn't have the attribute commit
query = db.execute("UPDATE prefix SET prefix_name = %s WHERE guild_id = %s", (prefix, guild_id))
db.commit()
Do the commit on the database, not the cursor
db.commit() AttributeError: 'psycopg2.extensions.cursor' object has no attribute 'commit'
oh ok
it worked. Thanks!!
How do I prevent CORS on my Flask server?
Getting this, how to solve this?
Are you using the correct username and password and host?
I just install and getting this error.
when using react and django together, are you basically running 2 different servers essentially?
Have you run the apache and MySQL correctly?
is express nescessary when using nextjs?
yes I did.
that's working properly.
let me check once.
I think the user of MySQL should be the root
no (but you can implement your own nodejs api for it)
this the correct channel for talk about html
Hmm I am not sure 😅
ok
thank @dull coral it's solved.
You are welcome!
yep
ah i see
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
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
idk cuz express is javascript
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
flask is probably easier to use
I'd honestly say it's about equal
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
cuz it works better for them
you can use <Component />, why not?
lots more people use express because JS is specifically a web-dev language
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
You still have to get data somehow
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).
So your backend app should provide it 😉
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 😦
but I mean with my flask app i would be rendering the templates anymore
nope
or passing variables to my templates and stuff
so all I would do is return 1 empty page?
well, you return one single page and the rest is done on the client-side
then your flask backend just serves as an API
yeah so just api
you can also sprinkle react is templates but i've never tried
hmmm
Express is really basic imo 😅
Kinda like flask
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
I think flask is obsolete now because of fastapi
And for js you can use something like nestjs
all of the routing is done on the client side, the routing is no longer handled by flask.
thats crazy to me
you render your React app once, then that is your application.
specifically the routing is done with React-Router
and then you only use flask as an api server
Right
pretty much 😄 just like any backend framework, really
I wouldn't write any app that might have more that 50 lines of js code without some kind of framework
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
So moving to node just to move? 😅
For me its just because of popularity / employability
I like django but fastapi does things so much better 🤔 but sadly it misses some features
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?
@opaque rivet Not really, it's flask on steroids 🙂
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__)
i'm wondering what __name__ does
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
ok thx, i have another question
I kinda don't like django because it's hard to use with openapi...
You either have to define schema by hand or write custom input/output serializers for each view
openAPI is the thing used to write api docs right?
Yep
what is @spare ridge.route('/') ? and more generally, why some functions have this @instance.xxx() before their def ?
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
Also flask doesn't allow to register routes with specific methods (Get, Post, etc)? 😅
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 ?
@native tide Share the actual error
do you want all the traceback ?
Sure
Template not found 🙂
flask is trying to find them in templates directory by default
So create one and put your template in it
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
you can pass templates_folder argument when creating flask instance
thanks for your help
let me read the doc 🙂
try "../templates"
If that wouldn't work then it needs an absolute path
so you can try
from pathlib import Path
Path("../templates").absolute()
is anyone familiar with cpanel?
yeah from like 15 years ago
Thanks!
<img src="Denis_Villeneuve_Cannes_2018" />
is this the wrong way of using image tag?
You also need to add the file ending like .jpg, .png etc
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 @green snow thanks there.
@oak sky Idk what db youre using but that could help you to "fake" a 404
https://stackoverflow.com/questions/53042728/flask-get-or-404-like-function-but-with-another-status-code/53043143
ok ima check that out, i found smth about abort(404) too
ok i think both answers are ok bc they look similiar in django but idk flask so idk if that will work
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
great 👍
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?
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
I think issues are with indentation
does anyone tried deploying their django app on heroku? I kinda need help rn 
the error i get says the element cannot be located then my code stops there
hey
I deployed like 3 different already and updated them around a 100 + times. What's your problem?
open the dev tool console and see if there are some css loading issues
can i tag u on the help channel
wait
Hi everyone. Let me ask about django-braces - is it still useful these days? The last update was 2019
mby sounds dumb but just add an else block and in there print smth and see if it works then
@jovial mist is that header in he response from your server?
I found the problem
Its because Debug = True
for some unknown reason it does that 😦
btw can someone help me fix this error (heroku)
sry idk what varying is but it says the value is too long for that type. Can you show where you assigned that
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?
are django-crontabs supported while deploying a website on heroku?
webscrapping
There is URL Field?
yeah mby that fixes it
This is probably because you are using sqlite database in local and postgresql in production
dk How to fix that
Sqlite doesn't enforce the max_length thing but postgresql does.
should I just delete this ?
Show your models
nope it doesn't fix it, I just changed it
sry but i cant rlly help you there bc I havent had that problem yet but mby if you can try switching your db in production to MySQL bc then it works for me with max_length
How can I do that?
how to draw a web app architecture?
if you are using heroku. Its pretty simple just go to addons and add ClearDB MySQL and then u got it. the only thing then left is the change in the settings.py
This is what I used : heroku addons:create heroku-postgresql:hobby-dev
Terrastruct?
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
What is tetrastruct?
It is an app that can be use to draw a web app diagram
Ohh I know some developer architect their web app in draw.io
Yeah
those are the app to draw diagram
But I want to know how to draw one
Using this video you can understand how to draw Class diagram in StarUML.
This is the class diagram for Hospital Management System.
Also you can generate code from this UML diagram, to know about it, visit video "Generate code in StarUML" on link: https://youtu.be/tY5Sw2YDVpI
For more UML Diagrams:
How to draw Sequence Diagram:
https://www.you...
Thanks for sharing that
no problem
Yes, I used Postman
Hi guys, i've a question
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
are you using jwt authentication?
does JWT also authenticate? i thought that was for authorization only
or u can use like login required thing
I read something about djoser, which is kinda what I need
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
'rest_framework.authentication.SessionAuthentication', # Required for Browsable API login
),
its for authentication
`from django.contrib.auth.decorators import login_required
@login_required
def my_view(request):
...`
okay that sounds good, thats build in right?
Also for email confirmation, password reset etc. etc. what do you recommend me to use?
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
You can also use django auth to rest password
kinda yes, front-end vue and backend python
API with JWT authorization, but should I handle the login, register as api aswell or
in this case, you don't have to use built-in password reset/email confirmation function
you should handle everything using API
why not?
doesn't make sense to me
built-in password reset/email confirmation is for django template
hmm okay
bc the syntax is wrong. You need to have a space between {% or %} and the if statement
so to wrap it up, login / register should be done trough api calls aswell?
oooooo
@thin dome
always reply and tag them so they see it
thx
thx to you too
np man
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
Hey, is there any way to make subdomains with flask?
you usually do that trough the DNS no?
Well... is there a way to do it via flask?
there you go
@native tide its not working 😐
then the condition is false
but its correct
you dont need to endif before elif thats probably the error
Well it didn't quite work
endelif?
remove {% endif %} before {% elif %}
bump 😄
@thin dome is it working?
i dont understand
you only need the last {% endif %}
oh
is this what are you saying?
yes exactly
but its not working too
ok can you show your models and the view for that page pls.
ok and the view of that page pls bc it looks like your linter detects some errors
@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
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
what is linter?
is there a way to create a model in django whose instances automatically get deleted after some time from their creation?
Sounds like time for Celery and Redis
celery doesn't work on windows ig
Pack in docker
I heard it was made working in windows 10
But better start working in linux
It is better way anyway
also if i deploy my site on heroku will it work there also or i will have to use their task scheduler?
Not familiar enough with heroku
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
hmm... i don't know much about nginx.
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?
nope - use celery for that 🙂
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?
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}'")
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?
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,).
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?
my bad my bad
always use prepare staments
😛
cc @formal gull
what
@formal gull was regarding this, don't use f strings
was my bad
wrong person 🙂
Anyone suggest me best site to learn css?
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
ill try this thanks
not sure wym by an else block tho
it worked. Thanks!
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
Just wrap to
query = db.execute(f"select prefix_name from prefix where guild_id = {str(guild_id)}'")
@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'
hi
will these work even after i deploy the website on a platform like heroku?
Can i use js vars in python with flask
Like i get an input from <input> and use the string in python?
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;
}```
who deleted their answer to my question?
i just got time to work on my code and now the help i needed is gone
hey is this correct? html <a href="/"><h2 class="text-white title-font text-lg font-medium">{{dress.name}}</h2></a> {% a = dress.name %}
who is using flask to code site
