#web-development

2 messages ยท Page 99 of 1

white spruce
#

for the longest

marble carbon
#

Okay but

#

I literally explained u why it isn't working

#

๐Ÿคจ

#

If there's a doubt, feel free to ask

white spruce
#

okay

#

I am just having some issues with the function

#

to add

#

not sure where to begin with that part

marble carbon
#

okay hmm wait, do u know how functions have return types?

white spruce
#

yeah

stable kite
#

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

marble carbon
#

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

white spruce
#

I get that part

#

I think what I am confused about it writing the function

marble carbon
#

I gave you a link

white spruce
#

resend

#

oh found it

marble carbon
#

okay did u study arrays yet?

#

because if u did, then you might have already studied what i sent

white spruce
#

yeah I did

marble carbon
#

Okay then, u got ur solution

white spruce
#
  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

marble carbon
#

Well

#

that function recieves only one argument

#

that is the element

white spruce
#

you mean it's only sending one element to the function at a time/?

marble carbon
#

yep, you Don't have to iterate ur self

white spruce
#

oh the function isn't necessary then

marble carbon
#

it is like this : for Each element, run this function

#

no, you need the function

versed lotus
#

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

white spruce
#

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

versed lotus
#

do you want to add a class to all child-divs of #board?

white spruce
#

yeah

#

so that all the divs

#

can have the style

versed lotus
#
function myFunction(item) {
  item.classList.add('the-class');
}
white spruce
#

to make the 9 grids

versed lotus
#

then something like that

#

each "item" is going to be a div from your querySelectorAll result

white spruce
#

okay I think I am king understanding now

versed lotus
#

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.

marble carbon
#

uh it's for an assignment ๐Ÿ‘€

versed lotus
#

oh well

white spruce
#

thanks for teaching me that Sani

#

@versed lotus cmon

#

it's not like I wasn't trying

#

@marble carbon cmon

marble carbon
#

man

#

it's for your learning, that's why I wasn't giving exact code

white spruce
#

but he never gave exact

marble carbon
#

kinda

white spruce
#

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

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

white spruce
#

The helpers should have a donate button like @versed lotus

native tide
#

If so, is it then being appended into an object for the model?

white spruce
#

like a tip button or something like that

versed lotus
#

have you tried printing it? print(type(request.data), request.data)

#

no idea what LeadSerializer is though

native tide
#

I don't exactly know how I can print that, as request will be a PUT request to the api.

#

LeadSerializer is a ModelSerializer

lavish prismBOT
#

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.

native tide
#

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.

versed python
#

are your other static files being imported correctly?

native tide
#

this is the only static file so far, as this is a new project

topaz widget
#

@native tide Do you have load static at the top of your template?

native tide
#

I do

topaz widget
#

{% load static %} to be precise

native tide
#

INSTALLED_APPS = [ .... 'django.contrib.staticfiles', 'frontend' ]

topaz widget
#

Have you run the collecstatic command?

native tide
#

I have not

topaz widget
#

hol up

native tide
#

I'm reading that rn on my other screen

topaz widget
#

Was this file working before, you made updates, and now the updates aren't showing?

native tide
#

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

topaz widget
#

ok nevermind then

native tide
#

so its all stock settings in settings.py

topaz widget
#

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.

native tide
#

what does that do?

topaz widget
#

It prevents browser caching from not registering changes to the css file

#

because it forces it to load a new one.

native tide
#

oh thats very useful, thanks for letting me know

topaz widget
#

Do that after every static file.

#

href="{% static 'blahblah.css' %}?{% now 'U' %}"

#

and also for scripts as:

#

src="{% static 'blahblah.js' %}?{% now 'U' %}"

native tide
#

awesome, thanks

topaz widget
#

do you have a static root?

native tide
#

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

topaz widget
#

STATIC_ROOT =

#

You need a static root for the development server

native tide
#

I'm still here, reading into it

#

that did it.

#

STATIC_ROOT = '' magically made it work

topaz widget
#

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.

native tide
#

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

topaz widget
#

pretty sure, yeah

#

Here's what I have:

#

STATIC_ROOT = os.path.join(BASE_DIR, 'static')

native tide
#

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

topaz widget
#

Yeah, just copy and paste what I wrote into your settings.py file in place of the empty string.

native tide
#

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

topaz widget
#

I don't know why it works, just that it works.

native tide
#

lol no problem

#

thank you very much for your help

topaz widget
#

sure

native tide
#

I'll remember this going forwards

topaz widget
#

are you going to be serving static files from your database, too?

#

aka "media" files.

stable kite
#

@topaz widget media files are not served through database

#

in database links of media are stored

topaz widget
#

They are referenced from the database.

stable kite
#

yes

topaz widget
#

I was imprecise in my language, I know they're not stored there.

stable kite
#

ok lol

native tide
#

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

topaz widget
#

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

native tide
#

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

topaz widget
#

ah ok

native tide
#

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

topaz widget
#

good deal

native tide
#

this helped me a lot, thank you again

topaz widget
#

yw

near bison
#

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

native tide
#

@near bison 100% bootstrap

near bison
#

That what you do ?

native tide
#

yes

#

you simply load the css file, and it gives you a ton of css classes to plug in

near bison
#

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 ?

native tide
#

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

near bison
#

Thanks

native tide
#

๐Ÿ‘

topaz widget
#

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

native tide
#

not a fan of bootstrap? lol

topaz widget
#

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.

native tide
#

yeah. could you say why? I'm not arguing, just curious on your perspective

topaz widget
#

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.

native tide
#

thats fair

#

I learned bootstrap before css

topaz widget
#

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)

native tide
#

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.

topaz widget
#

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.

native tide
#

which is exactly what I'm doing now, so hearing that reaffirms I'm making the right choice lol

topaz widget
#

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.

cerulean otter
#

anyone use redux :)?

stable kite
#

@cerulean otter yes i did

nova nacelle
#

@bronze oak

native tide
#

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?

versed python
#

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

modest scaffold
#

@marble carbon thanks ill try this

glad patrol
#

hi i need help

#

@stable kite

#

how to add speedometer or gauge to monitor host usage in html.

topaz finch
#

Any tips for allowing my Flask app to serve JSON responses faster?

@ me when answering please.

stable kite
#

@glad patrol can you elaborate your question

glad patrol
#

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

topaz finch
#

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.

native tide
#

is Django + React common?

stable kite
#

@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

native tide
#

Yeah I'm currently trying to make a Django + React app utilizing APIs. Hopefully it'll be a good project ๐Ÿ˜‰

stable kite
#

@topaz finch it will be in your html code so

wise crescent
#

Hi, I'm learning Django. I got an issue as shown in the picture below

stable kite
#

the module is not found

wise crescent
#

does anyone know why it says the file is not found after I ran runserver?

stable kite
#

name your app correctly

#

@wise crescent you have use personal.views & not design_hub.personal.view

wise crescent
#

it shows error if I only put personal.views

stable kite
#

on line 19

#

no it wouldn't

wise crescent
stable kite
#

@wise crescent just try to run your server

#

in which directory is this file located?

wise crescent
stable kite
wise crescent
#

sure

stable kite
#

in which directory is this file located?
@wise crescent ??

#

@wise crescent which Django version are you using?

wise crescent
#

oh I get it, I added the name in MIDDLEWARE but not the INSTALLED_APPS๐Ÿ˜…

#

thanks, it works now

stable kite
#

no problem

wise crescent
#

sorry for the stupid question

native tide
#

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?

stable kite
#

@native tide just check if user requesting this page is a staff member then return the page & if not then render a different page

versed python
#

^ along with django view level permission will be enough

dapper tusk
#

@topaz finch browsers always ask for a favicon

near bison
#

How does signUp email verification work in websites

quiet comet
#

in django how can i get the raw sql changed data in a UPDATE?

jolly matrix
#

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

native tide
#

are static files usually front end or back end job

trim star
#

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

warm igloo
#

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.

trim star
#

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?

marble carbon
#

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

trim star
#

Yes I mean the web server portion that is serving the application

marble carbon
#

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

trim star
#

Ok. I meant that i thought apache is better for serving the application..or nginx too

marble carbon
#

watch this, you'll understand the layers

trim star
#

Awesome, I will look at this too

marble carbon
#

how an app is served in production

#

๐Ÿ‘

trim star
#

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

marble carbon
#

Uhm Django doesn't comme with a production scale server

#

only a development server, which should not be used in production itself

trim star
#

yeah thats why I was saying before that I heard django isnt good for production

marble carbon
#

they instead provide an interface, that is the WSGi

trim star
#

Ah ok

marble carbon
#

Django can still be used in production

#

just not on its own

trim star
#

Ah ok. Thanks for explaining

native tide
#

someone willing to give me feedback on my website

jolly matrix
vapid acorn
#

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?

versed python
#

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
#

@topaz finch browsers always ask for a favicon
@dapper tusk But there is no html being sent, only the dictionary.

versed python
#

As for your question here's how I would approach it.

  1. Sign up user (using a custom user model as defined below) and insert relevant record to db.
  2. Create a model called UserUploadedImage with definition as below:
class CustomUser(AbstractUser):
  images = models.ManyToManyField('appname.UserUploadedImage')
  # etc
class UserUploadedImage(models.model):
  image = models.ImageField()
  # etc
  1. When a user uploads a new image, I'd create a new UserUploadedImage instance and associate it with the currently logged in user.
dapper tusk
#

yes, but browsers ask for a favicon anyway

versed python
#

@vapid acorn

dapper tusk
#

maybe there is a header you can send to make it not ask for one

vapid acorn
#

@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

versed python
#

Ah well that makes more sense

topaz finch
#

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.

vapid acorn
#

So is there a better solution then having one gigantic pictures list?

versed python
#

I just gave you a solution ๐Ÿ˜

native tide
#

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
#

hello

#

wait

#

ill let the other guy ask

#

before i ask

stable kite
#

@native tide who other guy is?

native tide
#

i want to get ist of courses with these filters (specific student, teacher, time range)

stable kite
#

whats the problem in that @native tide

native tide
#

how should i implement that in my api

#

my mind is broken

stable kite
#

are you using any framework?

native tide
#

no just by requests package

stable kite
#

where are you getting data from?

native tide
#

postman

stable kite
#

It's an API package

loud mountain
#

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?

stable kite
#

@native tide it doesn't have data stored in it

loud mountain
#

using bottle btw

native tide
#

@native tide it doesn't have data stored in it
@stable kite icant get y

stable kite
#

@loud mountain no idea about bottle sorry

#

@native tide like database or something else

native tide
#

@native tide like database or something else
@stable kite aha its h2

stable kite
#

what is h2?

native tide
#

like memcache

#

in memory database

stable kite
#

then you have to use javascript for that

#

i think so

#

memchache means local db?

#

right?

native tide
#

javaxcript for front ?

stable kite
#

memchache means local db?

native tide
#

nearly

stable kite
#

javaxcript for front ?
@native tide yes

#

because you can't access memchache with python as far i think so

native tide
#

@native tide yes
@stable kite idonr need front at the momnent i m just calling it by postman

white spruce
#
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?

vapid acorn
#

@versed python now I see your solution, thank you

tepid lark
#

@white spruce What's happening with your code now?

white spruce
#

got it fix @tepid lark

#

appreciate the help

tepid lark
#

Yay!

native tide
#

Hello

#

Can I ask a quick flask question?

pine yew
#

shoot

native tide
#
@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')```
pine yew
#

I'm assuming you're using marshmallow and sqla there?

native tide
#

marshmallow and pymongo

pine yew
#

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

native tide
#

directly?

pine yew
#

yep

native tide
#

I thought you needed url_for

pine yew
#

uh, yes

#

redirect(url_for('login'))

native tide
#

just a sec please

pine yew
#

I'm hanging around

native tide
#

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

white spruce
#

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

        }

  })
pine yew
#

how are you doing the post? through a form? @native tide

native tide
#

React frontend, sends a form

pine yew
#

okay, but how are you calling the endpoint?

#

through fetch or through a form action?

native tide
#

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
pine yew
#

what does the login form code look like?

#

is it just markup? there's no event handlers hooked to it?

native tide
#

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

pine yew
#

it's kind of important to know

#

because your request log looks fine

#

like it's being redirected to / on a valid login

native tide
#

Alright then, thank you ๐Ÿ™‚ Will ask my friend about the frontend part

white spruce
#

@pine yew can you assist me now?

pine yew
#

@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

white spruce
#

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

pine yew
#

so, a note, you usually don't want to modify innerHTML ever. try to stick to innerText because it's much safer to use

white spruce
#

oh my instructor said I should have used innerHTML to make the appropriate X show

pine yew
#

that's the problem with academia, no real-world experience ๐Ÿ˜…

#

what does your HTML look like here?

white spruce
#

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>
pine yew
#

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

white spruce
#

oh I see

#

we not allowed to touch our html either

#

nor css

pine yew
#

give me a few to review. In the middle of making dinner!

white spruce
#

okay

pine yew
#

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?

white spruce
#

var boxElements = document.querySelectorAll('.square'), X_or_O = 0;

#

my bad

pine yew
#

so you never re-assign that variable in your code sample

#

and your if block always resolves to writing X as a result

white spruce
#

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?

pine yew
#

nothing wrong, but I'd recommend doing things a little differently

white spruce
#

what would you recommend

#

I'll see if I can make the changes

pine yew
#
  1. using var is kind of out of vogue with the introduction of let and const in es6
  2. for (..) loops are also not very common with better idioms such as .forEach and iterator-based lazy approaches
  3. Is counting the X/O the best approach for things? or should you just test each square for inversion?
#
  1. multiple assignments on a single line are frowned upon for being hard to read and easy to make mistakes
white spruce
#

okay so I'll start off by fixing 4 and 1

pine yew
#

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

white spruce
#

the reason I do stuff a bit different sometimes is because i'm new

#

so certain stuff I am not aware of

pine yew
#

that's understandable, I'm just giving feedback

white spruce
#

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

pine yew
#

so when you use an iterator like this

winter spindle
#

heyy

pine yew
#

the thing you're working on is passed into the argument list

winter spindle
#

i just wanted to ask a silly thing pls help

pine yew
#

(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

winter spindle
#

uk how can we resize the window to check if its responsive withou t resizing the browser ?

white spruce
#

oh okay thanks

#

also instructor asked

pine yew
#

check out the Array#forEach documentation on mdn (mozilla document network)

#

the mdn is a crucial resource for web development on the frontend

white spruce
#

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

pine yew
#

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

white spruce
#

you think I could do sumn like tis

#

this

#

nvm

pine yew
#

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

white spruce
#

still a bit new with arrays so trying to figure out how to do this

pine yew
#

so something you could do

#

collect your boxElements, right?

#

then have an if condition that tests each win

winter spindle
#

@pine yew i dont understand what are you saying but still i figured tht out thanks

pine yew
#
if (boxElements[0] == 'X' && boxElements[1] == 'X' && boxElements[2] == 'X') {
  console.log('X wins!');
}

note: VERY inefficient but hacky/working way to do it

white spruce
#

I was planning on storing all the elements in a constant

#

then checking them with if conditions

#

for each win

pine yew
#

yep, you can do that

white spruce
#

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

pine yew
#

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

white spruce
#

that's what you think he meant

pine yew
#

it's a guess, yeah

white spruce
#

okay guess ama add that to the code

winter spindle
#

heyy

#

@white spruce @pine yew can you guys review my static one page design

white spruce
#

@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

pine yew
#

you want classList.add('square', 'X')

white spruce
#

oh yeah, it's just saying it's not reading the property add

pine yew
#

because you're working with a collection, probably

#

you want boxElement[0].classList or similar

white spruce
#

so ama need that for all the elements in the array

#

damn

#

no shorter ways?

pine yew
#

not quite

boxElements.forEach((el) => el.classList.add('square', 'X'));
white spruce
#

man I'm such a novice, wish he showed us some of those stuff

pine yew
#

yeah, the array methods are invaluable

white spruce
#

also that website breaks stuff down better

#

than WSS

pine yew
#

it's a very good resource

white spruce
#

been using WSS all this time

#

yeah seem to make me understand stuff better

pine yew
#

MDN will be your lifeblood if you choose to do web dev

#

they also have a lot of tutorials if you explore the site

white spruce
#

thanks for those resource mean especially MDN

white spruce
#

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

pine yew
#

correct, the first line is initialization, the second is an example of adding to the list in a different spot

white spruce
#

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

pine yew
#

I do not; looks good

white spruce
#

looks like I am writing it in the wrong place

pine yew
#

btw, use \```js to tag your fence with syntax highlighting

#

not with a backslash

#

that was a mistake

white spruce
#

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

pine yew
#

there you go

#

only need it once

#

after the opening ticks

white spruce
#

oh I see

pine yew
#

so if you're using a function handler vs. an arrow function, you can still access the current element using this

white spruce
#

that code for hover seems to mess up my whole code

#

might need to write sumn else

pine yew
#
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?

white spruce
#

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

pine yew
#

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

white spruce
#

before you go

#

I'd have to add that for the 'O' as well

#

then

pine yew
#

correct, so in your else block you'd have a this.classList.add('O')

white spruce
#

yeah did that

#

idk why for some reason this shxt seems to be missing my first click

#

hopefully he doesn't deduct my marks

pine yew
#

you're still setting everything to X in the first line of the for loop ๐Ÿคท๐Ÿผโ€โ™‚๏ธ

white spruce
#

no I changed that

#

i took it out

pine yew
#

ping me your full code sample and I'll check it out when I get back, should only be an hour or so

white spruce
#

okay, appreciate the assistance

white spruce
#

pinged you @pine yew so whenever you back you can check

daring pollen
#

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
vestal hound
#

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)

pine yew
#

@daring pollen if not r.ok is the paradigm usually

#

ok should be True if the code is <400

vestal hound
#

oh, hm, I didn't know that was a thing

#

yeah, that sounds better

daring pollen
#

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

pine yew
#

it depends on what your needs are

#

only you can answer that really

daring pollen
#

hah well if my company could answer that I'd be golden, problem is they just see my work as magic ;P

silver shell
#

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?

stable kite
#

@silver shell can you elaborate your question?

silver shell
#

@stable kite yes of course. which part?

stable kite
#

But how do i ensure that the paging is done on modelA

silver shell
#

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

stable kite
#

for converting Querset to json

#

how are you doing paging?

silver shell
#

by subclassing generics.ListAPIView

jolly matrix
#

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?

marble carbon
#

open devtools

#

go to network tab

#

check disable cache

#

@jolly matrix

jolly matrix
#

yes that worked thank you!

stable kite
green python
#

what framework is best for a python pro coming to web dev.

#

plz tell

#

noone helps

marsh canyon
#

flask or django are good options

green python
#

ok

#

i just assume real python tutorials cover them fully and thank you for help

silver shell
#

django is best for sure

#

flask is good for small POC things...but use django for real stuff

red pine
#

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 ?

versed python
#

in django terminology yes

native tide
red pine
#

you are following CoreyMS ?

native tide
#

yep @red pine

#

just started that but dont know why its not working ??Do u know how to do it?? @red pine

red pine
#

can you post your code ? a little more than the screenshot

native tide
#

its the 3rd video's code

#

im following the exact tutorial as shown in his video but on mine its not working @red pine

red pine
#

checking

hot swallow
#

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?

red pine
#

ignore

native tide
red pine
#

see in the screenshot you are doing for post in posts but on line 8 you are doing posts.title instead of post.title

native tide
#

did those changes but didnt work @red pine

#

its showing blank screen

#

dont know where i messed up

red pine
#
{% block content %}
{% endblock content %}``` dont you require these ?
native tide
#

umm he didnt use those in his videos

hot swallow
#

You called the context 'post', but ask for 'posts' when iterating over it

#

since posts is empty: you dont see anything

red pine
#

try putting the for loop inside blocks

native tide
#

ahhh okay

red pine
#

i dont think this will work because you have not created a template html page yet right ?

native tide
#

i have home.html

#

in templates

red pine
#

can you just change line 22 on views.py to posts=posts instead of context

native tide
#

okay lemme try that

red pine
#

alright

native tide
#

it correct right?? @red pine

#

or do i have to worry about font style

#

coz its not same

#

everything looks in <h1> tag

red pine
#

you have not closed the h1 properly on line 8

native tide
#

woops my bad

#

sorry

red pine
#

in fact you have not closed the p tags as well

native tide
#

got it

#

thank you for helping ๐Ÿ™‚

red pine
#

no problem

#

i started Django today

native tide
#

woo nice i started yesterday

sullen basalt
#

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

stable kite
#

@sullen basalt use the filter method

#

@sullen basalt py model.objects.filter(id__gte=10).order_by('-id')[:5]

native tide
sullen basalt
#

@stable kite Found out I can do this using Pagination and that makes it way easier

nova crest
#

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?

stable kite
#

@sullen basalt yes Pagination is more easier

devout coral
versed python
#

10/10 would close it

#

add some styles to it

#

maybe a light shadow border

exotic pond
#

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
#

PHP

#

someone might help, but don't really think so since it's a Python server

exotic pond
#

@marble carbon I know
But I didn't found PHP server on discord

marble carbon
#

try asking on r/php

#

maybe

gray lance
#

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
stable kite
#

@gray lance you should use mysqlclient

#

because django support it

gray lance
#

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

stable kite
#

@gray lance i think you have procibally use mysqlclient for using django orm

#

there is error in your settings

#

check this out

gray lance
#

๐Ÿค” it says it may not support the latest release of django
could this be the problem?

stable kite
#

which package gives you this warning?

gray lance
#

nvm I installed mysqlclient, thanks :D

stable kite
#

ok

native tide
#

hi

#

anyone can help me?

#

@gray lance is this channel also for web scraping?

gray lance
#

I'm not sure really

native tide
#

ok

#

but can anyone help me?

devout coral
#

Hello, Anyone here know how to check if the reason a post_save signal was triggered was do to a delete()

sleek flower
#

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?

devout coral
#

What do you have so far?

#

What did you try

sleek flower
#

I tried this <link rel="stylesheet" href="1owebsite.css"> @devout coral

devout coral
#

You using django?

sleek flower
#

no

#

html and csss

#

front end

#

@devout coral

devout coral
#

Ok, can you show me the project structure?

#

the css file is in the same directory as the html file?

sleek flower
#

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

devout coral
#

Is that css file in the same directory as the html file?

sleek flower
#

no

#

bro do you know the issue or not?

ionic idol
#

what's the most secure way to store encryption keys & secret key of a django app?

native tide
#

Do you guys know what serializer actually means in this context in DRF? Is it translating JSON content into python code?

warped mirage
#

guys i need some help

#

i installed django

pure fjord
#

src code?

#

source code please

#

@warped mirage source code

warped mirage
#

oh nvm

#

it worked

#

i was typing the wrong code

marble carbon
pure fjord
#

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

warped mirage
#

sorry !

orchid pond
native tide
#

@orchid pond why u running flask on repl when you can easily use vscode or pycharm

orchid pond
#

but can you help?\

native tide
#

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?

orchid pond
#

how I do that

quick cargo
#

theyre trying to use it for a bot im guessing

#

even though REPL.IT IS NOT A BOT HOST

orchid pond
#

its not write something on the console

#

why

#

How I fix that?

quick cargo
#

pay for a actual host

#

or self host

#

dont use repl.it and dont use heroku

native tide
#

I personally prefer not to use reply.it for flask

orchid pond
#

okkkk

native tide
#

Just download vscode

quick cargo
#

@native tide they're using it to 'ping' repl.it to keep their bot alive

orchid pond
#

how I host the bot from: notepad++

quick cargo
#

they're just trying to use it for a free host which it isnt designed for

#

@orchid pond run it... with python?

orchid pond
#

yeah

quick cargo
#

run it... with python...

orchid pond
#

with cmd write: python and then the name of file

native tide
#

Use Heroku or pythoneverywhere

quick cargo
#

no

#

dont use those

native tide
#

Why

quick cargo
#

they are NOT bot hosts

native tide
#

@orchid pond you aren't calling run()

#

Hmm

#

Does anyone have experience with DRF and serializers

orchid pond
#

@native tide so...

#

\

native tide
#

what?

quick cargo
#

@native tide some what about them?

native tide
#

@quick cargo My question is... what does a serializer even do? Convert JSON to Python code? I don't know.

orchid pond
#

@orchid pond you aren't calling run()
@native tide so...

quick cargo
#

@native tide pretty much

native tide
#

Oh ok ๐Ÿ™‚

quick cargo
#

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

native tide
#

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

native tide
#

Ooh getting into these REST APIs is actually really enjoyable

marble carbon
#

yess

#

once you get into GraphQL it's even more fun

native tide
#

lol

#

funny

#

lmao I always hear stuff about GraphQL either people love it with a passion or think it's the devil reincarnate

frank nebula
#

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

native tide
#

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

frank nebula
#

Humm, i will try.

#

Thats the thing.
I have a to send a valid form to a view

native tide
#

So you are working with an API? @frank nebula

frank nebula
#

yes

native tide
#

This is django right

frank nebula
#
            
            validated_email = email
            form = PasswordResetView.form_class({"email" : email})
            form.is_valid() 
            ##Need to insert the form into request
            PasswordResetView.as_view(request)
native tide
#

What's your API view?

frank nebula
#

class PasswordReset(APIView):

native tide
#

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

frank nebula
#

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

devout coral
#

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

native tide
#

Ok, so just do form.is_valid() in your form view?

#

I don't fully understand what it needs to do here

devout coral
#

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.

loud zephyr
#

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'
devout coral
#

make sure to do .save() after any changes

#

@loud zephyr

loud zephyr
#

@devout coral what?

#

I don't know what you mean

#

model.save()?

native tide
#

@loud zephyr have you done makemigrations and migrate?

loud zephyr
#

no changes detected since questionType is not a models object

devout coral
#

@loud zephyr How are you trying to change a property?

loud zephyr
#

@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 %}

devout coral
#

oh just do.

{% for question in questions %}
  {{ question.questionType }}
{% endfor %}
#

@loud zephyr

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

devout coral
#

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

loud zephyr
#

I don't want the user to have to manually choose that though

devout coral
#

You can set the field for them....

#

No need to have them choose

loud zephyr
#

How

devout coral
#

First, what is it that you are trying to achieve.

#

So I get a better understanding

loud zephyr
#

@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

native tide
#

does anyone know how to make a download button?

#

in html

#

@umbral gust

#

can you help?

pine yew
#

lmao, you can literally google that question

native tide
#

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?

acoustic oyster
#

@native tide sadly this breaks the rules here and we cannot help you.

#

!rule 5

lavish prismBOT
#

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

native tide
#

sorry

acoustic oyster
#

no worries

native tide
#

didn't realize this broke any rules

acoustic oyster
#

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.

native tide
#

Hi

#

anyone can help me?

#

@acoustic oyster are you still there?

#

please ping me if anyone can help please

versed python
acoustic oyster
#

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

native tide
#

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?

marble carbon
#

Brooo

native tide
#

???

marble carbon
#

Stop pinging random people you see online for no reason

#

you're going to get banned....

native tide
#

oh ok

marble carbon
native tide
#

ok let me delete them

pine yew
#

@acoustic oyster I'd recommend pointing people at the mdn tutorials over w3schools. Higher quality, natural progression to reading good documentation

marble carbon
#

noo

#

don't

versed python
#

lol

marble carbon
#

delete pings, even worse

native tide
#

I already did

marble carbon
#

coz ghost pings

native tide
#

oh

versed python
#

F

native tide
#

I didn't delete them yet

versed python
#

keep them there

native tide
#

I was talking to mburzley

#

and do any of you guys know html?

versed python
#

just ask

native tide
#

I kinda need help

marble carbon
#

download attribute anchor tag html

native tide
#

ok

marble carbon
native tide
#

How do I make a download button without using a hyperlink though

#

I already went to that site before

marble carbon
#

hmm

versed python
#

what are you trying to do?

marble carbon
#

XY problem

versed python
#

ahh

native tide
#

make a download button for a image

#

that's what I am trying to do

marble carbon
#

well image has a src obv, doesn't it

versed python
#

the image is the download Button?

native tide
#

no

#

I have another button

versed python
#

so use that...

native tide
#

???

stable kite
#

@native tide just create a link and style it to look like button

native tide
#

how do I style?

#

I haven't styled before

#

except for color

#

and I don't know how to color buttons yet

stable kite
acoustic oyster
#

how do I make a download button in html?
@native tide ```<button class="button">Download</button>

native tide
#

but that only says button

versed python
#

wtf

native tide
#

doesn't trigger a download

versed python
#

he's trolling

#

i think

native tide
#

๐Ÿ˜‘

acoustic oyster
#

I'm busy, sorry haha. I do not totally understand which part you have a question about

versed python
#

none of us have any idea

#

that's why they're not getting the help they want

native tide
#

I need a download button that doesn't look like it has a hyperlink in it

marble carbon
acoustic oyster
#

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

native tide
#

???

versed python
#

just style it using css

I need a download button that doesn't look like it has a hyperlink in it
@native tide

native tide
#

idk how to

versed python
#

... look it up??

native tide
#

ok

marble carbon
#

okay ... I got this

stable kite
native tide
#

???

versed python
#

"styling buttons using css"

acoustic oyster
#

That is javascript then, you need a function that runs onclick()

native tide
#

๐Ÿ˜‘

#

ok

versed python
#

yeah there are so many options, you need to use just one

native tide
#

i don't use java script

versed python
#

god

native tide
#

I will just use css

marble carbon
acoustic oyster
#

If you are using djsngo or flask on the backend, then you need to set up the backend first

marble carbon
#

here here ๐Ÿ‘Œ

native tide
#

๐Ÿ˜

pine yew
#

go. read.

native tide
#

i will use w3school

#

ok

versed python
#

Bro you probably need to learn basic css

marble carbon
#

no, use mdn :)

#

or you could simply post code ?

#

which u never did

versed python
#

i doubt he's written any

marble carbon
#

same

native tide
#

I can post my html code

austere prawn
#

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

versed python
#

we cannot help you if you black out your personal information - _-

#

joking aside, what's the error?

austere prawn
#

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

marble carbon
#

I believe that notification is clickable?

austere prawn
#

yes, it is

#

This would be easy to troubleshoot if I had a genuine Edsby "new posts" notification

#

From an actual post

marble carbon
#

there's two different IDs

austere prawn
#

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:

marble carbon
#

how about u use the website as a user, and when it appears, inspect it

#

and click on it while you're still inspecting

austere prawn
#

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

marble carbon
#

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

austere prawn
#

"sources" tab?

marble carbon
#

chrome?

native tide
#

does anyone know atom the text editor here?

marble carbon
#

Ctrl + U

native tide
#

i need to know how to run the code

#

ok thank you

austere prawn
#

okay

#

I opened the source

marble carbon
#

Ctrl + F

#

<script

austere prawn
#

<script?

#

okay

marble carbon
#

that'll highlight the script tags for u

austere prawn
#

Hmm

golden shore
#

Hey can anyone suggest me best Quiz provider for my Django-React application ?

austere prawn
#

I don't think the source code provided by Ctrl + U is what makes the site tick

#

this is the body:

marble carbon
#

i cant really tell without having access to site tbh

austere prawn
#

but in the Sources tab there's a file tree with other scripts

#

hold on

marble carbon
#

I am just throwing possible solutions that I can think of

austere prawn
#

I'll poke around the source code for a minute

marble carbon
#

this is the body:
@austere prawn uh

#

can u download a tool

austere prawn
#

What tool?

marble carbon
#

a sec

austere prawn
#

Okay I found the "core" source code

marble carbon
#

this one and see if it is using any JavaScript framework on the page you're looking at

austere prawn
#

it definitely is

#

here's the file tree

#

I'm searching for the ID now

marble carbon
#

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