#web-development
2 messages ยท Page 99 of 1
Okay but
I literally explained u why it isn't working
๐คจ
If there's a doubt, feel free to ask
okay
I am just having some issues with the function
to add
not sure where to begin with that part
okay hmm wait, do u know how functions have return types?
yeah
but lemme ask a dbt . If I use put this way then couldnt the user get the data and manipulated. ?
@outer pier You can send updated database to user as a response
so querySelector returns a single element, which is why what you're doing works fine with that
but querySelectorAll returns an array of elements, that's why ur code won't work
so to be able to actually modify class for those element, u need to use forEach
I gave you a link
okay did u study arrays yet?
because if u did, then you might have already studied what i sent
yeah I did
Okay then, u got ur solution
btn.addEventListener('click', e => {
e.preventDefault();
function myFunction(item, index, arr) {
arr[index].square;
}
document.querySelectorAll("#board>div").forEach(myFunction);
console.log(container);
})
any reason why that wont work
doesn't return anything
no errors or nth
you mean it's only sending one element to the function at a time/?
yep, you Don't have to iterate ur self
oh the function isn't necessary then
the arguments to myFunction are correct. though arr[index] should be the same as item
though you can use item directly.
but currently, that statement arr[index].square; doesn't really do anything
I see appreciate that
I know how to add the class to a element but I am confused on how to put this in a function
do you want to add a class to all child-divs of #board?
function myFunction(item) {
item.classList.add('the-class');
}
to make the 9 grids
then something like that
each "item" is going to be a div from your querySelectorAll result
okay I think I am king understanding now
you can also do multiple classes like:
function myFunction(item, index) {
item.classList.add('the-class');
item.classList.add('the-class--' + index);
}
then the first div should have the-class--0 the second has the-class--1 etc.
uh it's for an assignment ๐
oh well
thanks for teaching me that Sani
@versed lotus cmon
it's not like I wasn't trying
@marble carbon cmon
but he never gave exact
kinda
he don't even seem to look at my code
I will be back
I really appreciate you sani
for that a little help
and understanding
def api_update_event(request, slug):
try:
event = Events.objects.get(slug=slug)
except Events.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.method == "PUT":
serializer = LeadSerializer(event, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(status=status.HTTP_200_OK)```
I'm having trouble understanding this line:
serializer = LeadSerializer(event, data=request.data)
Is the data that is passed to LeadSerializer in JSON format?
The helpers should have a donate button like @versed lotus
If so, is it then being appended into an object for the model?
like a tip button or something like that
have you tried printing it? print(type(request.data), request.data)
no idea what LeadSerializer is though
I don't exactly know how I can print that, as request will be a PUT request to the api.
LeadSerializer is a ModelSerializer
Hey @hollow hill!
It looks like you tried to attach file type(s) that we do not allow (.toml). We currently allow the following file types: .3gp, .3g2, .avi, .bmp, .gif, .h264, .jpg, .jpeg, .mkv, .mov, .mp4, .mpeg, .mpg, .png, .tiff, .wmv, .svg, .psd, .ai, .aep, .xcf, .mp3, .wav, .ogg, .webm, .webp, .flac, .afdesign, .m4a.
Feel free to ask in #community-meta if you think this is a mistake.
Hi there, I'm having regarding static files with Django and I'm stuck on what exactly the problem is. I am simply trying to load a css stylesheet into my base template. According to Pycharm's autocorrect, it is in the right location. However when I serve the page, I get a 404 for its location.
The app is registered, to get that out of the way. The css file is in projectroot/frontend/static/frontend/css/style.css, frontend being the app name.
As for the base html template, here is the code to import it: <link rel="stylesheet" type="text/css" href="{% static 'frontend/css/style.css' %}">. {% load static %} is on the line right before it.
are your other static files being imported correctly?
this maybe an issue regarding settings.py
this is the only static file so far, as this is a new project
@native tide Do you have load static at the top of your template?
I do
{% load static %} to be precise
INSTALLED_APPS = [ .... 'django.contrib.staticfiles', 'frontend' ]
Have you run the collecstatic command?
I have not
hol up
I'm reading that rn on my other screen
Was this file working before, you made updates, and now the updates aren't showing?
this is a brand new project, this is the first time I tried to use a static file for the project, and it simply is not working
ok nevermind then
so its all stock settings in settings.py
For future reference, though, you should always put ?{% now 'U' %} after the block with the static file in it.
inside the href attribute.
tacked onto the end.
what does that do?
It prevents browser caching from not registering changes to the css file
because it forces it to load a new one.
oh thats very useful, thanks for letting me know
Do that after every static file.
href="{% static 'blahblah.css' %}?{% now 'U' %}"
and also for scripts as:
src="{% static 'blahblah.js' %}?{% now 'U' %}"
awesome, thanks
only BASE_DIR and STATIC_URL. I was under the impression there was nothing else to configure in settings.py to get static files to work in registered apps
I'm still here, reading into it
that did it.
STATIC_ROOT = '' magically made it work
Okay, well, I wouldn't do that though
I would give it a path
So it's not dumping all the static files in your root directory.
which is only the case if I run collectstatic, right? right now, the css file is nicely structured inside the static folder for my app
pretty sure, yeah
Here's what I have:
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
my only concern right now is that static files serve in the dev environment, once I deploy this to a linux box I'd definitely like the files in their own neat place
Yeah, just copy and paste what I wrote into your settings.py file in place of the empty string.
can confirm that works as well
I'm still a bit confused why it works though, because from what I'm reading online, STATIC_ROOT is simply where files get 'exported' to when you run collectstatic
if you don't know its fine, I'm still very pleased and grateful
I don't know why it works, just that it works.
sure
I'll remember this going forwards
are you going to be serving static files from your database, too?
aka "media" files.
@topaz widget media files are not served through database
in database links of media are stored
They are referenced from the database.
yes
I was imprecise in my language, I know they're not stored there.
ok lol
semi answering your question, there will be a fair amount of files being served, but they will be via s3, and I believe a python library called bota which interfaces with it
so the only thing being saved in the DB is simply the path to those files
Well, if you're going to be serving "media" files on your development server, you should add this line to the bottom of your root urlconf:
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
And you need this import statement at the top of the urls.py file:
from django.conf.urls.static import static
I wont be, but thank you though. Once I get to the point of getting this functionality working, to keep it simple I'm jumping straight into s3 buckets
ah ok
as for the static files, there will probably be no more than a few dozen total (svg files, and light stuff like that)
so I think I'm set
good deal
this helped me a lot, thank you again
yw
When you need a job to be done fast and the client doesn't care if you use a template ... How would you handle that ? how you get kinda readymade templates or wireframe or stuff like that than we can use as a base? What is path professionals or freelancers take ? Do do you actually start from scratch ? write your own css and stuff ?
Any freelancers ?
As you guys must be concentrating on the backend .. how do you handle the frontend ? help
ping
@near bison 100% bootstrap
That what you do ?
yes
the stock theme is a little plain, pick your favorite from here: https://bootswatch.com/
you simply load the css file, and it gives you a ton of css classes to plug in
Hmm..Is there a way for me to build components and store it. and when the clients what some feature.. i can just add it and not build it from scratch
I tried bootstrap. but with bootstrap i spend more time trying to change the framework than actually progressing .. then i tried tailwind .. which was good.. i am using sass.. But i don't know.. if someone what something done fast.. i can just use a template right ?
https://getbootstrap.com/docs/4.5/components/alerts/ look at the available components first, if you haven't before
it gives you a LOT to work with.... different types of tables, alerts, nice looking buttons, etc
with these primitives you can do quite a lot
sure, you could use a template too
I suppose it really depends on what you're doing, and how granular of control you need
Thanks
๐
@near bison If it's about money and there is a free or cheap template available that is acceptable to your client's need, you would be stupid not to use a template.
not a fan of bootstrap? lol
you talking to me? @native tide And no, I'm not a huge fan of bootstrap.
but i would happily use a bootstrap template if it did the job.
yeah. could you say why? I'm not arguing, just curious on your perspective
Because you basically have to learn all the boostrap classes and what they do, and it's not that much harder to just learn css.
me too
a little bit anyway
but then I realized I didn't want to be locked into the bootstrap paradigm and thought it was a waste of time to learn that more instead of just learning all the underlying css.
(and js)
yeah that makes sense. I'm forcing myself in my previously talked about project to do my own css, just so I'm more comfortable with working with it. all of my previous Flask & Django projects have been with bootstrap over the past 1-2 years.
Well, if you're doing stuff that is pretty cookie cutter, bootstrap is fine. You can even make nice-looking stuff with it. It just boxes you in a bit if you want to do something kind of unique or complex.
I've seen some pretty attractive bootstrap templates. It has its place.
which is exactly what I'm doing now, so hearing that reaffirms I'm making the right choice lol
If you're making some slightly custom site for which there isn't a great pre-existing template out there, bootstrap seems like a good tool for that job.
anyone use redux :)?
@cerulean otter yes i did
@bronze oak
Does anyone know if a website GUI is possible to be tied into Discord? Like, a GUI app for a Discord bot is possible... but what about through a website?
yes it is possible
webpages are just views which are just python code blocks. You can do everything here, which includes calling discord.py methods
@marble carbon thanks ill try this
hi i need help
@stable kite
how to add speedometer or gauge to monitor host usage in html.
Any tips for allowing my Flask app to serve JSON responses faster?
@ me when answering please.
@glad patrol can you elaborate your question
@stable kite
i have my index.html
which display some widget like this
they are some ecommenrece widget
what i want to display host usage here
like cpu ram and netwowrk
like this widget
@stable kite i hope you get my question.
My flask webapp is attempting loading favicon for no apparent reason.
Its literally just a basic test page that returns a json, so anyone know how to fix that, or why that may be happening? if so, please @ me when responding.
is Django + React common?
@glad patrol just code your widget in html & display widget as per data received from backend
@native tide not so common
but can be used
Yeah I'm currently trying to make a Django + React app utilizing APIs. Hopefully it'll be a good project ๐
@topaz finch it will be in your html code so
the module is not found
does anyone know why it says the file is not found after I ran runserver?
name your app correctly
@wise crescent you have use personal.views & not design_hub.personal.view
it shows error if I only put personal.views
like this
yes, it shows error
have you added your app in settings.py?
sure
in which directory is this file located?
@wise crescent ??
@wise crescent which Django version are you using?
oh I get it, I added the name in MIDDLEWARE but not the INSTALLED_APPS๐
thanks, it works now
no problem
sorry for the stupid question
I have a view here```python
@login_required(redirect_field_name='user_login', login_url='/login/')
def profile(request, pk):
user = Person.objects.get(id=pk)
context = {
'user': user,
'title': 'Profile'
}
return render(request, 'index/profile.html', context)
But I don't want a user that isn't a staff user to be able to view this page
how do I do that?
@native tide just check if user requesting this page is a staff member then return the page & if not then render a different page
^ along with django view level permission will be enough
@topaz finch browsers always ask for a favicon
How does signUp email verification work in websites
in django how can i get the raw sql changed data in a UPDATE?
Im having a problem with divs and buttons
Im having buttons under a div element. I make the div into a grid so that I can lay the buttons out as I want but then the css I had written for the buttons does not work
https://paste.pythondiscord.com/owuxejehug.xml - part of the code with the problem
are static files usually front end or back end job
Anyone know where i can get official info on security best practices in django?
I know django has documentation on its security features
but looking for a best practices document
I suggest reading OWASP materials and then finding specific Django patterns and/or libraries that will help you meet those standards. Also suggest using the OWASP ZAP tool to scan your site(s) regularly.
Thank you @marble carbon and @warm igloo .
btw
Is django suggested for production environments?
Ive had the thinking that django was better for prototyping and that apache was better for production environments?
Huh
Those are two different things
Django is used to build applications
while apache used for serving that Application
so apache will handle the traffic
Yes I mean the web server portion that is serving the application
actually I have a talk for it too
that'll explain better
but they used nginx in it, which is about the same as apache
Ok. I meant that i thought apache is better for serving the application..or nginx too
WSGI is the foundation of most Python web frameworks, but there's a good chance you've never had to interact with it directly. In this talk we'll explore why it exists, how it works, and what the heck it's doing in your stack.
A great web framework abstracts away all the low-...
watch this, you'll understand the layers
Awesome, I will look at this too
Cool thanks
From my understanding and past exposure, django can both serve and create the web application itself...nginx and apache just serve the application (?)
Uhm Django doesn't comme with a production scale server
only a development server, which should not be used in production itself
yeah thats why I was saying before that I heard django isnt good for production
they instead provide an interface, that is the WSGi
Ah ok
Ah ok. Thanks for explaining
#web-development message Could I get help with this please Please don't bother its solved
Im fairly new to databases and Im working on a django-application right now.
It will allow users to create an account. My way of approaching this would be to have 1. A table for every user and 2. A table for (for example) pictures they liked with each of the pictures having a pointer pointing at the users who have like it.
But for this to work, I would have to loop through all the pictures and check if the user Im looking for is in the pointer-"list".
Is there a better way of going about this problem?
Why do you need a new table for each user? Just use a new record, that is, insert a new row into the db when a user signs up
@topaz finch browsers always ask for a favicon
@dapper tusk But there is no html being sent, only the dictionary.
As for your question here's how I would approach it.
- Sign up user (using a custom user model as defined below) and insert relevant record to db.
- Create a model called
UserUploadedImagewith definition as below:
class CustomUser(AbstractUser):
images = models.ManyToManyField('appname.UserUploadedImage')
# etc
class UserUploadedImage(models.model):
image = models.ImageField()
# etc
- When a user uploads a new image, I'd create a new
UserUploadedImageinstance and associate it with the currently logged in user.
yes, but browsers ask for a favicon anyway
@vapid acorn
maybe there is a header you can send to make it not ask for one
@versed python lol I I wrote on table for every user, so you can understand it both ways, but it is one table containing every user
Ah well that makes more sense
Hmm that sounds about right, since it is going to favicon.ico endpoint that doesnt exist, it is probably returning my Page Not Found page to the browser. Ill check for a header.
So is there a better solution then having one gigantic pictures list?
I just gave you a solution ๐
hey how to pass date type in postman
{
"timestamp": "2020-10-11T15:47:24.685+00:00",
"status": 415,
"error": "Unsupported Media Type",
"message": "",
"path": "/api/courses/store"
i got error like this
@native tide who other guy is?
i want to get ist of courses with these filters (specific student, teacher, time range)
whats the problem in that @native tide
are you using any framework?
no just by requests package
where are you getting data from?
postman
It's an API package
Hi all, if I have an HTML form that is displayed when a hyperlink is clicked that submits a post request; what's the best way to handle the submission for the user? Currently I'm just returning a slightly different template that indicates the submission was successfully but ideally i'd perfer the user session not be interrupted. Is the only way to do this to have the post request be submitted via ajax client side?
@native tide it doesn't have data stored in it
using bottle btw
@native tide it doesn't have data stored in it
@stable kite icant get y
@loud mountain no idea about bottle sorry
@native tide like database or something else
@native tide like database or something else
@stable kite aha its h2
what is h2?
then you have to use javascript for that
i think so
memchache means local db?
right?
javaxcript for front ?
memchache means local db?
nearly
javaxcript for front ?
@native tide yes
because you can't access memchache with python as far i think so
@native tide yes
@stable kite idonr need front at the momnent i m just calling it by postman
window.addEventListener('load', () => {
var btn = document.querySelector('.btn');
btn.addEventListener('click', e => {
function myFunction(item) {
item.classList.add('square');
}
document.querySelectorAll("#board>div").forEach(myFunction);
})
var boxElements = document.querySelectorAll('.square');
boxElements.forEach(square => {square.addEventListener('click', handleClick, {once: true})
})
function handleClick(e){
console.log('clicked')
}
});
I am trying to get each div that is click to only be clicked once and it should show clicked. Not sure what is being done wrong. Anyone?
@versed python now I see your solution, thank you
@white spruce What's happening with your code now?
Yay!
shoot
@app.route('/api/login', methods=['POST'])
def login():
# TODO: Try/Except return error with required field
req = request.form
login_schema = LoginForm()
req = login_schema.load(req)
user = mdb.users.find_one({'username': req['username']})
if user:
password = req['password'].encode('utf-8')
hashed_password = user['password']
check_password = bcrypt.checkpw(password, hashed_password)
if check_password:
session['username'] = req['username']
print(f"Welcome, {req['username']}")
return redirect('/')
return redirect('/login')```
I am trying to make flask redirect the user to a page depending on if the login succeeds or not
but in both cases, nothing changes and there is no redirect
I also tried using py redirect(url_for('login_page'))
but that wont work either
@app.route('/login')
def login_page():
return render_template('index.html')```
I'm assuming you're using marshmallow and sqla there?
marshmallow and pymongo
gotcha. have you checked that the user is happening?
oh derp, I see what's going on now
you want redirect('login')
the app registers the route as the function name
directly?
yep
I thought you needed url_for
just a sec please
I'm hanging around
it returns py 127.0.0.1 - - [11/Oct/2020 22:45:44] "POST /api/login HTTP/1.1" 302 - 127.0.0.1 - - [11/Oct/2020 22:45:44] "GET / HTTP/1.1" 200 -
but it doesn't redirect the page anyway
anyone I want this to alternate from X to O but only getting X's
btn.addEventListener('click', e => {
function myFunction(item) {
item.classList.add('square');
}
document.querySelectorAll("#board>div").forEach(myFunction);
var boxElements = document.querySelectorAll('.square'), X_or_O;
boxElements.forEach(square => {
square.addEventListener('click', handleClick, {once: true})
})
function handleClick(e) {
for(var i = 0; i < boxElements.length; i++){
boxElements[i].onclick = function(){
if(this.innerHTML !== "X" && this.innerHTML !== "O"){
if(X_or_O%2 === 0){
console.log("X OR O");
this.innerHTML = 'O';
}else {
console.log("X OR O");
this.innerHTML = 'X';
}
}
}
}
}
})
how are you doing the post? through a form? @native tide
React frontend, sends a form
post
@app.route('/login')
def login_page():
return render_template('index.html')
@app.route('/api/login', methods=['POST'])
def login():
# TODO: Try/Except return error with required field
req = request.form
login_schema = LoginForm()
req = login_schema.load(req)
user = mdb.users.find_one({'username': req['username']})
if user:
password = req['password'].encode('utf-8')
hashed_password = user['password']
check_password = bcrypt.checkpw(password, hashed_password)
if check_password:
session['username'] = req['username']
print(f"Welcome, {req['username']}")
return redirect(url_for('login_page'))
return redirect('/login')```
the relevant code
what does the login form code look like?
is it just markup? there's no event handlers hooked to it?
tbh I don't really know, not the one working on the frontend. I just know that if I go to /login it serves react the index.html file so that it renders the login page
same with / and /register
it's kind of important to know
because your request log looks fine
like it's being redirected to / on a valid login
Alright then, thank you ๐ Will ask my friend about the frontend part
@pine yew can you assist me now?
@white spruce Sure, let's start by cleaning up your example and clarifying your question
btn.addEventListener('click', e => {
function myFunction(item) {
item.classList.add('square');
}
document.querySelectorAll("#board>div").forEach(myFunction);
var boxElements = document.querySelectorAll('.square'), X_or_O;
boxElements.forEach(square => {
square.addEventListener('click', handleClick, { once: true })
})
function handleClick(e) {
for (var i = 0; i < boxElements.length; i++) {
boxElements[i].onclick = function () {
if (this.innerHTML !== "X" && this.innerHTML !== "O") {
if (X_or_O % 2 === 0) {
console.log("X OR O");
this.innerHTML = 'O';
} else {
console.log("X OR O");
this.innerHTML = 'X';
}
}
}
}
}
})
So you want to flip the Xs and Os?
invert, rather
yeah after each person goes
after working so hard to get my clicks to work. It wanna do me like this lol
was so happy when the click started working ๐
but it's wont invert
so, a note, you usually don't want to modify innerHTML ever. try to stick to innerText because it's much safer to use
oh my instructor said I should have used innerHTML to make the appropriate X show
that's the problem with academia, no real-world experience ๐
what does your HTML look like here?
lol, thanks for the tip though, I'll write it down and keep it for future uses
got to work with what he wants for now
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>INFO2180 - Tic-Tac-Toe</title>
<link rel="stylesheet" href="tic-tac-toe.css" />
<script src="tic-tac-toe.js"></script>
</head>
<body>
<h1>Tic <span>-Tac-</span> Toe</h1>
<div id="game">
<div id="status">Move your mouse over a square and click to play an X or an O.</div>
<div id="board">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
<div class="controls">
<button class="btn">New Game</button>
</div>
</div>
</body>
</html>
so the danger of using innerHTML is that the browser will render whatever is in your string. what this means is if you ever take user input, it becomes a potential vulnerability
give me a few to review. In the middle of making dinner!
okay
I see your problem
X_or_O evaluation is always false
var boxElements = document.querySelectorAll('.square'), X_or_O;
@white spruce what are you trying to do with this line? where is X_or_O coming from?
so you never re-assign that variable in your code sample
and your if block always resolves to writing X as a result
figured it out
var boxElements = document.querySelectorAll('.square'), X_or_O = 0;
boxElements.forEach(square => {
square.addEventListener('click', handleClick, {once: true})
})
function handleClick(e) {
for(var i = 0; i < boxElements.length; i++){
boxElements[i].onclick = function(){
if(this.innerHTML !== "X" && this.innerHTML !== "O"){
if(X_or_O%2 === 0){
console.log("X OR O");
this.innerHTML = 'X';
X_or_O += 1;
}else {
console.log("X OR O");
this.innerHTML = 'O';
X_or_O += 1;
}
}
}
}
}
you see anything wrong?
with what I've done?
nothing wrong, but I'd recommend doing things a little differently
- using
varis kind of out of vogue with the introduction ofletandconstin es6 for (..)loops are also not very common with better idioms such as.forEachand iterator-based lazy approaches- Is counting the X/O the best approach for things? or should you just test each square for inversion?
- multiple assignments on a single line are frowned upon for being hard to read and easy to make mistakes
okay so I'll start off by fixing 4 and 1
re: tests
boxElements.filter((el) => el.innerText)
is an easy way to remove the blanks and guarantee you only have X or O
then you can go further by chaining things together
boxElements
.filter((el) => el.innerText)
.forEach((el) => { el.innerText = el.innerText === 'X' ? 'O' : 'X' };
it makes for more readable code
the reason I do stuff a bit different sometimes is because i'm new
so certain stuff I am not aware of
that's understandable, I'm just giving feedback
I saw someone did that thing
.forEach((el) => { el.innerText = el.innerText === 'X' ? 'O' : 'X' };
but tbh I didn't understand it lol
so I never bothered to use it
so when you use an iterator like this
heyy
the thing you're working on is passed into the argument list
i just wanted to ask a silly thing pls help
(el) is an element from your list of elements
all you're doing is reassigning one of its properties based on what is already there
uk how can we resize the window to check if its responsive withou t resizing the browser ?
check out the Array#forEach documentation on mdn (mozilla document network)
the mdn is a crucial resource for web development on the frontend
to initialize an empty array to keep track of the state of the game after each square is clicked so that I can use it later to check which user has won. Not sure how I go about that part
basically you need to check the matrix for win conditions
you can brute force this by checking if three contiguous squares as filled with one character, the tricky part is checking the cross wins โ
so in your sample, you have an array, 1-9 right? (0-8 when indexing)
0 1 2
3 4 5
6 7 8
you need another array to keep track of the state of this matrix and check it for wins
so if 2, 5, 8 are filled with X, etc.
Xs & Os is easy to brute force, you only have 8 win conditions
so it's a small amount of code
@winter spindle Just some feedback: no clue how to check window responsiveness since it's the thing responsible for running your code so... how could your code possible know, y'know?
still a bit new with arrays so trying to figure out how to do this
so something you could do
collect your boxElements, right?
then have an if condition that tests each win
@pine yew i dont understand what are you saying but still i figured tht out thanks
if (boxElements[0] == 'X' && boxElements[1] == 'X' && boxElements[2] == 'X') {
console.log('X wins!');
}
note: VERY inefficient but hacky/working way to do it
I was planning on storing all the elements in a constant
then checking them with if conditions
for each win
yep, you can do that
that's what I was thinking
he said this, what does he mean
to just initialize an empty array to keep track of the game
not sure what he means
yeah, that's confusing. maybe he means log messages to order the turns?
const turnOrder = [];
turnOrder.push({user: 'X', move: 8})
where 8 = the element array position
I'm taking a minute to eat dinner, but if you have further questions, just @ me
that's what you think he meant
it's a guess, yeah
okay guess ama add that to the code
heyy
@white spruce @pine yew can you guys review my static one page design
https://reverent-leavitt-614d6c.netlify.app/
pls check the bottom icons hover !!
@pine yew when the square is clicked I want to add a class to it to style it. I know what to write to do it
but not sure where it goes
well when I write it in the handleclick function
it gives an error
this is it boxElements.classList.add('square.X');
trying to get the box to change after click
to get the appropriate color
@white spruce classList.add check out the documentation
https://developer.mozilla.org/en-US/docs/Web/API/Element/classList
you want classList.add('square', 'X')
oh yeah, it's just saying it's not reading the property add
because you're working with a collection, probably
you want boxElement[0].classList or similar
not quite
boxElements.forEach((el) => el.classList.add('square', 'X'));
man I'm such a novice, wish he showed us some of those stuff
yeah, the array methods are invaluable
here's a good article to read:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
it's a very good resource
MDN will be your lifeblood if you choose to do web dev
they also have a lot of tutorials if you explore the site
https://css-tricks.com/
another great resource when you get to css stuff
thanks for those resource mean especially MDN
@pine yew
const turnOrder = [];
turnOrder.push({user: 'X', move: 8})
if he said to just initialize an empty array to keep track, I wouldn't need to push to it right?
correct, the first line is initialization, the second is an example of adding to the list in a different spot
ok just making sure
@pine yew I am trying to get this .hover class I have over the grid
boxElements.forEach(function(elem, index, list) {
elem.addEventListener('mouseover', function(e) {
e.target.classList.add('hover');
});
elem.addEventListener('mouseout', function(e) {
e.target.classList.remove('hover');
});
do you see anything wrong with that
that's what I did
I do not; looks good
looks like I am writing it in the wrong place
btw, use \```js to tag your fence with syntax highlighting
not with a backslash
that was a mistake
wasn't I doing that?
boxElements.forEach(function(elem, index, list) {
elem.addEventListener('mouseover', function(e) {
e.target.classList.add('hover');
});
elem.addEventListener('mouseout', function(e) {
e.target.classList.remove('hover');
});
```js
oh damn
I never knew that
oh I see
so if you're using a function handler vs. an arrow function, you can still access the current element using this
boxElements.forEach((el, idx, list) => {
el.addEventListener('mouseover', function() {
this.classList.add('hover');
});
el.addEventListener('mouseout', function() {
this.classList.remove('hover');
});
});
oh so it works but the css breaks something?
it works, just a small issue
of when to set it
for(var i = 0; i < boxElements.length; i++){
boxElements.forEach((el) => el.classList.add('square', 'X'));
boxElements[i].onclick = function(){
if(this.innerHTML !== "X" && this.innerHTML !== "O"){
if(X_or_O%2 === 0){
this.innerHTML = 'X';
X_or_O += 1;
}else {
this.innerHTML = 'O';
X_or_O += 1;
right here I want the first click to start but with the right colors instead of first click being to change the color, any idea?
@pine yew adding the .square.X class when I first click instead of the first click going to waste
so in your click handler
I believe this is the element, in your if block, you can modify the classList
if (X_or_O % 2 === 0) {
this.innerText = 'X';
this.classList.add('X');
X_or_O += 1;
}
I'm stepping away for a bit; DM me if you need further assistance later
correct, so in your else block you'd have a this.classList.add('O')
yeah did that
idk why for some reason this shxt seems to be missing my first click
hopefully he doesn't deduct my marks
you're still setting everything to X in the first line of the for loop ๐คท๐ผโโ๏ธ
ping me your full code sample and I'll check it out when I get back, should only be an hour or so
okay, appreciate the assistance
pinged you @pine yew so whenever you back you can check
hmmm what is the most recommended way to check if a requests request was successful or not? Do people always do
r = request.get()
if not r.status_code == 200:
raise
#continue logic
hmmm what is the most recommended way to check if a requests request was successful or not? Do people always do
r = request.get() if not r.status_code == 200: raise #continue logic
@daring pollen define "successful"
if you mean "2xx" code, then // 100 and check if it's equal to 2
(which is the most common understanding of successful, I guess)
@daring pollen if not r.ok is the paradigm usually
ok should be True if the code is <400
yeah that sounds good to me
do people usually put retry logic in there? I can see how things get really complicated trying to identify what was the issue and to make sure the code is still successful
hah well if my company could answer that I'd be golden, problem is they just see my work as magic ;P
hi. Using Django Rest API I can build a paged response which is awesome. However, I have to instead of returning a response like {...,results:[{...},{...},...]} I have to return a paged response looking like this: {...,results:{'ModelA':{0:{...},1:...},'ModelB':{0:{...},1:...},'ModelC':{0:{...},1:...}}}, where the paging is done on the modelA results. Transforming response from list to dict i do using this: https://dpaste.org/hTw5 But how do i ensure that the paging is done on modelA?
@silver shell can you elaborate your question?
@stable kite yes of course. which part?
But how do i ensure that the paging is done on modelA
well because normally the queryset is a list, and now i suddenly have a a response which is a dict, so i guess i somehow need to modify how the paging is being done
@silver shell you can use django inbuilt function for that
https://docs.djangoproject.com/en/3.1/topics/serialization/#serialization-formats-json
for converting Querset to json
how are you doing paging?
by subclassing generics.ListAPIView
When I make changes in my css file, the django server does not show those changes at all, sometimes it takes long to show those changes. Why does this happen?
yes that worked thank you!
@silver shell check this out it may help you
https://www.django-rest-framework.org/api-guide/pagination/
Django, API, REST, Pagination
flask or django are good options
django is best for sure
flask is good for small POC things...but use django for real stuff
started with Django. and i have a small doubt. is it correct to say that an django app is a section of a website. for example if I am making a website for a college, admissions section will be a separate app and contact us will be another app ?
in django terminology yes
does anyone know why jinja is not working with html?? i use django framework
you are following CoreyMS ?
yep @red pine
just started that but dont know why its not working ??Do u know how to do it?? @red pine
can you post your code ? a little more than the screenshot
its the 3rd video's code
im following the exact tutorial as shown in his video but on mine its not working @red pine
checking
Situation: simple python program that has a client and a server (using sockets) for a game. I want to use SSL to encrypt the data so people cant sniff the content. The server should be able to run everywhere: not only on my machine. I have a self-signed certificate alongside the program, and I can communicate just fine if I use "context.check_hostname = False" on the client. Is this the proper/normal way to do this, or is there a better way?
see in the screenshot you are doing for post in posts but on line 8 you are doing posts.title instead of post.title
did those changes but didnt work @red pine
its showing blank screen
also its not showing in source code part
dont know where i messed up
this is my views.py
{% block content %}
{% endblock content %}``` dont you require these ?
umm he didnt use those in his videos
You called the context 'post', but ask for 'posts' when iterating over it
since posts is empty: you dont see anything
try putting the for loop inside blocks
ahhh okay
i dont think this will work because you have not created a template html page yet right ?
alright
it correct right?? @red pine
or do i have to worry about font style
coz its not same
everything looks in <h1> tag
you have not closed the h1 properly on line 8
in fact you have not closed the p tags as well
woo nice i started yesterday
Using the following in Django will give the last 5 objects in the table:
queryset.order_by('-id')[:5]
Is it possible to start from a certain last id and get the 5 after that. So like if you go to the next page you will get the next 5
@sullen basalt use the filter method
@sullen basalt py model.objects.filter(id__gte=10).order_by('-id')[:5]
Hi, i am using this example, but how can i change it so that on mobile each product is stacked 2 per row? https://mdbootstrap.com/docs/jquery/ecommerce/design-blocks/shopping-cart/#!
@stable kite Found out I can do this using Pagination and that makes it way easier
Hello,
I have a Flask webapp which calculates travel times between events in Google Calendar. The calculation process itself can take up to 60 seconds. This sadly triggers Heroku's worker timeout of 30 seconds.
How can I move this process into the background so that the worker stays alive? What module would you recommend?
@sullen basalt yes Pagination is more easier
Can I get some feedback on this dropdown?
Hi
Anybody here knows PHP?
Can someone check my PHP code?
I have an issue and I didn't found big PHP server on discord as yours ๐
@marble carbon I know
But I didn't found PHP server on discord
Hey, how can I use mysql-connector-python as the database for django? (I'm not sure if I'm using the right terminology here)
I've pip installed mysql-connector (v8.0.21) (Django v3.1.2)
It says
Try using 'django.db.backends.XXX', where XXX is one of:
'mysql', 'oracle', 'postgresql', 'sqlite3'
``` when I pass `mysql.connector.django` as the `'engine'` in settings.py
Is there any way I can use connector though?
It's for a school project and I'm sort of forced to use stuff we've been taught
@gray lance i think you have procibally use mysqlclient for using django orm
there is error in your settings
check this out
๐ค it says it may not support the latest release of django
could this be the problem?
which package gives you this warning?
nvm I installed mysqlclient, thanks :D
ok
I'm not sure really
Hello, Anyone here know how to check if the reason a post_save signal was triggered was do to a delete()
im a pythoner and started recently coding in html and css i don't know why i can't link my css doc with my html doc can anyone help me on this?
I tried this <link rel="stylesheet" href="1owebsite.css"> @devout coral
You using django?
Ok, can you show me the project structure?
the css file is in the same directory as the html file?
imma show u
The html doc
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="1owebsite.css">
</head>
<body>
<h1>3 ting du mรฅ vite om Nettverk</h1>
<p>
<br>
<br>
<br>
<br>
<strong>Kort om nettverk</strong> <br>
Et nettverk er en samling av forskjellige enheter som er koblet til hverandre til รฅ dele data.<br>
Eksempel pรฅ Nettverk er Internett der millioner av enheter er koblet seg sammen til hverandre.<br>
Et bilde <b>
</p>
</body>
</html>
The CSS doc
body {
background-color: bisque;
}
```
@devout coral
Is that css file in the same directory as the html file?
what's the most secure way to store encryption keys & secret key of a django app?
Do you guys know what serializer actually means in this context in DRF? Is it translating JSON content into python code?

you didn't even ask the right thing
i was asking for source code
3 times
2 in another channel
why did you make me suffer
sorry !
someone can help? thats not show me the site!!
@orchid pond why u running flask on repl when you can easily use vscode or pycharm
but can you help?\
It's hard to use flask on reply because u need to change up some setting and you need to install flask package in repl
But why u using repl?
how I do that
okkkk
Just download vscode
how I host the bot from: notepad++
they're just trying to use it for a free host which it isnt designed for
@orchid pond run it... with python?
yeah
run it... with python...
with cmd write: python and then the name of file
Use Heroku or pythoneverywhere
Why
they are NOT bot hosts
@orchid pond you aren't calling run()
Hmm
Does anyone have experience with DRF and serializers
what?
@native tide some what about them?
@quick cargo My question is... what does a serializer even do? Convert JSON to Python code? I don't know.
@orchid pond you aren't calling run()
@native tide so...
@native tide pretty much
Oh ok ๐
its purpose is to be the converter between the two types
so it generally will turn python things into json and vice versa depending on what its designed todo
I have an API and it seems to convert between JSON and data in a python model... but it kinda knows itself what to translate into
@orchid pond I don't understand what you're trying to ask if you say "so...". I didn't understand the 1st time so repeating the exact same thing surely won't change anything
Ooh getting into these REST APIs is actually really enjoyable
lol
funny
lmao I always hear stuff about GraphQL either people love it with a passion or think it's the devil reincarnate
Does anyone knows how to change the request.POST?
request.POST.__setitem__(key="email", value=email)
AttributeError: This QueryDict instance is immutable
or -
I need to add a form to a request or create a new POST request with a form
@frank nebula can you do request.data["email"] = email?
class UserSerializer(ModelSerializer):
class Meta:
model = Users # Don't forget that in the Meta class, we need a model and its fields.
fields = ["username", "email", "hashed_password"] # __all__ is a shorthand for all of the model's fields.
btw does my fields have to correspond to the fields in my model? Can they be different?
So you are working with an API? @frank nebula
yes
This is django right
validated_email = email
form = PasswordResetView.form_class({"email" : email})
form.is_valid()
##Need to insert the form into request
PasswordResetView.as_view(request)
What's your API view?
class PasswordReset(APIView):
Hmm... the only way I know how to do it... is making a view like this (with the decorator):
@api_view(["POST])
def PasswordReset(request):
request.data["key"] # Because the request.data is a dictionary
Then you can manipulate the request data
So you can send the data from your form into your API view and then manipulate it
the thing is, this View needs a form to be validated, the frontend is sending the email in a JSON format, i need to transform this to a form and append to the request
all you have to do is pass the post data to the form.
@login_required
def notification_settings(request):
if request.method == 'POST':
form = NotificationSettings(data=request.POST, instance=request.user)
if form.is_valid():
form.save()
return redirect('main-home')
else:
form = NotificationSettings(instance=request.user)
return render(request, 'employees/notification_settings.html', {'form': form})
That is an example of a view from my project.
@frank nebula
Ok, so just do form.is_valid() in your form view?
I don't fully understand what it needs to do here
I think he wants a form with his post data.
All he needs for that is to pass the post data when initializing the form.
Question, I currently have a view that handles the exporting of some information from my database as pdf. I made a py file inside my app called helper_functions.py to handle all these functions (that query the database for the needed things and create the pdf). Then they return the file object and the view returns it. I was wondering if this is alright or if I should have them elsewhere. I was first thinking of putting them in the models but then I would need to have a model object to call it. Not really sure what to do.
Hello! I am trying to override a property in one of my Django models, but everything still just returns "Question". Does anyone know how I can correctly override properties?
class Question(models.Model):
text = models.TextField()
image = models.ImageField(blank=True)
section = models.ForeignKey(Section, on_delete=models.CASCADE)
number = models.IntegerField(default=0)
manual_grading = models.BooleanField()
@property
def questionType(self):
return 'Question'
class FreeResponseQuestion(Question):
correct_choice = models.CharField(max_length=200, blank=True)
@Question.questionType.getter
def questionType(self):
return 'FreeResponseQuestion'
@loud zephyr have you done makemigrations and migrate?
no changes detected since questionType is not a models object
@loud zephyr How are you trying to change a property?
@devout coral Well, I have a view that shows a list of questions. It includes MultipleChoiceQuestions, FreeResponseQuestions, and a few more. I'm trying to use a for loop like this {% for question in questions %} and I want each question to display the type of question that it is, but the problem is I don't know how to get the type of question if I just do {% for question in questions %}
oh just do.
{% for question in questions %}
{{ question.questionType }}
{% endfor %}
@loud zephyr
@devout coral I do, right here <p class="article-content">{{ question.questionType }}</p> The problem is questionType is always 'Question'. It doesn't get overwritten
Yeah I think you should probably be doing a charfield with a choice on the Question model as opposed to doing what you are doing
class Counseling(models.Model):
ACTION_CHOICES = [
('0', 'Verbal Counseling'),
('1', 'Verbal Warning'),
('2', 'First Written Warning Notice'),
('3', 'Final Written Warning Notice & 3 Day Suspension'),
('4', 'Last & Final Warning'),
('5', 'Discharge for \"Just Cause\"'),
('6', 'Administrative Removal from Service'),
]
action_type = models.CharField(max_length=40, choices=ACTION_CHOICES)
Like this
I don't want the user to have to manually choose that though
How
@devout coral I'm making a test website. What I want to do is display a list of questions that inherit from the Question class. I want to be able to render multiple choice questions, free response, etc all under the same for loop. In order for me to do that, I need to be able to check which child of Question I'm dealing with. For Free response, I render a blank text field. For multiple choice, I render radio buttons
How do I check which "child" of Question I'm dealing with in a for loop?
That is my basic problem
does anyone know how to make a download button?
in html
@umbral gust
can you help?
lmao, you can literally google that question
Hi, I am trying to create a python web scraper using requests but unfortunately, the website I am trying to scrape is protected by Incapsula. I found this GitHub https://github.com/ziplokk1/incapsula-cracker-py3 but the code appears to be out of date and doesn't work anymore. Does anyone know how to bypass incapsulate with Python requests?
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.
sorry
no worries
didn't realize this broke any rules
yeah, I do not think any one minds the mistake as long as you do not push it. haha
but we wont be able to help you.
Hi
anyone can help me?
@acoustic oyster are you still there?
please ping me if anyone can help please
@native tide w3schools has some good guides. Follow one of those, then come back if you hit a wall or have a specific question please. This is a broad topic with many levels.
Get all your html in place and do all you can with docs and guides, then come ask when you have a more specific question.
ok
I already have a question though
how do I make a download button in html?
@acoustic oyster
oops
sorry for the ping
@manic frost do you know html?
@native tide do you know html?
Brooo
???
Stop pinging random people you see online for no reason
you're going to get banned....
oh ok

ok let me delete them
@acoustic oyster I'd recommend pointing people at the mdn tutorials over w3schools. Higher quality, natural progression to reading good documentation
lol
delete pings, even worse
I already did
coz ghost pings
oh
F
I didn't delete them yet
keep them there
just ask
I kinda need help
download attribute anchor tag html
ok
https://www.w3schools.com/tags/att_a_download.asp
HTML a download Attribute - W3Schools
How do I make a download button without using a hyperlink though
I already went to that site before
hmm
what are you trying to do?
XY problem
ahh
well image has a src obv, doesn't it
the image is the download Button?
so use that...
@native tide just create a link and style it to look like button
how do I style?
I haven't styled before
except for color
and I don't know how to color buttons yet
how do I make a download button in html?
@native tide ```<button class="button">Download</button>
but that only says button
wtf
doesn't trigger a download
๐
I'm busy, sorry haha. I do not totally understand which part you have a question about
I need a download button that doesn't look like it has a hyperlink in it

The download aspect is handled on the backend if you are downloading from a server, or you can add an href target __blank to a download server
???
just style it using css
I need a download button that doesn't look like it has a hyperlink in it
@native tide
idk how to
... look it up??
ok
okay ... I got this
???
"styling buttons using css"
That is javascript then, you need a function that runs onclick()
yeah there are so many options, you need to use just one
i don't use java script
god
I will just use css
If you are using djsngo or flask on the backend, then you need to set up the backend first
here here ๐
๐
go. read.
Bro you probably need to learn basic css
i doubt he's written any
same
I can post my html code
Hello
I'm using Selenium to check if there are any new posts within a class on the Edsby website and, if there are, click "like" on them
When a new post is made, it does not appear without reloading the page, rather, a notification appears saying "There are X new posts"
Once you reload the page, the posts appear
To avoid reloading the page every 5 seconds to check for new posts, I'm instead detecting when the "new posts" notification appears
However, I've run into a problem
For reference, here is the site
I've blacked out any personal information
Here is the HTML structure I'm having trouble with
we cannot help you if you black out your personal information - _-
joking aside, what's the error?
Lol
So
to provide context
There is a list of items whose class names begin with xds-feeds-feedItem
Those can be located at the bottom
each of those is one entire "post"
within the edsby page
Now, the part highlighted is what's giving me trouble
There are two extremely similar pieces of HTML that both represent a "There are X new posts" notification
One is highlighted, the other can be found a few lines below the first one
I believe that notification is clickable?
yes, it is
This would be easy to troubleshoot if I had a genuine Edsby "new posts" notification
From an actual post
there's two different IDs
Yeah, the IDs are different
I'm just confused about which one I should be looking at, if I want to detect when there's a new post
I'm not good at HTML or any form of web development, so this next question may seem dumb:
how about u use the website as a user, and when it appears, inspect it
and click on it while you're still inspecting
Is it possible to see the code that makes this item change from hidden to unhidden?
See, the problem is, edsby has a really janky timeout system, and it would require me to wait a day or two for a new post to be made
I'm just wondering if I can, using the chrome console, see the code that causes the notification item to become unhidden
when a new post is made
it depends whether they have left any console log statements in their code
or you can simply
check the javascript files attached on that page by doing view source
and search for the IDs
"sources" tab?
chrome?
does anyone know atom the text editor here?
that'll highlight the script tags for u
Hmm
Hey can anyone suggest me best Quiz provider for my Django-React application ?
I don't think the source code provided by Ctrl + U is what makes the site tick
this is the body:
i cant really tell without having access to site tbh
I am just throwing possible solutions that I can think of
I'll poke around the source code for a minute
What tool?
a sec
Install the Wappalyzer browser extension to see the technologies used on websites you visit at a glance.
Okay I found the "core" source code
this one and see if it is using any JavaScript framework on the page you're looking at
hmm seems like webpack, idk it would be better to find out which client side framework it is using, and modify the approach according to that
