#web-development

2 messages ยท Page 91 of 1

astral musk
#

if I put it at the top of the sub template, it works

umbral echo
#

Hello,
Anyone ever used the Django Scheduler package please? Need a little help because I have no clue of how to display the calendar or even use the package even after reading the doc. Should I just copy/paste the code in there : https://github.com/llazzaro/django-scheduler/tree/develop/schedule or is there another doc somewhere?

marble carbon
#

ah man

#

I have been trying to get it to work myself

#

since yesterday

umbral echo
#

talking about the scheduler @marble carbon ?

marble carbon
#

yea

umbral echo
#

๐Ÿ˜ซ

marble carbon
#

when I include its urls in my config

#

and open the fullcalendar view, it extends the base.html from a different project

#

so it's not working aniblobsweat

umbral echo
#

how weird

zinc hill
#
class Order(models.Model):
    STATUS = (
        ("Pending", "Pending"),
        ("Coming", "Coming"),
        ("Done", "Done"),
    )
    status = models.CharField(
        max_length=200, null=True, choices=STATUS, default=("Pending", "Pending"))

is there a way for me to change the choices in the code? like someorder.status= ("Coming", "Coming")

marble carbon
#

I might just use the interface itself

#

instead of UI

#

@umbral echo do u want the ui or just want to work with creating schedules?

umbral echo
#

I actually wanted to have something that can create schedules, no need of a fancy thing at first

marble carbon
#

ok then

#

I tried to go through the code

umbral echo
marble carbon
#

yea just a sec

#

read the explanation given under each model

umbral echo
#

Ok, i'll get into it ! Thanks a bunch

marble carbon
#

let me know if u get it to work

#

might get ideas from ur code

mortal socket
#

there is anyway to link react pages with Flask/django + routes?

lethal orbit
#

You shouldn't need to add a new file... just add the WSGI lines and the Directory directive to the default file.

#

Also, you should drop the user=user1 group=group1 (or replace it with valid users).

#

In /etc/apache or /etc/apache2/... depends on your distro

#

That depends on your distro

#

Probably something like /etc/apache2/sites-enabled/default

#

sites-enabled is a directory, not a file

#

Probably something like /etc/apache2/sites-enabled/default

#

Then you probably want to add the WSGI information in both of those ๐Ÿ˜„

#

And make sure that mod_wsgi is installed and enabled, of course

#

sudo a2enmod wsgi

#

You need to enable the mod

#

First run grep www /etc/{passwd,group}

#

See if it shows you a www-data user and group, we can use that to run the app, actually.

#
<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    ServerName domain.com
    ServerAlias www.domain.com
    DocumentRoot /var/www/domain.com
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
RewriteEngine on
RewriteCond %{SERVER_NAME} =www.domain.com [OR]
RewriteCond %{SERVER_NAME} =domain.com
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]

    # WSGI Settings
    WSGIDaemonProcess flaskapp user=www-data group=www-data threads=5
    WSGIScriptAlias /flaskapp /var/www/domain.com/flaskapp
    <Directory /var/www/domain.com/flaskapp>
        WSGIProcessGroup flaskapp
        WSGIApplicationGroup %{GLOBAL}
        Require all granted
    </Directory>
</VirtualHost>
#

Just add it within the VirtualHost directive in both those files.

#

domain.com.conf

#

You can add those lines to both

#

Just before you close the </VirtualHost> direcectives in each.

#

Actually, it may not even be necessary in the non-ssl file lol

#

Since it should redirect to SSL anyways.

#

Just add this:

    # WSGI Settings
    WSGIDaemonProcess flaskapp user=www-data group=www-data threads=5
    WSGIScriptAlias /flaskapp /var/www/domain.com/flaskapp
    <Directory /var/www/domain.com/flaskapp>
        WSGIProcessGroup flaskapp
        WSGIApplicationGroup %{GLOBAL}
        Require all granted
    </Directory>
#

right before the </VirtualHost>

#

Do it in the domain.com-le-ssl.conf file first.

#

On new lines after SSLCertificateKeyFile /etc/letsencrypt/live/domain.com/privkey.pem

#

Did you restart apache?

#

sudo service apache2 restart try this

#

sudo chown -R www-data:www-data /var/www/domain.com/flaskapp

#

Odd. You are accessing it over https?

#

WSGIDaemonProcess flaskapp user=www-data group=www-data threads=5 double-check that this line has the correct permissions, and that the www-data user owns the directory and its files.

#

ls -lhaR /var/www/domain.com/flaskapp

#

ls -lh /var/ | grep www

#

oh, sorry

native tide
#

Hi, I'm using @api.resource decorator for endpoint routing in Flask, what I'm not able to figure out is how to accept some parameter in one of the resource methods (e.g. def get(self, task_id)). Is there any other way other than using api.add_resource... ? Thanks

lethal orbit
#

ls -lh /var/www | grep domain

#

Oh, I am an idiot ๐Ÿ˜…

#

WSGIScriptAlias /flaskapp /var/www/domain.com/flaskapp
should be WSGIScriptAlias /flaskapp /var/www/domain.com/flaskapp/myapp.wsgi

#

then restart apache again

#

what's in your /var/www/domain.com/flaskapp/myapp.py ?

#

Change myapp.wsgi to this:

import sys
sys.path.insert(0, '/var/www/domain.com/flaskapp')
from myapp import app as application
#

restart the server

#

but why?
Your app is probably not in the python path :p

#

So it fails to import

#

Yeah

#

You'd have to check the apache log files, then, because fuck if I know what's wrong.

#

Might be the path ...

#

@app.route('/') maybe this should be @app.route('/flaskapp')

#

or @app.route('/flaskapp/')

#

But check the logs

versed python
#

it says no module named flask

lethal orbit
#

ImportError: No module named flask

versed python
#

did you install it?

#

weird

#

did you use a virtual environment or installed it globally?

lethal orbit
#

Um, interesting a myapp.pyc file was generated in var/www/domain.com/flaskapp
That's just python building your code into something closer to machine code for optimization.

#

did you install it as root? with sudo?

native tide
#

I have a question that might be super basic but I cannot figure this out. It seems so simple but I don't know how to continue from here:

I have a list of products that I will display on a products page in the flask app. Based on filters it could be any amount of products from 0 - 4567. I don't know in advance how many products are returned.

in the HTML the Design uses some parallaxes in sets of 6 products and repeats after 6 products. so basically I have also a list of six designs containing these features:

1. Product: data-top-bottom="transform: translateY(-50px);" data-bottom-top="transform: translateY(50px);"
2. Product: data-top-bottom="transform: translateY(100px);" data-bottom-top="transform: translateY(-100px);"
3. Product: data-top-bottom="transform: translateY(-50px);" data-bottom-top="transform: translateY(50px);"
4. Product: data-top-bottom="transform: translateY(50px);" data-bottom-top="transform: translateY(-50px);"
5. Product: data-top-bottom="transform: translateY(-100px);" data-bottom-top="transform: translateY(100px);"
6. Product: data-top-bottom="transform: translateY(50px);" data-bottom-top="transform: translateY(-50px);"
7. Product: repeat from 1. Product
...

How do I map the right html feature to the right product in my list? is it possible to loop (continuously) through two lists in jinja? I mean, i could do something like taking the loop index and see if a division by 6 returns an integer, and then would map the 6th element in the html list to the product, but then again a loop index dividable by 6 is also dividable by 3 ....

#

I feel like the answer is so super simple but I cannot figure this out and even don't know what to google for

#

any suggestions?

lethal orbit
#
import sys
sys.path.insert(0, '/var/www/domain.com/flaskapp')
raise Exception(sys.path)
from myapp import app as application
#

put this in your .wsgi file

#

and check the logs again

versed python
#

that is just bytecode. It is "translated" python into machine readable code.

#

don't bother about it.

#

if you don't want it to appear, you have to use an environment variable "PYTHONDONTWRITEBYTECODE=1"

#

what does the logs say?

lethal orbit
#

Did you run pip3 install to install flask?

#

Apache is using python2.7

versed python
#

sys.path variable shows that apache is executing code using python2

#

read the last line of errors

#

How can I make it use python3?
@native tide normally pip3 install should work

#

I have no idea sorry

lethal orbit
#

try sudo apt-get install libapache2-mod-wsgi-py3

#

maybe xD

#

Nice

#

comment out the raise

#

# raise Exception(sys.path)

#

the .wsgi file

#

add a # before it

#

If it works, you can delete it altogether

charred patio
#

I need help, I wanna make it so when someone opens a new tab it closes all the tabs, for this one project im doing in java script it would mean a lot if someone could help me out with this.

#

Soo yeah if u know how to do this lmk cause i wanna do this.

lethal orbit
#

You can delete the previous logs from the chat if you want to hide your ip lol

#

and I think this is the part where you have to change the path in @app.route

#

If you are now getting a 404

charred patio
#

soo no one gonna help me?

lethal orbit
#

I need help, I wanna make it so when someone opens a new tab it closes all the tabs, for this one project im doing in java script it would mean a lot if someone could help me out with this.
@charred patio you'd have to write a browser extension, I think

charred patio
#

:?????????? i think u can do it in javascript with like 15 lines max of code..

lethal orbit
#

soo no one gonna help me?
@charred patio we don't owe you help. Especially not in the 2 minutes after you ask your question

#

Especially if you are rude about it

charred patio
#

I know you dont owe me help in the time spansion of 2 minutes of me asking the question.

#
  • idk how asking if no one is gonna help me is being rude about it
lethal orbit
#

@lethal orbit Which ones?
@native tide the Apache error logs

#

That you pasted in here

native tide
#

Where is my ip there?

lethal orbit
#

at the beginning of every line it says source IP: port

#

Yeah

#

Just saying you can, for privacy reasons.

#

You don't have to. Seeing as you just pasted it again, you may not care lol

#

This is the user client.

#

Basically, your home IP, or work IP, or mobile phone IP

#

Ok, now try @app.route('/flaskapp) instead in your .py file

#

It logs who is connecting to the server, and the error.

#

When you connect to the server, it opens a connection.

#

If it didn't get your IP, it wouldn't know where to send the reply to.

#

Yeah

#

You might need to restart apache

#

Anything useful in the logs?

#

For the record, It's not a huge deal if people get your IP address. Someone could use it to trace where you live (although not all the way to your house... just country, maybe city).

#

They could also try to hack you. Which is not as easy as movies make it sound.

#

Yeah

#

Don't worry about it

#

Hmmm....

#

odd

#

It doesn't log the 404s.

native tide
#

@lethal orbit

lethal orbit
#

Actually, leave it as app.route("/")

#

And make sure you go to www.domain.com/flaskapp/ with a trailng slash

#

Decades of experience as sysadmin lol

#

WSGIScriptAlias /flaskapp /var/www/domain.com/flaskapp

#

This says "treat www.domain.com/flaskapp as an alias.

#

So it passes everything that comes next to flask

#

I think you might be able to do @app.route("") and add a default view for www.domain.com/flaskapp without a trailing slash.

#

Try it with a different function maybe

#

that returns "you didn't add a slash" :p

lethal orbit
#

Thanks. Why couldn't you have figured this need for only app.route("/") before lol @lethal orbit
Well, that wasn't the original problem.

#

The original problem was the python version.

#

Would have been much faster to troubleshoot if I had access to the server ๐Ÿ™‚

#

And that emoji is me laughing at myself

#

process of elimination

#

and logs

#

raise Exception(sys.path) logged the path as an error...

#

You just try different things.

#

Yeah

versed python
#

and hope to god it works somehow

marble carbon
#

lol

lethal orbit
#

raising exceptions is a great way to print information you need xD

#

Well, I would be working directly on the shell with no middleman :p

#

Sometimes it does.

#

I think 20 minutes tops, and I would have fixed this.

#

But you do need patience for this kind of work xD

#

yeah

#

That I don't know. It was something worth trying.

#

Also gives you a 404?

#

You'd probably have to look into the flask internals to know that.

#

I mean in the flask source code

#

But don't worry about it.

#

This is a case where it's probably easier to just accept that you need a / and move on ๐Ÿ˜„

#

Nope

#

I have looked at Django more. I do a lot more of my work with that than Flask.

#

No, I didn't.

#

I use Arch Linux btw

#

Yeah

#

Ubuntu on server, Arch on Desktop/laptop

#

Now a Lenovo Yoga

versed python
#

everything works on arch

lethal orbit
#

But they pretty much all did

#

The ones I have used in the past.

#

Some might be missing some features.

#

Better than Windows lol

#

Ok, I gotta go.

#

Have to do some offline things.

versed python
#

!resources

lavish prismBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

lethal orbit
#

Work on projects. Find someone to do code reviews (the code jams on this server are good for that). Watch talks by Raymond Hettinger, and Uncle Bob...

#

Watch as many PyCon talks as you can.

#

Work with more experienced devs, if you can.

versed python
#

how does one join a code jam?

#

i dont have permission to send messages there

lethal orbit
#

Check the pydis website. Next one will be in winter.

#

Check the resources page. I usually just refer to the official python docs. It has a tutorial.

#

Kinda DRY, but it's a very solid resource.

#

Yeah

#

Though I may not be the best person to ask.... I've been coding for over 20 years.

#

Kinda DRY, but it's a very solid resource.
@lethal orbit killing it with the jokes today ๐Ÿ˜†

#

Corey Schafer (spelling?) has some highly touted videos, I think.

#

But don't follow tutorials too much.

#

Think of a problem, search for a solution.

#

a monkey could copy/paste code

#

Yeah, they're on youtube

versed python
#

looks like pyweek is only for games

lethal orbit
#

Yeah, that's the one. And yes. pyweek is just for games.

versed python
lethal orbit
#

Prevents the app from being run as a script if it's imported.

#

toodles

versed python
#

watch that video above you'll understand

@lethal orbit O don't understand that.
@native tide

#

lol he Rick rolled you

#

madlad

versed python
#

idk but he did lol

native tide
#

can y'all help me with something basic? I have a flask app that takes a list with n elements (i dont know beforehand how many products are in the list). then i pass it to jinja and need to render the html based on the 1. to 6. child

#

so the first product gets asigned the attribute "one", second "two,..., sixth "six", seventh "one", ...

#

so every sixth element in the list needs to get assigned the attribute six.

#

so far i thought i could use {% if loop.index is divisibleby 6 %} to render the attribute for the element. but 6 is also divisible by 3 and 2 ... even worse 24 is divisible by 6, 3, 2 and 4

#

there must be some way to select nth child element of a list or count from 1-6 continously in a loop until the for loop of the product list breaks.

#

back then i could use {% set count = 1 %} {% for i in p %} {{ count }} {% set count = count + 1 %} {% endfor %}

#

but that doesnt seem to work anymore in the new jinja. it just returns 1 for every element and does not increment

#

also i thought i count the elements in the list and send the count to jinja and doing something like: {% for i in range(1, count, 6): %}

#

but then, how do i access the product dictionaries in my productlist?

lethal orbit
#

so every sixth element in the list needs to get assigned the attribute six.
@native tide maybe try using a modulo? Can you use zero-based indexing?

#

loop.index % 6 ...

native tide
#

well it is not only every sixth element, basically i need to cycle through two lists at a time. I go through a list with lets say 100 products. for each element i need to render an attribute (between 1 and 6) so basically, 1. product: one, 2. product: two, 3. product: three, 4. product: four, 5. product: five, 6. product: six, 7. product: one, 8. product: two, 9. product three, ....

#

so basically i need to count from 1 to 6 and over and over again until i cycled through the whole product list

#

basically i need to be able the 1.-6. child of the loop

lethal orbit
#

basically i need to be able the 1.-6. child of the loop
@native tide that's what modulo does.

>>> print(", ".join(map(str, (i % 6 for i in range(100)))))
0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3
native tide
#

yeah, i just figured it out, thanks for your help

#

this is my solution:

#
                                                     {% if loop.index % 6 == 1 %} {{ one|safe }} {% endif %}
                                                     {% if loop.index % 6 == 2 %} {{ two|safe }} {% endif %}
                                                     {% if loop.index % 6 == 3 %} {{ three|safe }} {% endif %}
                                                     {% if loop.index % 6 == 4 %} {{ four|safe }} {% endif %}
                                                     {% if loop.index % 6 == 5 %} {{ five|safe }} {% endif %}```
#

thanks @lethal orbit for you help! I was too dumb to get this

lethal orbit
#

Not dumb. Experience makes things easier ๐Ÿ˜„

native tide
#

well this was dumb. i spent the last three hours figuring this out ๐Ÿ˜›

glossy arrow
#

Hey, so I have a question, I'm making an application with flask, where users sign up and get a dashboard page. How do I make flask create a new dashboard for every user that signs up?

west tendon
#

is it better to rename template with .jinja2 extension instead of .html with a flask project ?

quick cargo
#

why?

west tendon
#

I can't get PyCharm (pro) to correctly detect that it's jinja

and I was wondering if it was a good or a bad idea to change .html to .jinja2

clear fjord
#

Nope 0 benefits to doing that

#

What IDE are you using?

west tendon
#

PyCharm (pro)

#

(I am new with it)

clear fjord
#

Yea for pycharm apparently you have to

lethal orbit
#

Hey, so I have a question, I'm making an application with flask, where users sign up and get a dashboard page. How do I make flask create a new dashboard for every user that signs up?
@glossy arrow I don't really use flask, but you need to build a context dict, and pass that to your template. For example, add a dict like {"user": {"name": "bob, "points": 50}} and use it like:

<h1>{{ user.name }}</h1>
<p>{{ user.points }}</p>
#

Pretty basic stuff.

glossy arrow
#

@lethal orbit Cool, thanks

warm garden
#

I have been using ruby on rails and there was a gem delayed jobs for queuing long running tasks .. is there any similar thing in flask_restful for doing that?

lethal orbit
#

@lethal orbit Could you help with my question?
@native tide sorry, I don't really deal with npm outside docker.

native tide
#

I have another question. this part of my code seems to work since the html renders correctly, but it throws an error:

#
    for i in data:
        if i['p_id'] == prod_id:
            kamin = i
    return render_template('kamin_prod.html', kamin=kamin)
#

Error: return render_template('kamin_prod.html', kamin=kamin) UnboundLocalError: local variable 'kamin' referenced before assignment

#

is the variable bound to within the for loop? cant i use it outside the for loop? why does it render the data stored in "kamin" though?

lethal orbit
#

Variables are generally in function scope, so if you set it in the loop, it should work outside of it.

#

But you can set it to None before the loop

#
 kamin = None
 for i in data:
        if i['p_id'] == prod_id:
            kamin = i
    return render_template('kamin_prod.html', kamin=kamin)
#

It might render the template with kamin=None in some cases though...

hollow inlet
#

when usings Requests lib get() followed by Requests post() on the same object will my cookies transfer over if I do it on the same thing (thing as in like s = Requests.Session() and I'm doing it on both s.get and s.post without redeclaring the object)

#

tldr; can i do s.get(site) to get cookies then pass them with a s.post(site2) or are there more steps?

coral raven
#

@native tide change that to /about

#

Rerun your server

#

Did you add url_prefix?

#

And you defined the app inside flaskapp?

#

wsgi file is in flaskapp

#

So server will start from flaskapp

hollow inlet
#

I'm having trouble getting cookies from one page and giving them to another. They do not show up in my results

s = session.get(parse_URL,headers=headers)
print("\n\r Status code: " + str(s.status_code) + "\n\r" + str(s.headers) + "\n\r ^^ Headers after GET ^^ \n\r")
s = session.post(login_URL,payload)
print("\n\r Status code: " + str(s.status_code) + "\n\r" + str(s.headers) + "\n\r ^^ Headers after POST ^^ \n\r")

This is my output

 Status code: 200
{'Content-Type': 'text/html;charset=UTF-8', 'Content-Encoding': 'gzip', 'Vary': 'Accept-Encoding', 'Server': 'Microsoft-IIS/10.0', 'Set-Cookie': 'JSESSIONID=3DREDACTEDC5.cfusion; Path=/; Secure; HttpOnly; SameSite=Strict, UID=WWTS; Max-Age=946080000; Expires=Mon, 12-Sep-2050 05:52:28 GMT; Path=/; Secure; HttpOnly; SameSite=Lax', 'Date': 'Sat, 19 Sep 2020 14:52:41 GMT', 'Content-Length': '4640'}
 ^^ Headers after GET ^^


 Status code: 200
{'Content-Type': 'text/html;charset=UTF-8', 'Content-Encoding': 'gzip', 'Vary': 'Accept-Encoding', 'Server': 'Microsoft-IIS/10.0', 'Date': 'Sat, 19 Sep 2020 17:52:28 GMT', 'Content-Length': '4640'}
 ^^ Headers after POST ^^
coral raven
#

Yes

#

Wsgi is Web Server Gateway Interface

#

Cool

#

There is one from Corey Schafer

#

One from Miguel Grinberg

#

Miguel Grinberg one has everything including docker and deployment

#

You will get many posts/tutorials on using apache2

hollow inlet
#

Should I post my question elsewhere?

coral raven
#

Yes , definitely

strange briar
#

hey guys, anyone has experience with graphql and django ? I'm building a web app with graphene-django, i implemented a custom user model, i implemented the Query for it, and now i would like to implement a mutation to create a new user

coral raven
#

He has a site that has less features, if you are new, do his first, then you can do the other ones

#

This code goes well with his book

#

Yes

#

You can customize

#

He shows how to add profile pics

#

You can take the same logic into your posts

#

No

#

Just addition

#

I have one which I made

#

But I reworked the styling and stuff

#

Not hosted

#

No

#

Maybe on his youtube

#

Did not check

#

I have sent you

lethal orbit
#

So your flask apps all have to be accessed under /flaskapp/something

#

Not sure I understand...

#

But I am off to watch a movie

#

Just a question of formatting your templates accordingly

alpine terrace
#

what is portal, e-portal in websites?

lethal orbit
#

Like here have options for adding images, placing them where I like in my blog post, changing fonts etc
@native tide I use Django... The admin interface does that out of the box

hollow inlet
#

Could I ask a question about handling sessions in Pythons requests library connecting as a client here?

#

I'm having trouble getting my session from one page and giving to another. It does not show up in my results

s = session.get(parse_URL,headers=headers)
print("\n\r Status code: " + str(s.status_code) + "\n\r" + str(s.headers) + "\n\r ^^ Headers after GET ^^ \n\r")
s = session.post(login_URL,payload)
print("\n\r Status code: " + str(s.status_code) + "\n\r" + str(s.headers) + "\n\r ^^ Headers after POST ^^ \n\r")

This is my output

 Status code: 200
{'Content-Type': 'text/html;charset=UTF-8', 'Content-Encoding': 'gzip', 'Vary': 'Accept-Encoding', 'Server': 'Microsoft-IIS/10.0', 'Set-Cookie': 'JSESSIONID=3DREDACTEDC5.cfusion; Path=/; Secure; HttpOnly; SameSite=Strict, UID=WWTS; Max-Age=946080000; Expires=Mon, 12-Sep-2050 05:52:28 GMT; Path=/; Secure; HttpOnly; SameSite=Lax', 'Date': 'Sat, 19 Sep 2020 14:52:41 GMT', 'Content-Length': '4640'}
 ^^ Headers after GET ^^

 Status code: 200
{'Content-Type': 'text/html;charset=UTF-8', 'Content-Encoding': 'gzip', 'Vary': 'Accept-Encoding', 'Server': 'Microsoft-IIS/10.0', 'Date': 'Sat, 19 Sep 2020 17:52:28 GMT', 'Content-Length': '4640'}
 ^^ Headers after POST ^^
#

I need that jsessionid

cold socket
#

What is the best way to protect my endpoints in Flask and prevent bots from sending requests?

quick cargo
#

you dont

#

you have no real way of knowing if theyre a user or a bot

#

sure you can check some things like user agent but most are fake anyway when it comes to bots

lethal orbit
#

@lethal orbit How does Django admin interface have those features of adding images, placing those images where I like in blog post, changing fonts built in?
Sounds like you need WYSIWYG editing.... So no, that is not a Django or Flask feature.

#

Look at CMS ... maybe Wagtail.

#

Then what were you saying```. The admin interface does that out of the box im django

@native tide must have misunderstood your question. ๐Ÿคทโ€โ™‚๏ธ

#

RIP my notifications

warped timber
#

@native tide missing a comma before 'date_posted'

#

twice

#

@native tide afaik django does have an admin thing out of the box

#

but flask doesn't because its a "micro" framework

#

pretty sure you can use images w/ markdown

#

idk about the others

#

"Like here have options for adding images, placing them where I like in my blog post, changing fonts etc" other features

#

99% sure images are supported

#

idk about fonts, etc

#

wysiwyg is basically an editor like word or google docs

#

and neither framework supports that natively

#

markdown can i think

#

fonts

#

arbitary positioning of images

#

etc

#

wait

#

i think i misremembered

#

you need to install a separate package for markdown in django, sorry

lethal orbit
#

oooof

#

double RIP my notifications?

marble carbon
#

lol

#

rip dude

#

poor poor lad

#

anw

#

these two might be what you're looking for @native tide

#

@native tide please respond when you can, thanks

vestal hound
#

@lethal orbit ?
@native tide you really should stop pinging people

#

everyone here is a volunteer. they're not obliged to answer your questions.

marble carbon
#

the dude didn't even say anything, he's too polite :(

#

here's a crazy thought

#

By installing email_validator perhaps?

#

u got

#

flask admin?

#

https://goo.gl/search/flask+tinymce
TinyMCE and Flask - Kevin Foong TinyMCE is a great WYSIWYG editor and suitable for things like blog posts. It also enables you to upload images directly into your text. Follow the instructions below to set up TinyMCE as a local download. In Flask I create your forms as per normal using Flask-WTF.

#

okay idk

#

man

#

wait for someone else to reply

#

and please don't ping me for this now

half bough
#

Hi, I'm working with Django. How come I can't do this: price = Trainer.objects.filter(trainer_price__id=3)? I get error Unsupported lookup 'id' for DecimalField or join on the field not permitted

#

I'm trying to replicate the SQL query: SELECT trainer_price from table WHERE id=3)

vestal hound
#

Hi, I'm working with Django. How come I can't do this: price = Trainer.objects.filter(trainer_price__id=3)? I get error Unsupported lookup 'id' for DecimalField or join on the field not permitted
@half bough trainer_price seems to be a field.

marble carbon
#

trainer_price__id?, you have an id for a price? better show ur models

vestal hound
#

that would be Trainer.objects.get(id=3).trainer_price

half bough
#

oh, ok let me try that @vestal hound

vestal hound
#

actually, no

half bough
#

no?

vestal hound
#

changed it

marble carbon
#

that would be Trainer.objects.filter(id=3).first().trainer_price

vestal hound
#

that should be .get, not .filter, since you want a single result

half bough
#

Eventually, I won;t hardcode and the 3 will be a pk or something

vestal hound
#

yeah, that's fine

#

just pass it as an argument

half bough
#

ok so I thought a filter is like the WHERE clause?

vestal hound
#

yup

#

it is

#

the filter method is like WHERE

half bough
#

So I'd try: Trainer.objects.get(id=3).first().trainer_price?

vestal hound
#

no

half bough
#

ok

vestal hound
#

Trainer.objects.get(id=3).trainer_price

half bough
#

ohh

vestal hound
#

because .filter() returns a QuerySet

#

however, you know id is unique

half bough
#

Ahh, ok

vestal hound
#

so you can use .get, which basically makes sure that there is only one result

#

and returns that single result

#

otherwise you'd need like Trainer.objects.filter(id=3).first(), or [0] in place of .first()

marble carbon
#

how about

#

u stop posting it again

#

and again

half bough
#

That worked like a charm! Thank you @vestal hound ๐Ÿ™‚

vestal hound
#

That worked like a charm! Thank you @vestal hound ๐Ÿ™‚
@half bough yw

versed python
#

@native tide did you read the errors? It clearly says what you need to do

idle karma
#

I have DB mapped with SQLAlchemy and Iโ€™d like to be able to do some bulk edits/updates using a flask frontend. Basically I want to display all rows where some value is NULL and allow me to enter a value for some or all and click update. Ideally I want to have it display the data as a โ€œtableโ€ with the appropriate field editable. Sort of like a spreadsheet style. Any tips/libraries that can help?

native tide
#

https://github.com/TCnet/flask-wysiwyg -- this hasnt been updated in 6 years, probably because its more popular these days to just do this kind of thing in JS front end, and communicate with the backend using REST API.

I would consider not using that seriously based on how old it is. But it sounds like you know what to search for

@native tide

lavish coral
#

Seeking suggestions: Currently teaching myself Django 3.1. I'd like to dig through a few apps built with this version. Any github repositories I could check out?

native tide
idle karma
#

@native tide So just hook it up using something like datatables? This is just a personal project and Iโ€™m not a JS person at all so trying to keep as much in python as possible

marble carbon
#

ohh pydis site is made in django

#

nice

topaz widget
#

@lavish coral Django 3.1 is very new. I tried updating my version of Django something like 2 or 3 weeks ago, and it loaded 3.0.8 instead. Only very recently did pip update to 3.1. Anyway, I doubt you're going to find too many projects built from scratch in 3.1 in that time frame. Almost everything out there using new features for 3.1 is just going to be a revision of some project made in an older version.

versed python
#

Django 3.1 is not really different from 3.0 especially for a beginner

#

and the django docs have their tutorial updated to 3.1

stark yarrow
#

Hey I had 70~ DRF serializers in a single file. I organized them in different files, but now I'm having issues with circular imports. What is my best option? I have a few that are nested.

topaz widget
#

Untangle your circular dependencies @stark yarrow

lavish coral
#

@topaz widget @versed python Good to know. I'll stick with 3.0.

stark yarrow
#

Do you know if there is a tool to visualize it? I had found one earlier but it doesnt have a update in more than 8 years

marble carbon
#

@versed python I think it's not about it being new, but a lack of tutorials available for it yet, since most of them are still 1.11 or 2.2

vestal hound
#

Hey I had 70~ DRF serializers in a single file. I organized them in different files, but now I'm having issues with circular imports. What is my best option? I have a few that are nested.
@stark yarrow why do you have so many serializers?

#

that seems like a LOT

indigo moth
#

Hi. I wanted to use bulma in my django app. So there was a package provided by this server named django-simple-bulma. I installed it using pip, did whatever told me in the README.md file. added 'django_simple_bulma' to INSTALLED_APPS settings, changed STATICFILES_FINDERS settings. my settings about static files now looks like this:

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

STATICFILES_FINDERS = [
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    'django_simple_bulma.finders.SimpleBulmaFinder',
]

but when I run python manage.py collectstatic it gives me error

ModuleNotFoundError: No module named 'django_simple_bulmaposts'
#

Why? what's wrong?

#

is this is pip package or something?

#

And I'm pretty sure I've installed django-simpl-bulma. it's on pip freeze output

django-simple-bulma==2.0.3
#

I'm so confused about what is this bulmaposts package?

#

ping me back when you are answering

versed python
#

@indigo moth You forgot a , in your INSTALLED_APPS

#

probably between django_simple_bulma and posts

indigo moth
#

oh lolz

#

thanks

#

can someone tell me should I use STATICFILES_DIRS or STATIC_ROOT in development?

versed python
#

You generally just need STATIC_ROOT in dev since django handles serving static files for you. In prod, you have to set both, otherwise collectstatic won't work

indigo moth
#

okay thanks again

burnt olive
#

Does anybody have experience with creating multi select filters in django admin, i tried looking for packages but none seems to have the feature
Any leads would be highly appreciated

native tide
#

Hello guys

native tide
#

I use Vue, for instance if I wanted to do this, I'd look at installing something like https://chmln.github.io/vue-wysiwyg/ There is much of them, I would say React is more popular but I prefer Vue.

I should point out, I never have done this exact project. And learninga JS and a JS frontend framework like Vue is as much work as learning Python and/or Flask.

Not to mention you have to get whats taken in that editor and convert it into HTML before you can post it anywhwere. You also have to design an API endpoint to receieve the post

Its kind of next level. I know the things you would need to research to do it, but I have never done it.

I would say overall its much easier to learn backend, designing APIs, and doing auth stuff if you stop expecting there to be easy to implement frontend features. Because at first there is not going to be.

#

Actually, this might be a lot easaier https://trix-editor.org/

#

@native tide Good luck

#

But, I can tell from your Flask project that you just started doing Flask. It might be wise to just accept for now what you cannot do without JS.

#

Its either that or learn JS now so you can mix them.

brittle basin
#

I asked that here before but still stuck - I'm trying to deploy my flask app to Heroku. But when I push and release the container it seems to have problem binding to the port, any idea why?

vestal hound
#

@brittle basin is PORT used by Heroku?

#

because there are some environment variables which are reserved for use by the host environment

brittle basin
#

@brittle basin is PORT used by Heroku?
@vestal hound From what I understood Heroku uses that env var for to me to bind to

vestal hound
#

@vestal hound From what I understood Heroku uses that env var for to me to bind to
@brittle basin uh...what that seems to say is that it's meant for Heroku's use

#

Heroku sets it

#

anyway, just try using like FLASK_PORT or something

#

and see if that fixes things

brittle basin
#

Got ya, I'll try it now ๐Ÿ™‚

vestal hound
#

if it's not, then my bad ๐Ÿฅด

brittle basin
#

Still same problem ๐Ÿ˜ฆ

twilit dagger
#

How do I optimize a website for mobile?

#

For e.g.- I have a container that's rendered row-wise but on mobile I want it to be column-wise

#

How do I optimize a website for mobile?
For e.g.- I have a flex container that's rendered row-wise but on mobile I want it to be column-wise

lethal orbit
native tide
#

Hi guys, new to django, does context always have to be a dictionary?

limber laurel
#

Wpuld this be good practice? If I cache for example a database query of all objects within a model and in the repr of that model have it delete all of the caches of that data?

#

Or would it better be just to have it cahced for like 200 seconds and then make the cache inactive

#

@native tide yes

sterile sphinx
#

So i wrote this and trying to learn flask but i can't view the site on localhost:5000 what am i doing wrong?

brittle basin
#

So i wrote this and trying to learn flask but i can't view the site on localhost:5000 what am i doing wrong?
@sterile sphinx Try adding parameter to the run() - host='0.0.0.0'

sterile sphinx
#

Still nothing, all firewalls and such has been taken down. I do not even get anything inside the console like it has started on a port or it's waiting for connections like it did on all these videos i watched?

twilit dagger
#

what about localhost:8000

brittle basin
#

Still nothing, all firewalls and such has been taken down. I do not even get anything inside the console like it has started on a port or it's waiting for connections like it did on all these videos i watched?
@sterile sphinx With what env parameters are you running it?

sterile sphinx
#

I do not run a env

brittle basin
#

You need FLASK_APP

sterile sphinx
#

i installed it directly on the system

#

is it a module i need to import?

brittle basin
#

FLASK_APP=C:\Users\gadw1\PycharmProjects\shared-story-server\app\app.py
for example

sterile sphinx
#

Do i do this inside the code or a terminal?

brittle basin
#

Are you using Pycharm?

sterile sphinx
#

vscode

brittle basin
#

Ok, I'm not sure how to run it with env vars for vscode
But you can do it via terminal

sterile sphinx
#

How would i do that? i tried flask run filename after cd'ing to the folder

brittle basin
#

Try looking there

sterile sphinx
#

Alright thanks.

#

Apprently i got it working it seems it has to be named app.py :/

swift sky
#

im having issues with the login module that I've built

#

I was hoping someone could help

#

basically my script works locally

#

but when i make a docker image out of it, it doesn't work

#

specifically it asks me to log in multiple times, it's not storing the session status properly

#
from flask import Flask, render_template, redirect, url_for, request, session, flash, send_file
from functools import wraps
from staffDashboard.load_parse_articles import urls_311




def routes(app: Flask):

    global sessionLogIn

    sessionLogIn = []

    # def login required decorator
    def login_required(f):
        @wraps(f)
        def wrap(*args, **kwargs):
            if True in sessionLogIn:
                return f(*args, **kwargs)
            else:
                flash("You need to log in first!")
                return redirect(url_for("login"))

        return wrap



    #    # login page and location logic
    @app.route("/login", methods=["GET", "POST"])
    def login():
        error = None
        if request.method == "POST":
            if (
                request.form["username"] != "admin"
                or request.form["password"] != "admin"
            ):
                error = "Invalid Credentials. Please try again."
            else:
                sessionLogIn.append(True)
                session["logged in"] = True
                flash("You were just logged in!")
                return redirect(url_for("staffdashboard"))
        return render_template("login.xhtml", error=error)

    @app.route("/logout")
    def logout():
        session.pop("logged_in", None)
        session.clear()
        sessionLogIn.clear()
        flash("You were just logged out!")
        return redirect(url_for("login"))

    # app routes for webpages
    @app.route("/")
    @login_required
    def staffdashboard():
        return render_template("staffdashboard.xhtml")

    @app.route("/updateknowledgearticles")
    @login_required
    def knowledge_articles():
        return render_template("updated_knowledge_articles.xhtml", dict_to_be_passed=urls_311)
brisk spindle
#

fastapi or aiohttp in 2020?

sterile sphinx
#

I keep getting rendertemplate not found "home.html" why can't it find it it it's in the same folder as the script is ran and i provided correct path...

swift sky
#

make sure the html is referencing the right FUNCTION

#

url_for{'name_of_function'}

#

so for you it would be home

#

@sterile sphinx

#

so check your html

sterile sphinx
#

inside my home.html all i have is a <h1> that says hello world, and it works in the browser

#

I'm unsure what you mean

swift sky
#

nvm

sterile sphinx
#

Just gonna give up flask and make my own framework, atleast that's easier todo than using this flask thingy where nothing works.

quick cargo
#

i can pretty much garentee making your own will be a 10000% harder than using flask

#

this is comming from someone who's made their own framework and server that covers the same scale as flask

#

there is alot

strange briar
#

except if you have deep knowledges of how frameworks work

quick cargo
#

even then

#

using the framework compared to building them is a massive diffrence

strange briar
#

yea

#

CF8 do you know about graphene and django ?

#

the graphql framework for django

quick cargo
#

not really im afraid

#

i mostly work with ASGIs

strange briar
#

i see

quick cargo
#

i can take a look if you want but dont expect me to have any idea whats going on ๐Ÿคฃ

strange briar
#

yes it'd still be appreciated ๐Ÿ™‚

#

i'll show you, if anyone also knows about graphene and django and can help me it would be appreciated

#

so here's my custom user class,

class CustomUser(AbstractUser):
    username = None
    first_name = models.CharField(max_length=255, verbose_name="First name")
    last_name = models.CharField(max_length=255, verbose_name="Last name")
    email = models.EmailField(unique=True, db_index=True)

    USERNAME_FIELD = "email"
    REQUIRED_FIELDS = ["first_name", "last_name"]

    objects = managers.CustomUserManager()

and here's my mutation to create a user, problem is that i don't know how it works and i don't find anything about it on internet so it's incomplete, if anyone can help me implement it and explain me

class CreateCustomUser(graphene.Mutation):
    """ Custom User mutations (main user table) """
    
    class Arguments:
        first_name = graphene.String(required=True)
        last_name = graphene.String(required=True)
        email = graphene.String(required=True)
        password = graphene.String(required=True)

    def mutate(root, info, first_name, last_name, email, password):
        user = CustomUser(
            first_name=first_name,
            last_name=last_name,
            email=email,
            password=password
        )
        
quick cargo
#

okay yeah i have no idea lol

lethal orbit
#

What's the point of redefining the first_name, last_name, and email fields?

#

Can't you just inherit them?

#

Inside CustomUser

#

And what problem are you having?

strange briar
#

@lethal orbit i don't know how to inherit them, can you tell me ?

lethal orbit
#

You just need to use: class CustomUser(AbstractUser): ๐Ÿ˜„

#

As it's a derived class, it should inherit those fields from AbstractUser

strange briar
#

so it would be like this

class CustomUser(AbstractUser):
    username = None
    email = models.EmailField(unique=True, db_index=True)

    USERNAME_FIELD = "email"
    REQUIRED_FIELDS = ["first_name", "last_name"]

    objects = managers.CustomUserManager()
``` ?
lethal orbit
#

Really, you should just be able to remove those lines.

#

Oh yeah, you need email since you set it to unique

strange briar
#

yes it's to login via email

lethal orbit
#

But redefining names is not necessary.

strange briar
#

ok i'll give it a try once i resolve my problem thanks ๐Ÿ™‚

#

here's how my mutation looks like now i followed a guide from a website

#
class CreateCustomUser(graphene.Mutation):
    """ Create CustomUser mutation (main user table) """
    
    class Arguments:
        first_name = graphene.String(required=True)
        last_name = graphene.String(required=True)
        email = graphene.String(required=True)
        password = graphene.String(required=True)

    def mutate(root, info, first_name, last_name, email, password):
        user = CustomUser(
            first_name=first_name,
            last_name=last_name,
            email=email,
        )
        user.set_password(password)
        user.save()

        return CreateCustomUser(user=user)
lethal orbit
#

I haven't used graphene much because I found ariadne to be much cleaner, but I think you want to use something like this for mutate...

from django.contrib.auth import get_user_model

User = get_user_model()
class CreateCustomUser(graphene.Mutation):
    """ Create CustomUser mutation (main user table) """
    def mutate(root, info, first_name, last_name, email, password):
        user = User.objects.create_user(
            None,
            first_name=first_name,
            last_name=last_name,
            email=email,
            password=password,
        )
        return CreateCustomUser(user=user)
strange briar
#

many people talked about Ariadne it interests me but I'm scared to get lost it's my first implementation of graphql and i started with this

lethal orbit
#

I'm not sure it's better, but I find it much easier to work with code built around ariadne than graphene lol....

#

Multiple-inheritance nightmare

strange briar
#

here i also saw that many people talked about Ariadne but not graphene so i think swapping would be good

native tide
#

I've got this table here

@media
only screen and (max-width: 760px),
(min-device-width:768px) and (max-device-width:1024px){
    table, thead, tbody, th, td, tr { 
        display: block; 
    }
    
    /* Hide table headers (but not display: none;, for accessibility) */
    thead tr { 
        position: absolute;
        top: -9999px;
        left: -9999px;
    }
    
    tr { border: 1px solid #ccc; }
    
    td { 
        /* Behave  like a "row" */
        border: none;
        border-bottom: 1px solid #eee; 
        position: relative;
        padding-left: 50%;
        right: 0;
    }
    
    td:before {
        font-weight: bold;
    }
    
    td:nth-of-type(1):before { content: "Ime i prezime"; }
    td:nth-of-type(2):before { content: "Pozicija u poduzeฤ‡u"; }
    td:nth-of-type(3):before { content: "Adresa e-poลกte"; }
    td:nth-of-type(4):before { content: "Broj mobitela"; }
    td:nth-of-type(5):before { content: "Datum unosa"; }
}

I wanna move the td content to the end of my table and keep the td:before at the start

final crest
#

Not sure if this applies for here, but it involves websites,

Using selenium to interact with a website. Pycharm with pyinstaller added in. my script runs fine in pycharm. When i run the .exe it shows aprox 3,000 lines of these
"Mixed Content: The page at 'URL page i loaded' was loaded over HTTPS, but requested an insecure image 'URL of loaded content image'. This content should also be served over HTTPS.", source: URL page i loaded (0)
is there a negative effect of handling that many notifcations, or can they be hidden? I did change all instances of 'http' to 'https' in my script

native tide
#

I am trying to create paginated pages in this view

#

def all_users(request):
    users = Person.objects.all()
    pag = Paginator(users, 3)
    page_num = request.GET.get('page')
    page_obj = pag.get_page(page_num)

    context = {
        'users': users,
        'title': 'All Users',
        'page_obj': page_obj
    }
    return render(request, 'index/users.html', context)
#

users.html :

#
{%extends 'index/base.html'%}
{%block content%}
<section class="all-users">
    {%for user in users%}
    <article>
        <h1 class="username">{{user.username}}</h1>
        <hr>
        <p><b>Email: </b><span class="email" class="">{{user.email}}</span></p>
        <p><b>FirstName: </b><span class="first-name" class="">{{user.first_name}}</span></p>
        <p><b>LastName: </b><span class="last-name" class="">{{user.last_name}}</span></p>
        <p><b>Joined on: </b>{{user.date_joined}}</p>
        {%if is_staff%}
        <p>{{user.username} is a staff member</p>
        {%else%}
        <p><span class="full-name">{{user.first_name}} {{user.last_name}}</span>, a.k.a {{user.username}} is a normal member</p>
        {%endif%}
    </article>
    {%endfor%}
</section>

<div class="pagination">
    <span class="step-links">
        {% if page_obj.has_previous %}
            <a href="?page=1">&laquo; first</a>
            <a href="?page={{ page_obj.previous_page_number }}">previous</a>
        {% endif %}

        <span class="current">
            Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.
        </span>

        {% if page_obj.has_next %}
            <a href="?page={{ page_obj.next_page_number }}">next</a>
            <a href="?page={{ page_obj.paginator.num_pages }}">last &raquo;</a>
        {% endif %}
    </span>
</div>
<script type="text/javascript">
    let users = '{{users}}' 

   
    for(let username of document.getElementsByClassName('username')){
        if (username.textContent.length >= 15 && username.textContent.length <= 20 ){
            username.style.fontSize = '30px'
        }else if (username.textContent.length >= 11 && username.textContent.length <= 14 ){
            username.style.fontSize = '45px'
        }
        }
</script>
{%endblock content%}```
#

as you can see in the paginator i want three users per page

#

but that doesn't even work

#

I still see all the users(article boxes with the users info) all on one page!

#

There are no Error message anywhere

half bough
#

Hi, I'm working with Django. How would I insert data into the database from a form when using a field from another model? For example, I have a Trainer modelform and User modelform in a separate app. I'm getting the price field from the Trainer app using the orm in the User view but when I submit my form the price field is not getting inserted.

#

let me know if you need to see my code

#

This is what my context looks like that I'm passing into my user_form:

#

FYI, I;m not using a foreign key

tall marlin
#

quick question about flask-- I'm getting an error 500 on login when running my application via gunicorn using nginx as a reverse proxy, but when I use the built-in development server logging in works perfectly. Is this something that has to do with gunicorn/nginx?

lethal orbit
#

hi all, anyone have recommendations on how to display a list in real time via flask? or should i use django?
@native tide the best solution is probably WebSockets: https://flask-socketio.readthedocs.io/en/latest/. You can also use push notifications (which I never did). The easiest is to write a simple view you can embed in a page and poll using htmx: https://htmx.org/

#

htmx would still not be real-time, but it takes minimal code. WebSockets would require some JS.

quick cargo
#

websockets take piss all js

#

my entire video syncing system is 100 lines of JS total

#
  • live chat included with that
lethal orbit
#

Ok, I stand corrected xD

quick cargo
#

a ws in js is litterally const myWebsocket = new Websocket("ws:/my.domain.com/path");

#

nice to see a corey vid

#

do you want it to be selectable

#

or just change the size with a hard coded thing

#

oh thats gonna be much harder

lethal orbit
#

a ws in js is litterally const myWebsocket = new Websocket("ws:/my.domain.com/path");
@quick cargo Well, you still have to handle events and shit lol

quick cargo
#

im trying to slowly type it

#

lol

#

@native tide thats gonna require alot of JS and probably a framework to dynamically change the fonts etc of the html

#

there isnt going to be any sort of easy way todo it

lethal orbit
#

Anyways, I will be doing that soon โ„ข๏ธ

#

I need to add Channels to my app.

quick cargo
#

not that i know of

#

erm well font sizes and families is done with css

#

look at font size css and font family css

#

highlighting also css

#

everything else you'll have todo with sheer logic im afraid

#

no idea

#

there's a reason there arnt loads of apps like this

#

they take alot of js and work and there probably arnt any plugins that do it

#

im afraid so

#

erm probably a long long project if you wanna do it so the user can choose a font size, highlights etc...

#

like many many many days with experience in js and alot more without js experience

#

also @lethal orbit @native tide a basic ws handler:

let addr = window.location.href        // get our current url
addr = addr.replace("https", "wss")    // replace out https with a ws protocol

const socket = new WebSocket(addr+"/ws");  // add "/ws" to out path and connect

socket.onopen = function () {
    console.log("Im connected to the ws!");
}

socket.onclose = function () {  
    console.log("I have lost connection to the ws!");
}


socket.onmessage = function (event) {
    let messageContent = event.data;
    let myJSONContent = JSON.parse(messageContent);
    
    // some logic here ig
}
#

that would be 100% done on the front end with alot of JS

#

the backend would only be able to help with storing the settings of the post for viewers to see when its rendered ig

#

but bearing in mind todo what you wanna do you'll most likley loose the ability to use the templating engine because by that point the client is gonna have to send the data back with all the css settings

#

yes

#

for this sorta thing not using JS isnt a option

#

no backend system is gonna help you with doing front end stuff

#

shear ignorance and experimenting

#

and a lot of trial and error

#

none

#

the only one i really use for js is the vue documentation and w3schools if i forget some basic stuff

lethal orbit
#

also @lethal orbit @Sevens a basic ws handler:
Cool. When I am done herding goats, I will get back to my portfolio site and add WS.

quick cargo
#

i didnt really need to learn that stuff

#

js is my 3rd programming language

#

my mains are Rust and python so im quite use to varible defining and that stuff

#

@native tide because css is what will make it look like it is and JS will be the thing that actually applies the CSS changes

#

otherwise it'll be static

#

for it to be dynamic you need to use js to add/remove diffrent css affects change positioning etc...

#

yeah that would work, or you could do it to support markdown directly and use markdown (which is probably gonna be safer in terms of stopping xss unless you disable js)

#

you will still needs some js altho no where near as much

#

altho ig a form with a POST request would work

#

so yeah you could get away with zero js that way ig

#

i mean if you enable html stuff from user input then you'll have a high chance of being xss attacked

#

markdown is a diffrent format

#

this is a example of markdown in discord

#

disable js in the injection box bit which i have no idea how you do it i just know it is a option you can do

#

yeah pretty much

#

no idea how though you'll probably have to google that

#

i have no idea what to search for tbh

#

other than js disabled user html input lol

#

and erm i wouldnt say ive really learnt it

#

like im probably still noob level ish ig

#

on and off about a month

#

if you're doing it so the user is in charge of laying it out how ever they want by writing the html themselves then yeah

#

idk how long it would take you cuz we learn at diffrent rates

#

oh like that thing

#

um

#

a while

#

i dont think i could do anything closed what it would need for months

#

alot of compilcated flex boxes and js is a yikes from me

#

i could probably hack it together

#

but it certainly wouldnt be pretty

#

yes

#

it would take me

#

a long time

#

i think the image positioning bit will be the hardest

#

text size and that you can sorta do with a bit of js

#

but you would be limited to what sizes

#

but the image repositioning would require alot of js to change all of the css for everything on the post as you move it

#

by making some custom massively complicated system by which point you're no longer using css and html but probably canvas or something entire diffrent making more of a gui than html

#

you'll need to search that

#

i wont be able to properly explain it

#

yeah markdown is limited

#

i would describe it as pygame for webpages sorta

#

yikes

#

cant be deleting all your messages on me ๐Ÿ˜ฉ

#

looks like ive gone mad

#

๐Ÿค” wdym

#

no idea who that is

#

also btw if you're self botting i wouldnt because you'll get perma banned from both here and Discord

#

i dont see anything massively complex there

#

not really?

#

yikes

#

i can see why it was useful but there are alot of trackers now

#

yh

#

its not massively complex though overall

#

like a week or less ig if you know what sites to scrape

#

wayy less

#

that site could be rendered with pure python templating and zero js overall

#

the map section would take some js

#

but there are modules todo that

#

in this case he used jquery jvectormap it seems

#

even if a module did exist

#

i imagine it would still be complex

#

like there is a vast diffrence between having a client user interaction and just serving general data from a db

#

all that site has todo is get the data from a db fed by the scraper

#

and render it with and use css to style it

#

no idea

#

doesnt really matter

#

yeah pretty much

#

there's all your hard work done for you

#

other than doing the whole submiting the settings ig? but yeah thats pretty much drop in and go

#

cuz i didnt look to see if a module already exist other than knowing that its generally not the most common thing to find on sites

#

if you were making the equivelant of that module thats over 120,000 lines of JS

#

welcome to programming :P

#

google is your friend

#

im not gonna be google for you other than general guessing

#

if you mean the 48 people who worked to build it and about 200,000 lines of code yeah alot of hard work

#

probably

#

i imagine no one really wanted todo it themselves with all that work

#

more like years

#

that module has been developed for ~6 years or more

#

Jun 1, 2014 โ€“ Sep 20, 2020

#

probably longer than a month still

#

i have no idea

#

try it and see

#

litterally the only way to learn anything is todo it

#

btw if you're doing that with the discord bot dont because you're just gonna get banned from discord

#

or you can keep going and just ignore that

#

๐Ÿ™ƒ

obsidian linden
#

Looking for a way to get a subscription based website that allows subscribers to connect to a database in order to look at data that we would be making/providing. Is there any web frameworks or things I should look into?

distant trout
#

could someone explain to me what exactly does offset parameter does? several API uses it for pagination and im confused

lethal orbit
#

looks like ive gone mad
lol, RIP

brisk spindle
#

@distant trout google SQL OFFSET keyword, it basically skips N records in query result

quiet comet
#

im using django and i need to have choices in a template but you can choose "other" and a text field appears so you can write, how can i do this? Do i send the choices from the views to the template and then use a if ?

vestal hound
#

Looking for a way to get a subscription based website that allows subscribers to connect to a database in order to look at data that we would be making/providing. Is there any web frameworks or things I should look into?
@obsidian linden can you elaborate/

#

it sounds like basically you're a data provider and you want to give customers access to that data.

obsidian linden
#

yes basically

vestal hound
#

do you have a technical background?

#

i.e. are you a coder

obsidian linden
#

I am working with one I have some knowledge

vestal hound
#

yeah, I kind of had the feeling you were a non-technical person

#

okay, so basically

obsidian linden
#

:/

vestal hound
#

nah, it's cool

#

just need to know how to scope my explanation

obsidian linden
#

Igu

#

i can relay the message though

vestal hound
#

what kind of data are you looking at?

#

if it's not sensitive

#

(this affects what kind of storage you use)

obsidian linden
#

integers?

#

i dont want to say the data exactly

vestal hound
#

okay, then some kind of SQL would work just fine

#

that's your database layer

obsidian linden
#

Yea thats what we were thinking

vestal hound
#

next, you want to give access over the Internet?

#

through some kind of API

obsidian linden
#

Yessir

vestal hound
#

I would suggest Django

obsidian linden
#

The thing is it is written in Java

vestal hound
#

what is "it"

obsidian linden
#

the way we pull data

#

but that might not matter

vestal hound
#

no, it doesn't matter

#

just like your server might be written in Python

#

but your clients might be written in some other language

#

that's the point of communicating over HTTP: your data's format is not bound to what generated it

#

anyway, yeah, Django

#

other Python alternatives include Flask and FastAPI, as well as Pyramid, Sanic, etc.

#

but IMO for a relative beginner Django is the best because it's an opinionated all-in-one solution

#

if you only want to provide an API, I suggest Django with DRF (Django REST Framework)

obsidian linden
#

ok

#

how do you deal with users logging in?

#

how would we add the paywall though

#

and like a verification to be allowed to request @vestal hound

vestal hound
#

don't wanna watch videos, sorry

#

anyway, those are details that you can find out from a Django tutorial

obsidian linden
#

TY

native tide
#

hey can someone help me with this error

vestal hound
#

hey can someone help me with this error
@native tide post the error...

native tide
#

ok

#

lok

#

im making extension

#

im helping someone

#

he wants the sliders to stay when you reload the extension

#

and he's getting this error

#

right now, only one of the sliders are saving

vestal hound
#

uh

#

so where's the code

#

also, this seems like JS...

tepid lark
#

are they bound to the right events / model / whatever your data source is?

native tide
#

it is javascript

#

hold on lemme get the code

#
document.addEventListener('DOMContentLoaded', function() {
    updateSlider();
    var Dark = document.getElementById("toggledark");
    var colorPick = document.getElementById("slider-color-picker");
    var GoogleAds = document.getElementById("toggleadsense");
    
    

    Dark.addEventListener("change", toggledSwitch);
    colorPick.addEventListener("change", changeColor);


    GoogleAds.addEventListener("change", togglegoogleads);
    


});```
#
var updateSlider = function(){
    let root = document.documentElement;
    var onToggled = chrome.extension.getBackgroundPage().onToggled;
    document.getElementById("toggleadsense").checked = onToggled;

    ///var popups = chrome.extension.getViews({type: "popup"});

}
#

forget it it's too hard

frozen spear
#

heroku

#

djangoo

weak chasm
#

@frozen spear " So it turns out that the last time I updated Heroku, the site automatically changed my API key for this particular app. Thus my new API key was not matching the old one in the _netrc file. The solution was to go to dashboard.heroku.com/account and scroll down to find the new API key. Use this as the password and email account as the user name and git push heroku master works again." did you try stackoverflow?

frozen spear
#

jeez i tried all resources online

#

including sof

#

i iwll

#

retry

#

thanks

#

@weak chasm btw wydm with api key as password and email as username

#

and where literally?

#

the netrc

#

?

weak chasm
#

that was from stack overflow. seems they were suggesting to double check your api key, password, email matched in the file as they did online. that's all i got sorry.

frozen spear
#

its ok

native tide
#

hello friends

#

i would like to make a ui using react but a back end using flask and jinja2

#

i would like to ask if you have any tutorials or guides you might know

#

also does anyone know how to create a react app without create-react-app (it's too bloated)

#

nevermind on my second question, I found this article: https://dev[dot]to/vish448/create-react-project-without-create-react-app-3goh

hybrid socket
#

Hello, anyone familiar with Flask? I have a small beginner problem. https://prnt.sc/uku6x5 When I enter the name and submit, I get internal server error

Lightshot

Captured with Lightshot

native tide
#

@hybrid socket have you imported request from flask

#

try adding this: from flask import request

hybrid socket
#

but that might be it, he names his flask app as application.py for example and I have to do app.py

#

there are small differences

native tide
#

yeah

hybrid socket
#

well it worked, thank you

native tide
#

np mate

stable kite
blazing sonnet
#

hi I'm new, I kinda messed up while learning django

#

how do I delete the webpage?

stable kite
#

what?

#

@blazing sonnet

blazing sonnet
#

I started making a webpage with django

#

kinda messed up

#

how do I start over

stable kite
#

just delete all the views , urls , models as per your need

#

or

#

create a new django app

blazing sonnet
#

so just deleting all the files will do?

stable kite
#

by using py manage.py startapp #name

#

not files

#

but data inside it that you wrote

blazing sonnet
#

I see

#

ahh okay

#

thanks!

unreal lynx
#

hey im trying to import my plotly charts to a django website

#

is there a good tutorial on how to do that

snow estuary
#

anyone interesting creating an ecommerce website using django for learning issue ?

versed python
#

hey im trying to import my plotly charts to a django website
@unreal lynx i have a fair bit of experience with this. it was my first project. https://github.com/IgnisDa/ocean-pv

unreal lynx
#

@versed python Hey thanks for reaching out! Damn that looks really impressive!

#

I need some help with what im trying to make, ill reach out on dm if your ok with that

versed python
#

sure np

north sky
#

so i have this html: <h2><span class="wid">70627</span> - 45k m3</h2>
how can i get the 70627 and the - 45k m3 with bs4?
replace method will not work because some times there are style inside the <span>
and .text returns: AttributeError: 'NoneType' object has no attribute 'text'

honest dock
#

Hello, has anyone used GeoDjango here?

limber laurel
#

Should I store cache in a seperate database?

cold anchor
#

what do you mean?

#

why are you using a cache?

bright spindle
#

within django, upon creation of password field generating requirements displayed under the password field

#

how do i implement those to a new userclass and usercreationform

limber laurel
#

@cold anchor So I wouldnt need to resend the queries to my database each time that I look in my case at the plans of a user.

#

But I am confused about where I should have it stored

frank nebula
#

Hello Devs, in Django admin, i have a M2M field with almost 500k objects. Theres any way to filter the queryset (or get just the latests) in a django admin field?

graceful mauve
#

Hi everyone, i have an issue with the "single interpreter" in HUG running on WSGI, i tried adding "--single-interpreter" to the .wsgi file but that didnt work any idea?

native tide
#

ppl told me flask is for small projects, so whats considered a small project?

quick cargo
#

@native tide flask can be used on big projects

#

Discord runs on flask for backend stuff

idle flame
#

Hello everyone, so sorry to bother you. Does anyone have a quick moment to point me in the right direction regarding static files for django?

#

I've been through the docs

#

and several youtube tutorials and somehow I still can't get an image to display. I'm almost certain it's something simple

#

I've even tried on a blank new project.

#

this is for the built in dev server*

#

not deployment

dapper tusk
#

django itself only handles static files when using debug=True

idle flame
#

the flag is set like this in settings already

#

so debug mode enabled

dapper tusk
#

did you add static file finders

idle flame
#

i.. dont think I did. It's on django3.

#

STATIC_URL = '/static/'

#

is the only setting I currently have in settings related to static files

dapper tusk
#

does admin have its static files?

idle flame
#

Sorry, I'm new to this. you mean the admin section?

#

Yes

dapper tusk
#

and the static files that are not displaying are in app_directory/static/?

idle flame
#

'django.contrib.staticfiles', is in INSTALLED_APPS

#

Yes

#

app/static/app/images/img.jpg

dapper tusk
#

STATIC_URL = '/static/'
STATIC_ROOT = BASE_DIR / 'static'
STATICFILE_FINDERS = [
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]
``` you need that last finder to make it use those paths
idle flame
#

I'd prefer static to actually be in the project root

#

is that plausible?

#

Rather than each individual app ( i think this will make deployment easier?)

#

sorry - I'm very new to django

dapper tusk
#

in prod, you use manage.py collectstatic and put them all into a single directory STATIC_ROOT

idle flame
#

so ./static/app/ image or css or etc

#

Sorry - this is bloating the scope of the problem right now.

dapper tusk
#

so you can have them per app and still just have a single path from which to route static files with the server

idle flame
#

okay, so I duplicate the same image across multiple apps - then i collectstatic at the end?

dapper tusk
#

you do not need to duplicate it

#

it can just be in a single app

idle flame
#

I can crossreference an app to look into another apps static?

dapper tusk
#

every app can use every static file

jagged lark
#

In production you usually not make django server the statics, for speed reasons

idle flame
#

this is why I was trying to keep it out of the app folder

#

but so far as I'm understanding, the filestructure is:

#

mainproject/app1/static/app1/img/img.jg

#

mainproject/app2/static/app2/img/img.jg

jagged lark
#

You could make your static root be a folder outside of the app, usually /var/www/statics

idle flame
#

I'm so sorry, I know that this is very basic. I've really hit a brick wall on the docs with this

dapper tusk
#

django has a way to copy all static files into a single directory

#

so app/static/img/img.png ends up in /var/www/img/img.png

#

you could also use the STATICFILE_DIRS to add another path to find static files

idle flame
#

it refactors all my templates at that time?

dapper tusk
#

templates are something else. They are not static files

#

those are served through django

idle flame
#

where my templates call my static files*

dapper tusk
#

ah, no. The URL is the same

idle flame
#

% load static %}
<img src="{% static "my_app/example.jpg" %}" alt="My image">

#

this bit is what I'm really messing up with here

dapper tusk
#

that would be stored in my_app/static/my_app/example,jpg in dev

jagged lark
#

Django will make sure that the url still points at the right static no matter where you store it

idle flame
#

okay, so to recap:

#

STATIC_URL = '/static/'
STATIC_ROOT = BASE_DIR / 'static'
STATICFILE_FINDERS = [
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]

#

i now create a folder mainproject/app1/static/app1/img/img.png

#

and use it this way? that is best practice for dev?

jagged lark
#

For development, you donโ€™t need to care about that afaik

dapper tusk
#

yeah, once you have that, {% static 'app1/img/img.png' %} should find it

idle flame
#

thank you very much for the help. I'll try applying it like this now

#

out of curiosity I need to deploy this eventually - I'm not a dev or anything. is it possible to pay someone to assist with the deployment in a safe way? Hiding the secret key, removing debug etc.

it's not a pet project or small thing. I've been lumped with the project at work and the backend has sensitive info. I need to move the database over to something more secure for production etc.

#

obviously I can't just deploy sqlite with debug true and I don't trust myself to do this correctly.

dapper tusk
#

there is the deployment checklist in django

#

but I don't think you can have someone deploy without exposing sensitive data

idle flame
#

I suppose this is a later problem.

drifting shell
#

Hi, can I ask a question bout Flask in here?

idle flame
#

Many thanks for all your help - it's very much appreciated.

dapper tusk
#

you can Dzony

idle flame
#

I will try applying this now and If I struggle I'll come back with some clearer questions.

drifting shell
#

Ok, so it's a simple question, but I'm newbie...
how can I return multi values from flask?
I've tried with a dictionary, but it doesn't work that way

#

I want to pass a value to another file, and render a template at the same time

quasi berry
#

.

drifting shell
#

.

quasi berry
#

hru@drifting shell

idle flame
#

Bizarrely it's still not working

#

I'm doing something wrong and I have no idea.

#

I have this;

#

STATIC_URL = '/static/'
STATIC_ROOT = BASE_DIR / 'static'
STATICFILE_FINDERS = [
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',

#

and I still get an unresolved template reference

dapper tusk
#

show a screenshot of the error

idle flame
#

soo i get the get request: [21/Sep/2020 16:39:53] "GET /static/img/asl-logo-nav.png HTTP/1.1" 404 1686

#

totally fine

#

no image shows

#

Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/static/img/asl-logo-nav.png
'img\asl-logo-nav.png' could not be found

You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.

dapper tusk
#

and does a path like myapp/static/img/asl-logo-nav.png exist?

idle flame
#

yes

dapper tusk
#

that is very odd

idle flame
#

I tried to PM you

#

but I can't because of your discord settings to show you

dapper tusk
#

try running manage.py collectstatic and see if you end up with the file in the directory it makes

idle flame
#

one second

#

132 static files copied to xxxx

#

waait

#

but not this image

#

hang on. I used bootstrap, it seems to have created the bootstrap static

#

i had an error in pycharm

#

and i said download the cdn

#

files

#

wait no, forget that

#

its only the admin static files it has pulled

#

are you willing for me to quickly screenshare you?

#

Im sure its something stupid

drifting shell
#

hru@drifting shell
@quasi berry not good, andU?

native tide
#

is it easy going from flask to django?

drifting shell
#

Define 'easy'

hallow jacinth
#

Hey do you guys know any solid security tutorials? I am making a social media app, and I want to learn about the different type of attacks I should watch out for and how to prevent them the best I can.

strange briar
#

the framework you use probably has a guide in this topic

#

is it easy going from flask to django?
@native tide you just need to learn to use the django tools, with flask you build most of the things by yourself while django has a lot of implementations to make you develop your application faster but it's relatively easy yes

hallow jacinth
#

okay I look through the flask documentation to see if they have anything on it

strange briar
#

I don't know about flask but Django for example has a part dedicated to it, anyway you should be able to find what you're looking for

#

else you can do raw researches on OWASP top 10

#

and you can learn each vulnerabilities and implement securities about it

hallow jacinth
#

okay ty

strange briar
#

Anyone use fastapi ? I'd like to know your opinion about it seems that many people talk about it right now

zealous siren
#

I've used it

#

it's great at what it does

strange briar
#

and what would be the main reason to choose it over flask or django in your opinion ? i've read that it's good for AI APIs due to the speed

zealous siren
#

It's ability to rapidly stand up and it's focus on REST APIs

#

I'm pretty not pro Django for REST APIs since DJango is massive and brings alot of baggage with it

strange briar
#

yes i also don't like much django REST for the same reason

native tide
#

hi react isnt making an application for me. I get this The directory . contains files that could conflict:

website1.js

zealous siren
#

probably biggest reason it's used is it's comfortable and DJango ORM is pretty good

#

Seijin, you can't go wrong using FastAPI

#

and it works well anyways with SPAs so it's useful for regular web development

strange briar
#

thanks rabbit i'll spend some time learning it ๐Ÿ™‚

native tide
#

hi
i have a table which i made it have circular borders, but when i add the link to bootstrap the borders become squares, without me adding any new classes or ids, why could this be happening?

td{
  height: 150px;
  width: 150px;
  text-align: center;
  border: 5px solid black;
  border-radius: 50%;

}
native tide
#

is ruby good for backend

dapper tusk
#

yes

warm marlin
#

what is difference btw backend and frontend?

dapper tusk
#

backend runs on your servers, frontend is what your users run

warm marlin
#

oookay , got it
but can u explainn more

native tide
#

is ruby better than python

zealous siren
#

Itโ€™s different

#

Itโ€™s seemed to lost its popularity

dapper tusk
#

ruby used to be a major backend language, it is still alive, albeit not the hegemon it once was. I would personally prefer python, but rails is still a very solid framework

quick cargo
#

think python is slightly faster in terms of frameworks aswell

marble carbon
#

Well Github uses ruby, doesn't it?

dapper tusk
#

ye

zealous siren
#

Yep

#

but I wouldn't go on "$BigSite uses X so it must be best"

#

Once a site gets big enough with different teams working on things, just about every language will creep in

marble carbon
#

I mean yeah they must be using a lot of different languages

quick cargo
#

yeah

zealous siren
#

Sure, but that's every big site

quick cargo
#

Discord uses flask for their backend api, as well as rust and elixer in places

marble carbon
#

but they might as well be supporting ruby's development

zealous siren
#

still flask?

quick cargo
#

yh

#

flask + gevent

marble carbon
#

Oh nice

zealous siren
#

got it

#

I guess it's not surprising

marble carbon
#

so gevent can improve performance? even if it's a synchronous Framework?

quick cargo
#

well sorta

#

it gives you a stackless system similar to asyncio just with sync functions

#

it suffers the same issues are asyncio just without the inbuilt system

#

which is why there is an entire system built around the gevent or libsomething i forget designed to be non blocking for these 'sync' based event loops

marble carbon
#

libuv? I think

quick cargo
#

so they improve perfromance a tonne, if you use the right system

#

i think its libuv yh

zealous siren
#

also remember, they probably use a ton of flask containers with load balancers

marble carbon
#

yeah I mean definitely

#

gotta learn more about gevent pithink

quick cargo
#

its meh imo

#

its good for some stuff but a bit outdated now asyncio is stable

#

also alot less perfromant than asyncio

zealous siren
#

Discord has been around for a while

quick cargo
#

they only recently migrated to python 3 iirc

#

thats the sort of age of code we're looking at before asyncio was even a real thing

zealous siren
#

remember, reasons for company running X isn't because "It's best" but generally "It's what we have been doing"

marble carbon
#

ohh

#

I mean asyncio would require a rewrite but with gevent you can atleast scale up existing applications for sometime

quick cargo
#

ehh yes and no

#

its not a drop in replacement

#

you have to replace alot of blocking stuff just like you would have to asyncio

#

to get any sort of perfromance

marble carbon
#

ohhh

#

well async is the way to go then hmm

quick cargo
#

if you want to get the most out of a single thread yeah

marble carbon
#

async has started becoming popular only a couple of years ago, right?

dense slate
#

What are your favorite front-end libraries to use? Aiming for minimal but still covering most of the bases. I use python/django for backend if that matters.

marble carbon
#

for Django take a look at

maiden kraken
#

hello is anyone familiar with deployment on heroku? I am getting the most stupid error:

-----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure ! Push failed