#web-development

2 messages · Page 28 of 1

prime ridge
#

Hmm. Okay... So for an order, a user creates an object containing form data, and also an object containing data for what they want to actually order

#

So shouldn't there be a relationship between that form data and the stuff they're ordering?

#

Specifically, I'd say doing something like... And someone correct me if this is bad design here

frigid egret
#

Ok, i'll try that.

#

Hm, wait

#

I don't get the first part

#

I have a model with foreign keys to both pizza object and user form. So I already have those.

prime ridge
#

So you have a third object that foreign keys to both?

frigid egret
#

yes

prime ridge
#

What if they want more than one pizza?

frigid egret
#

And it adds its own data as well

#
class OrderItem(models.Model):
    user_form = models.ForeignKey(Order, on_delete=models.CASCADE)
    item = models.ForeignKey(Pizza, on_delete=models.DO_NOTHING)
    size = models.CharField(max_length=100)
    quantity = models.CharField(max_length=100)
#

Size and Quantity are fields it gets from json since that's user choice

prime ridge
#

So for each order, with the way you've designed it, you have...

  1. One user_form
  2. One or many Pizzas.
  3. One or many OrderItems (equal to the number of Pizzas)
#

Yes?

frigid egret
#

not just for each order but for each item in the order.

#

say, if a user were to add 3 types of pizzas to the cart and then make that order, there are 3 objects created, for each pizza.

#

And they all contain a link to related pizza object, user form and user choice of size and quantity

prime ridge
#

Three Pizza objects. For the order, right. But also three OrderItem objects -- one for each pizza. Correct?

frigid egret
#

pretty much

prime ridge
#

But they all have a common user_form. Hmm.

#

You may have too much abstraction.

frigid egret
#

Well, OrderItem is referencing to each pizza so Pizza objects stay the same

#

Let me clarify.

#

Say there are 5 pizzas on the website, each can be created in the admin panel. Then when a user orders a pizza, there are still 5 of them. But OrderItem now knows which one the user chose.

prime ridge
#

Ok. So this is not a dominos create-your-own topping kind of thing. Management provides the menu

frigid egret
#

I could post my code if that helps

ruby palm
#

Sorry I thought this channel wasnt in use

frigid egret
#

@prime ridge yep, it's a basic web-store. It could have been shoes instead of pizzas. 😄

prime ridge
#

I'm starting to understand the reasoning behind your design decisions (my brain went to "oh well why don't we [do what you did]") but I think this could be simplified thonk

frigid egret
#

But there are multiple OrderItem objects for each order and I still don't get how to group them into a single item in admin panel

prime ridge
#

Django's a little funny about storing lists, right? Like, if you could have a list or a dictionary field, you'd just need one order object for each order.

frigid egret
#

Yea, but because I have those extra fields: size and quantity, it makes it tricky so I decided to separate those objects

#

Instead of having a list of pizzas and several sizes and quantities.

#

I have been working with sqlite thise whole time. Databases are out of my knowledge so far.

ruby palm
#

:thonk:

#

:thonk:

#

Blitz do you have nitro discord?

prime ridge
#

Nah but I got that from another discord

#

So, okay, let me just try to solve the problem as you have it instead of, erm, trying to tell you how you should redesign your entire project, gimme a sec to think

#

All OrderItems reference one user form. So the user form is the common element shared between all things relating to the order

frigid egret
#

I mean if that's poor design choice, I'd like to know how to not make that mistake again.

prime ridge
#

as mentioned before, you can add a calculated field to the user form model (call it an order model)

#

to get all OrderItems that reference it (a django query)

#

(this was step #2 above, maybe slightly modified)

#

then just add that field to the admin panel (step #3 above)

frigid egret
#

Ok, so I can display my Order objects in admin panel and then inside them have a list of related pizzas?

prime ridge
#

(assuming user form data == order) yes

frigid egret
#

Do i do it with Inline?

#

Here's my code, to be on the same page:

#
class Order(models.Model):
    name = models.CharField(max_length=100)
    phone = models.CharField(max_length=100)

    def __str__(self):
        return f"{self.name}, {self.phone}"


class OrderItem(models.Model):
    user_form = models.ForeignKey(Order, on_delete=models.CASCADE)
    item = models.ForeignKey(Pizza, on_delete=models.DO_NOTHING)
    size = models.CharField(max_length=100)
    quantity = models.CharField(max_length=100)

    def __str__(self):
        return f"item = {self.item}, size = {self.size}, quantity = {self.quantity}" \
            f", order = {self.user_form}"
prime ridge
#

I had something like this I implemented very poorly and ended up hating it but lemme go get the code while you do that

#

right. So you'd add a method to order to query all OrderItems with user_form referencing that order object -- lemme see what I can dig up

#
    def flags(self):
        return Flag.objects.filter(event=self.id)```
#

So, modifying this...

#
    def order_items(self):
        return OrderItem.objects.filter(user_form=self.id)```
#

You'd add that method to order

frigid egret
#

Ok, yea, that worked... Not perfect, but at least it's definitely closer to what I wanted to have

#
class OrderItemInline(admin.TabularInline):
    model = OrderItem


class OrdersAdmin(admin.ModelAdmin):
    list_display = ('name', 'phone')
    inlines = (OrderItemInline,)


admin.site.register(Order, OrdersAdmin)
prime ridge
#

Let me show you a whole lot of ugly. I hate this thing but it should give you some ideas

frigid egret
#

Ok

#

Uh...

prime ridge
#

Key part of this: I added a readonly field called "flags_html" which basically iterated over all of the related flags and provided a list output of them. The point is, you can override the HTML output handles the field you tack-on

#

so, if you don't like what it says or how it looks, there are lots of ways to override it

#

but yeah the way I did it was not pretty

frigid egret
#

Ok. Well, I'm trying to use standard views as much as possible. Didn't have to override any html yet.

prime ridge
#

lollll

#

good call

frigid egret
#

Since I don't know natural limitations of Django so far.

prime ridge
#

Yeah neither did I which is probably how I ended up with that hack deletes my shame

frigid egret
#

Well, now I know what to avoid if possible 😄

#

And thank you for pointing me in the right direction!

prime ridge
#

np

#

good luck

frigid egret
#

btw, you said previously

ruby palm
#

Hey

#

What is the {% block content %} {% endblock content %} for in django template language?

frigid egret
#

instead of, erm, trying to tell you how you should redesign your entire project

#

How would you approach the task?

#

@ruby palm You use those tags to transfer your html content to another page. Don't remember the name of this method.

ruby palm
#

extends?

frigid egret
#

Oh, right

prime ridge
#

Hmmm, I'm not confident in saying I have one objective right way to do it but I might just serialize the order as JSON and store it in a JSONField (postgres only) -- or just put it into a CharField (any db).

{pizza_id: quantity} -- so like {1: 2, 3: 1} to say 2 of pizza id 1, 1 of pizza id 3. Then just build off that.

frigid egret
prime ridge
#

So then you just have one object per order, with any complicated listy information being serialized

ruby palm
#

Thank you!!! @frigid egret

frigid egret
#

Also this

#

@prime ridge Yea, that's sounds efficient too. I'll keep that in mind

prime ridge
#

@ruby palm to chime in blocks are cool because it lets you do stuff like...

base.html

{% block head %}
<head>
    <title>MySiteName</title>
    {% block extra_head %}{% endblock %}
</head>
{% endblock %}
...```

home.html
```html
{% extends 'base.html' %}
{% block head %}
<head>
    <title>Ha I overrided the entire head</title>
</head>
{% endblock %}
...```

other.html
```html
{% extends 'base.html' %}
{% block extra_head %}
<script async src="https://HaImJustAddingToTheHeadNotReplacingIt.com/script.js"></script>
{% endblock  %}
...
ruby palm
#

In line 4 of base.html, havent you missed a block before extra_head?

prime ridge
#

yes, lol, ty

ruby palm
#

Ohh it makes a lot of sense now

prime ridge
#

SORRY, ahhh

ruby palm
#

Thank you so much @prime ridge and @frigid egret !!!

#

@prime ridge you must be very careful with those things though, you might confuse new people

frigid egret
#

yw ^_^

prime ridge
#

Yeah, my bad. I hate when someone's showing me an example and I get caught up trying to understand the logic behind a typo

pastel dove
#

Im having a hardtime deploying a django app to heroku

#

I see this in my heroko logs:

ModuleNotFoundError: No module named 'PROJECT_NAME'
My Procfile is:
web: gunicorn PROJECT_NAME.wsgi --log-file -
Can anyone confirm if this is right?

#

my projects name is "personal_portfolio"

#

but I wasn't sure if PROJECT_NAME is an env var

vagrant adder
#

if PROJECT_NAME is env var then do $PROJECT_NAME

#

i think that should work

pastel dove
#

I didint set it as an env var

#

I wasn't sure if that was a built in var

vagrant adder
#

what is your project name

pastel dove
#

personal_portfolio

vagrant adder
#

then do that

pastel dove
#

I get a module not found error

#

but let me try again

#

Now I get this error 2019-07-19T22:55:40.844492+00:00 app[web.1]: File "/app/.heroku/python/bin/gunicorn", line 11, in <module> 2019-07-19T22:55:40.844609+00:00 app[web.1]: sys.exit(run()) 2019-07-19T22:55:40.844613+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 61, in run 2019-07-19T22:55:40.844738+00:00 app[web.1]: WSGIApplication("%(prog)s [OPTIONS] [APP_MODULE]").run() 2019-07-19T22:55:40.844743+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/app/base.py", line 223, in run 2019-07-19T22:55:40.844994+00:00 app[web.1]: super(Application, self).run() 2019-07-19T22:55:40.844997+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/app/base.py", line 72, in run 2019-07-19T22:55:40.845121+00:00 app[web.1]: Arbiter(self).run() 2019-07-19T22:55:40.845124+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/arbiter.py", line 232, in run 2019-07-19T22:55:40.845276+00:00 app[web.1]: self.halt(reason=inst.reason, exit_status=inst.exit_status) 2019-07-19T22:55:40.845280+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/arbiter.py", line 345, in halt 2019-07-19T22:55:40.845519+00:00 app[web.1]: self.stop() 2019-07-19T22:55:40.845522+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/arbiter.py", line 393, in stop 2019-07-19T22:55:40.845725+00:00 app[web.1]: time.sleep(0.1) 2019-07-19T22:55:40.845728+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/arbiter.py", line 245, in handle_chld 2019-07-19T22:55:40.846156+00:00 app[web.1]: self.reap_workers()

ruby palm
#

Arent there some help channels? What is this channel for? I know its for help and all but why does it exist if there are other help channels?

prime ridge
#

topic chat/help channels are for both discussion and subject-specific support while help channels are for general python support

ruby palm
#

Ohh I understand

cursive cairn
#

quick question: I want my Flask app to access all files in a certain Folder directory on the clients local system. I want to upload all of these files to my web server. How would I achieve this using Flask?

#

How do I develop the Flask "Select folder" dialog with native file explorer?

tough star
#

How do I vertical align a card in Bootstrap 4?

prime ridge
#

@cursive cairn Wait, you're wanting to access someone's local file system using a webserver on a remote machine??? Not sure what you're aiming for.

cursive cairn
#

@prime ridge I’ll try to clarify. The server is run locally. I want the user to select a folder on their computer so the local server can analyze files at that folder without moving files (large file volume).

prime ridge
#

the server runs on the client computer

cursive cairn
#

Everything is run on clients machine

prime ridge
#

ok

#

Any reason you're choosing to use flask for this?

cursive cairn
#

Not necessarily. Just familiar with Flask

#

And because I’m familiar, I’ve already built a large portion of my program on Flask

prime ridge
#

Well, I figure you can do one of two things. You could use tkinter for the file selection bit (assuming you want it to just be a terminal and a file selector)

#

is the flask app using, um

#

a web interface?

cursive cairn
#

Yes

prime ridge
#

ohhh

cursive cairn
#

Sweet, thanks

prime ridge
#

So this would be the interface part

#

you'd just need to figure out how to get flask to accept that input -- interested to see what that'll look like.

cursive cairn
#

I’ll update you - thanks for the help!

prime ridge
#

np!

ruby palm
#

Could someone explain to me what exactly is <nav> for?

#

I don't see any graphic change when I use or not use <nav> tag

#

What is it exactly for?

ruby palm
#

Is there any free complete source to learn HTML and CSS?

proper hinge
#

MDN is a good resource in general

fathom horizon
keen sphinx
#

@ruby palm not every tag has a visual impact, many of them don't

#

and they are just to make the code more readable, so you don't have a million divs

#

they are "semantic" tags

#

I assume they also help search engines to look for certain tags and grab the contents, like Google does when it shows you a card of something you typed in, but that's speculation, I haven't examined the HTML of any webpage to see if this is true

ruby palm
#

So those tags are useful for making wrappers?

keen sphinx
#

I don't know what you mean, I'm not really frontend savy

#

this is just one of the few things I know

ruby palm
#

Oh ok

#

What does the attribute name mean?

lime thicket
#

The name attribute is used in form posts to identify that fields data

ruby palm
#

Ohhhh okok

#

Thanks

#

Then what are IDs for? Like the id that is in the image

keen sphinx
#

does anyone know how Flask handles generators when streaming with Response(somethingIterable(),mimetype='whatever')? does it automatically "unwrap" anything that recognizes as bytes?

#

because if something yields an integer or something and I cast it to bytes inside the Response, it works but what it prints is the address of the iterable object

#

which of course is ugly but I'm just trying to understand how it works

lime thicket
#

@ruby palm an ID could be used for CSS or JavaScript manipulation easier then an attribute like name. Sometimes you need to interpret data between the form and your API and leveraging the ID with $(‘#<ID>’) makes that easy

olive wharf
#

It should return something, but is not readable as json or plaintext

proper hinge
#

Looks like they are tuples

#

Delimited by a space

#

Each element uses a comma delimiter

#

I.think the ones at the bottom are weird cause those are for clues etc

#

It's readable as plain text to me (in a browser) so you should just be able to do a get request and simple string parsing

olive wharf
#

Yeah, it was a csv

#

I found another wrapper and figured out what they did

#

Just a csv of rank, level ,exp 🤷

native tide
#

C10K, C100K possible with redis access on python production-ready?

round saddle
#

Do you know how to make an image smaller with CSS?

vagrant adder
#

i think height and width can do that

#

but don't quote me on that one

frigid egret
#

Hi all

#

I need an advice on managing inlines in Django

#

I'm working on a dummy pizza store website for practice.

#

I have orders which contain user data, and then in each order I have a list of pizzas. That's where I use Inline to get pizza objects.

#

I would like to add anew field to the order list: total price. But first I have to get all pizza prices, multiply them by quantity. Basically, I have to get those values from an inline object and I only know how to display that said inline object.

ruby palm
#

@lime thicket Ok, thank you!!!

#

What does mean that HTML its an hypertext language?

ruby palm
#

If there are classes, why do we need ids in HTML and CSS?

proper hinge
#

As you may know, IDs are unique unlike classes

#

Meaning only one element may have a certain ID

#

But it's really a semantic difference. Nothing is stopping you from using classes for everything, even if some of those classes are unique

#

But that's just bad practice

ruby palm
#

Oh ok

#

Thank you so much!!

#

And what's the difference between span tags and div tags?

proper hinge
#

I believe the difference is in how they are styled by default

#

spans are displayed inline while divs are blocks

#

Something like that

#

so you could use a span if you want to have some inline element in a paragraph of text

ruby palm
#

Oh, ok!! Thank you, kind sir!

feral aspen
#

Hey guys im trying to make a website to host my portfolio, I was wondering if you had any suggestions as to where to store my projects to link on the website

polar wasp
#

it also makes a difference for nesting if you have other elements and are using HTML5 rules, a div can't nest inside a <p> tag, for example, and will automatically close the preceding one

#

@ruby palm

rigid laurel
#

Mesha. A github profile is usually whats linked to. If you mean hosting them, then a cheap vps is an option

ruby palm
#

@polar wasp oooOOOooo

#

Thank you!

ruby palm
#

views.py:

from django.shortcuts import render

# Create your views here.
def home(request):
    return render(request, "coffees/home.html", {'title' : 'Home', 'where_css' : 'css/styles.css'})

templates/coffees/base.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    {% if title %}
        <title>Coffees - {{title}}</title>
    {% else %}
        <title>Coffees</title>
    {% endif %}

    {% if where_css %}
        <link rel="stylesheet" href='{{where_css}}'>
    {% endif %}
</head>
<body>
    {% block content %}
    {% endblock content %}
</body>
</html>
#

templates/coffees/css/styles.css:

h1 {
    color: red;
}
#

templates/coffees/home.html:

#
{% extends "coffees/base.html" %}
{% block content %}
    <h1>Welcome to the home page!</h1>
{% endblock %}
#

However , "Welcome to the home page!" doesnt become red :(

#

Why does it happen?

#

Help, please

#

I dealt with this problem the whole afternoon and still no solution

vagrant adder
#

you know what

#

try ctrl-shift-r

#

hard refreshing

ruby palm
#

Still doesnt work

#

:(

full arch
light wave
#

just realized this isnt a help channel my b

ruby palm
tribal cobalt
#

Jafactor can you use dev tools to see if there is a 404 error for your style sheet?

frigid egret
#

Hi all

#

I'm trying to run custom authentication on my website (study project)

#

So that users only need phone number and password to be able to register and log in

#
from django.db import models
from django.contrib.auth.models import (
    AbstractBaseUser, BaseUserManager
)


class UserManager(BaseUserManager):
    def create_user(self, phone, password=None, is_staff=False, is_admin=False, is_active=True):
        if not phone:
            raise ValueError('User must have a phone number')
        if not password:
            raise ValueError('User must have a password')

        user_obj = self.model(
            phone=self.phone
        )
        user_obj.set_password(password)
        user_obj.staff = is_staff
        user_obj.admin = is_admin
        user_obj.active = is_active
        user_obj.save(using=self._db)
        return user_obj

    def create_staffuser(self, phone, password=None):
        user = self.create_user(
            phone,
            password=password,
            is_staff=True,
        )
        return user

    def create_superuser(self, phone, password=None):
        user = self.create_user(
            phone,
            password=password,
            is_staff=True,
            is_admin=True,
        )
        return user


class User(AbstractBaseUser):
    phone = models.CharField(max_length=100, unique=True)
    name = models.CharField(max_length=100)
    email = models.EmailField(max_length=100, unique=True)
    active = models.BooleanField(default=True)
    staff = models.BooleanField(default=False)
    admin = models.BooleanField(default=False)

    USERNAME_FIELD = 'phone'
    REQUIRED_FIELDS = []

    objects = UserManager()

    def __str__(self):
        return self.phone

    # def get_full_name(self):
    #     return self.phone
    #
    # def get_short_name(self):
    #     return self.phone

    @property
    def is_active(self):
        return self.active

    @property
    def is_staff(self):
        return self.staff

    @property
    def is_admin(self):
        return self.admin
#

I also added AUTH_USER_MODEL = 'users.User' to my settings.py

#

But when I try to register a new superuser (I've wiped my database to avoid conflicts) it gives me this error:

#
Traceback (most recent call last):
  File "manage.py", line 21, in <module>
    main()
  File "manage.py", line 17, in main
    execute_from_command_line(sys.argv)
  File "E:\Dev\Projects\DjangoPizzaShop\venv\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line
    utility.execute()
  File "E:\Dev\Projects\DjangoPizzaShop\venv\lib\site-packages\django\core\management\__init__.py", line 375, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "E:\Dev\Projects\DjangoPizzaShop\venv\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv
    self.execute(*args, **cmd_options)
  File "E:\Dev\Projects\DjangoPizzaShop\venv\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 61, in execute
    return super().execute(*args, **options)
  File "E:\Dev\Projects\DjangoPizzaShop\venv\lib\site-packages\django\core\management\base.py", line 364, in execute
    output = self.handle(*args, **options)
  File "E:\Dev\Projects\DjangoPizzaShop\venv\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 156, in handle
    self.UserModel._default_manager.db_manager(database).create_superuser(**user_data)
  File "E:\Dev\Projects\DjangoPizzaShop\users\models.py", line 37, in create_superuser
    is_admin=True,
  File "E:\Dev\Projects\DjangoPizzaShop\users\models.py", line 15, in create_user
    phone=self.phone
AttributeError: 'UserManager' object has no attribute 'phone'
#

Can someone help me with that please?

frigid egret
#

Anyone?..

timid arrow
#
user_obj = self.model(
            phone=self.phone
        )

should be

user_obj = self.model(
            phone=phone
        )
frigid egret
#

Tried that, same result

#

@timid arrow Oh wait, I just double checked and now it works. Odd, I must have made some mistake the first time then. Thanks!

feral aspen
#

@rigid laurel thank you

native tide
#

Anybody here have any experience sending an PIL generated image to your website and displaying it?

#

I've successfully sent my image and received it but since its in binary I can't just display it.

#

Might not even be binary though, I have a hard time reading it. Anybody remember how you did it?

turbid solar
#

how do i differentiate users in flask?
for example, i have a form that saves the data as JSON file
i want to name the json file differently per user, so that when the y try to change it, the server knows which JSON file to change

vagrant adder
#

There is this thing called database

turbid solar
#

can i use sessions?

vagrant adder
#

Where are you storing user data

turbid solar
#

server side

#

i guess i can use sessions

#

thanks :> i didn't get how sessions work clearly at first since i thought all users access the same dictionary.

vagrant adder
#

Umm

#

You doing me a confusion

turbid solar
#

sorryy.. i thought if i set the session['user'] when i access the login page from my computer it would replace the session['user'] that was setted when i logged in from my phone

#

i guess that wasn't the case

vagrant adder
#

Wait

#

Let's go from beginning

#

What do you want to do

turbid solar
#

i want to differentiate each user

vagrant adder
#

You gonna need a storage on your server

#

And most common case to deal with that is database

turbid solar
#

i didn't see the need for a database since it's only a local/LAN webserver.

vagrant adder
#

Yeah but if you save something on a session, that's gonna be available only on one browser session

#

Only one user

turbid solar
#

once the browser is closed, the session is gone?

vagrant adder
#

Yes but some data is remembered

turbid solar
#

i'm going to use the session to differentiate users

vagrant adder
#

I would strongly recommend making a database

turbid solar
#

then save the json on a folder named using the username stored in session

vagrant adder
#

Databases are quite fast nowdays and easy to setup

turbid solar
#

i'd consider that too

#

if i see some inconsistencies with the flow i want to implement

#

thankss

vagrant adder
#

Session only lives in a browser, not on a server

turbid solar
#

lemme make some pseudo code

#

app routing on /login

set session['username'] = form data

app routing on /settings

create json from form data
save on folder named session['user']
vagrant adder
#

Are you gonna use only one device or more

turbid solar
#

more

vagrant adder
#

Then use a database my dude

#

What lives in one's session, doesn't live on other's

turbid solar
#

What lives in one's session, doesn't live on other's

vagrant adder
turbid solar
#

that's actually what i need

#

but i guess it wouldn't hurt to use a database

#

so yeah

#

thanks for convincing me :>

vagrant adder
#

Let me get home aight?

#

I cant type while on work :p

#

I'll ping you when i get home

turbid solar
#

okay :3

uncut orchid
#

hi anyone here?

#

am working with flask

#
from SecondTest import func1
from SPEED2 import NetSpeed
import time
import multiprocessing
app = Flask(__name__)


@app.route('/')
def student():
   return render_template('input.html')


@app.route('/result', methods=['POST', 'GET'])
def result():
    ip1 = request.form['IP1']
    sp1 = '8200'
    ip2 = request.form['IP2']
    sp2 = '8210'

    print(ip1)
    print(ip2)

    speed = multiprocessing.Value('f', 0)
    ping = multiprocessing.Value('f', 0)
    endFlag = multiprocessing.Value('i', 0)
    endFlag.value = 1

    manager = multiprocessing.Manager()
    shared_list = manager.list()

    p1 = multiprocessing.Process(target=NetSpeed, args=(ip1, sp1, speed, ping, endFlag))
    p2 = multiprocessing.Process(target=func1, args=(ip2, sp2, speed, ping, endFlag, shared_list))

    p1.start()
    time.sleep(20)

    p2.start()
    p1.join()
    p2.join()

    # print(shared_list)
    return render_template("result.html", shared_list=shared_list)


if __name__ == '__main__':
    app.run(debug=True)
#

what the above program does is: get 2 IP address as input, do some process. Process p1 updates its values to Process p2.

#

Process p2 has access to shared variable named - shared_list, whose value changes every 30sec. I want to display this dynamically changing shared_list in the front end.

#
   <body>
    <form action = "/result" method = "POST">
    <p>IP address and Port number of device 1 <input type = "text" name = "IP1" /></p>
    <p>IP address and Port number of device 2 <input type = "text" name = "IP2" /></p>
    <p><input type = "submit" value = "submit" /></p>
</form>
   </body>
</html>```
#

Above input.html takes 2 IP address as input.

#
  • IN SHORT - PROCESS WHICH HAS ACCESS TO SHARED_LIST, KEEPS CHANGING THE VARIABLE'S VALUE'. I MUST DISPLAY THE CHANGES IN FRONT END *
#

how do i display the changes

stray nexus
#

you have to either pool the server from the client periodicaly, or use some kind of event to send data at the server intiative.

uncut orchid
#

I dont know how to implement that unfortunately

#

and thats where i am totally stuck and clueless

round saddle
#

Hey. I was using this in CSS but it didn't change anything but it should. Do u know what might be the problem?

p{
  font-family: Arial;
}
polar wasp
#

do you have the Arial font installed?

#

check the paragraph in the browser inspector tool to see if there are any other CSS rules that might be overriding it.

round saddle
#

Nvm

#

Thanks!

#

I had Arial in body 😅

round saddle
#

Hey. I wanted to make an animation. When user would hover on a word "Leaders" it would change from red to green. What might be wrong?
CSS:

Leaders:hover{
  animation-name: changing;
  animation-duration: 3s;
  animation-iteration-count: 1;
}

@keyframes changing {
  from {color: #b8b8b8;}
  to {color: green;}
}

HTML:

<li class="Leaders"><a href="#"><strong>Leaders</strong></a></li>
native root
#

@round saddle you're missing the . in front of Leaders in the css

round saddle
#

Ok

#

XD

#

I'm dumb

native root
#

lol

round saddle
#

Thanks!

native root
#

nw

stone heath
#

Guys, if I buy domain on sale and registrar shows that renewal price is $9, will it stay same price even after a year?

#

I mean sale price is 3 and renewal is 9

vagrant adder
#

You pay it for 3, next time it gets the renewal price is 9

stone heath
#

@vagrant adder thank you.

smoky swan
#

hey guys! I made something that manipulates data and calculates a few statistics based on a postcode.
Expected behavior: user inputs a postcode (44400) and an essence type (gazole)

# the correct answer is this ((name, address), (average prices over 12 months)) /thanks @ jojo#2133:
(('E.Leclerc Station Service', '10 Rond-Point de la Corbinerie, Rezé'), [1.348, 1.319, 1.317, 1.352, 1.41, 1.418, 1.395, 1.401, 1.427, 1.475, 1.426, 1.358])
(('E-Leclerc service station in Reze Cedex', '1 rue Ordronneau, Route de Pornic, Rezé'), [1.347, 1.309, 1.321, 1.36, 1.411, 1.416, 1.387, 1.411, 1.432, 1.473, 1.408, 1.329])
(('E.Leclerc Station Service', '10 Rond-Point de la Corbinerie, Rezé'), [1.343, 1.312, 1.311, 1.342, 1.414, 1.412, 1.391, 1.398, 1.427, 1.473, 1.408, 1.354])

The issue here, is that, when I launch my flask server, it does correctly starts and on user input, follows the expected behavior — but only on the first time, when I go back, refresh the page (anything unless I restart the flask server (dev or prod btw)), it appends to the html output in a weird way, and does not reset the content, and display the nth request (see attached)

Flask script gist : https://gist.github.com/ceIia/7780c207c30e51d57ef8b817ad6e4d34 (I only added the flask related files, not the actual scripts, because I tried them directly from the CLI and it was working fine, giving the expected results everytime- which made me suppose it does come from the Flask server somewhere? Tell me if you need anymore information).

Thanks a lot for taking the time to read this, sorry for the wall of text!! 😅

Gist

GitHub Gist: instantly share code, notes, and snippets.

native root
#

I don't see anything wrong with your flask script, try printing the results from yearly_average_constructor after each request

#

I suspect something in there is not resetting

vagrant adder
#

it does not get reset?

#

i think that's because you are constantly writing to a file and between requests it is filled with data from previous requests

broken roost
#

can anyone help me out is $element.innerText and $element.href the proper syntax?

native root
#

I suspect you'll have the problem of it selecting the h3, not the A inside the h3

vagrant adder
#

$?

#

That is jquery

#

element.innerText is native js if i recall correctly

round saddle
#

Hey. I have a small text which is in this class. There is also another one, (Leaders) when someone hovers on it then it should'v cover this text in class About us but even with z-index.

.Leaders:hover{
  animation-name: changing;
  animation-duration: 2s;
  animation-iteration-count: 1;
  animation-fill-mode: forwards;
  z-index: 5;
}
.About-us{
  color: #384e69;
  position: fixed;
  font-size: 5vw;
  left: 38vw;
}

What might be the problem?

#

The animation works

#

but the text using class About us covers it

vagrant adder
#

position: Absolute?

broken roost
#

what should i be using ? im running out of ideas since nothing seems to work

vagrant adder
#

For about us

#

Try position absolute

native root
#

Z-index only functions on elements that are positioned something other than "static", which is the default

#

"relative" might be more helpful here

round saddle
#

Hmmm... I tried relative and absolute on Leaders class but it still doesn't work.

native root
#

We'd need to know a bit about the underlying html then

#

Z-index controls the relative placement of "stacking contexts" in their parent "stacking context"

#

so, if you've already got a container that doesn't also contain the "about us" but is also positioned nonstatically, then that one must be greater in z-index than the about us label

#

also note opacity and transforms trigger stacking contexts

round saddle
#

This is the HTML

<body>
    <header>
           <img src="https://i.imgur.com/e4IPafW.jpg">
            <nav>
                <ul>
                    <li><a href="#"><strong>Join us</strong></a></li>
                    <li><a href="#"><strong>Rules</strong> (not ready)</a></li>
                    <li class="Leaders"><a href="#"><strong>Leaders</strong>(not ready)</a></li>
                    <li><a href="#"><strong>In-game clans</strong>(not ready)</a></li>
                    <li><a href="#"><strong>Home</strong>(not ready)</a></li>
                </ul>
            </nav>
    </header>
    <div>
      <h1 class="About-us">About us</h1>
#

It's part of the whole, but it's part about this

native root
#

is header position:fixed or sticky?

round saddle
#

fixed

native root
#

right

#

so you'd need to elevate <header> to be higher than "About-us", since that's the interaction you're seeing

round saddle
#

so... I need to add z-index to it?

native root
#

Yes

#

z-index is contained within layers, and each layer is created whenever a stacking context is

round saddle
#

Ohh... It works now, Thanks!

native root
#

you can't break out of a z-index layer with z-index, so since <header> creates a new context that is below About-us's context, it doesn't matter what value that your leaders gets, since its flattened down into the one that <header> uses when it's compared to anything outside of <header>

round saddle
#

I have a question. Is this possible? I'd like to make an image transparent when I would hover on a text which is somewhere else (on the same website ofc)

native root
#

Depends on your constraints

#

If the image is next to or inside the hovered element, you can do it with css, via the adjacent sibling combinators and similar.

#

if it is not, then you can use javascript

round saddle
#

Wdym by "inside"?

#

This image is next to it

native root
#
<container>
    <item1>
        <hoveredelement>
            <elementinside></elementinside>
        </hoveredelement>
        <adjacentelement></adjacentlement>
    </item1>
    <untargetableelement></untargetablelement>
</container>
silent girder
#

Hello. Im working on Django app and i have one problem. Why i dont see tabulr and stacked admin in django admin?

native root
#

I don't think you registered your ItemAdmin class to the Item model

smoky swan
#

@native root : (message from 11:13am) yearly_average_constructor outputs the wrong behavior, so it actually might not be flask you're right, @vagrant adder. The thing is, I have in every python script called by the main Flask script, a variable_name = [] (or 0) at the start to make sure it starts clean everytime...
(I updated the gist to add the file from which it constructs the wrong list, if you maybe have an idea of what could be wrong)

https://gist.github.com/ceIia/7780c207c30e51d57ef8b817ad6e4d34#file-create_year_data-py

Gist

GitHub Gist: instantly share code, notes, and snippets.

silent girder
#

@native root 😄 fak! i spend 2h 😄

native root
#

pump_list and raw_array should be inside the function

#

unless you wish to keep the sticky behavior for some other module, at which point you can write a reset() function that reinitalizes them. If you do that, make sure to use global

smoky swan
#

ahhh, my bad then

vagrant adder
#

You got your problem solved? @smoky swan

smoky swan
#

trying

#

it worked, thanks @native root & @vagrant adder - you guys rule

vagrant adder
#

Cheers mate @smoky swan

smoky swan
#

hey! it's me again 😅
found this great tutorial online about chart.js and flask -> https://blog.ruanbekker.com/blog/2017/12/14/graphing-pretty-charts-with-python-flask-and-chartjs/
here's my issue: I have a list of gas stations with different datasets everytime (as shown on the screenshot): what would be the workaround to reset the js script datasets to generate a new graph everytime?

also, at the end, i'll be supposed to generate a big graph with every line stacked, which is done by giving every dataset at once to chart.js, and even that is another whole thing.

what would be the best workaround this? should I have multiple instances of the js script running for each graph? (chart.js docs : https://chartjs.org/docs/latest/)
(sorry again for the 2nd wall of text today- thanks so much for the help you guys gave me: i've progressed so much in python over the last two weeks thanks to your help)

flint breach
#

you simply make a function

#

that has input params the parameters of the graph

#

and renders the graph for the specified input

#

if for example you're scraping data, and a user inputs a link for a specified petrol station

#

you simply fetch the data, and return it, and then write a js function to handle the data with the specified input

#

and that's that

vagrant adder
#

make a request to the database and collect the data.
After that shape data in any way or form you need and just pass it as argument in chart.js Chart object

#

chart.js updates realtime

ruby palm
#

Hello

#

Well this is embarrasing

#

Im gonna to ask a question I already asked in this channel, two weeks ago

#

Because I forgot what the answer is and as I'm a dumbass I didn't save it into any archives

#

Is there a free source for learning data structure fundamentals and/or pattern designs?

native root
#

FYI you can search pretty nicely, there'sa bar in the top right

#

from: jafactor in:web-development

smoky swan
#

@vagrant adder @flint breach yeah- but that would not work if I have to display multiple graphs at once

flint breach
#

Why not

vagrant adder
#

Why

#

Make multiple requests

#

On my internship i had to graph jenkins tests and i used mutiple charts at once

flint breach
#

exactly

smoky swan
#

I think I'm not following on the last part- I would have as many copies of the js script in my html page as I have graphs rendered?

vagrant adder
#

Yeah

#

Although, you can make 2 instances of Chart object in a single js script

#

But i'd recommend separating each instance im separate scripts

smoky swan
#

hmmm- i hope it doesn't affect performance too much

vagrant adder
#

No it doesn't

#

Js is hella fast

smoky swan
#

oh okay then ahah

#

thanks

flint breach
#

v8 bejbi

vagrant adder
#

@flint breach where you from

flint breach
#

Slo, why

vagrant adder
#

Cro

#

Just askin

tough star
#

How do I disable the jQuery UI sortable's windows auto resizing?

vagrant adder
#

jQuery doesn't resize

#

Check your css and html viewport tags

ruby palm
#

Ok, thanks @native root !!

next bane
#

would django be better for a larger scale api than using something like flask or quart?

vagrant adder
#

Both flask and django are pretty scalable

native tide
#

How do I turn on debugging in Flask using Powershell? I have tried $env:FLASK_ENV="development" but then I get an error No module named C:\Users\shado\python-scripts\microblog\venv\Scripts\flask

vagrant adder
#

Try set FLASK_ENV="development"

#

@native tide

native tide
#

that doesn't do anything

#

$env:FLASK_ENV="development" is how to set the variable in Powershell

vagrant adder
#

Nope

#

It's set

#

And also, try pip installing flask in your venv

native tide
#

it's not set because I've already been down that road

#

$env actually changes the mode but set does not

vagrant adder
#

It worked for me

native tide
#

it doesn't for me

#

I can turn debug mode on I just can't get the app to run

#

and flask is already installed

#

I can run the application outside of debug mode

vagrant adder
native tide
#

didn't do anything

vagrant adder
#

Is your code on github?

#

And do you have git bash

native tide
#

no I'm using a tutorial, but the tutorial code is on github

#

I have gitbash but I don't know how to use it

vagrant adder
#

Oh thank god

#

Now

#

Do export FLASK_ENV='development'

native tide
#

in gitbash?

#

can I use gitbash as an interpreter?

#

export gives an error in Powershell

vagrant adder
#

Think of bash as better powershell

#

Im bash do export line

native tide
#

I have no idea how to get this set up in gitbash

#

is git copying my Powershell directory?

vagrant adder
#

export FLASK_ENV='development'

#

Git is vcs

#

Bash is better powershell

native tide
#

vsc?

vagrant adder
#

What publishes your code on github

#

That's git

native tide
#

when I do export it doesn't do anything

vagrant adder
#

Export in bash sets env vars

native tide
#

I don't understand what you're asking because I don't know how to set directories or run the program from git

vagrant adder
native tide
#

if I don't have my environment activated in Git how can I work with the variables?

vagrant adder
#

activate env by typing source venv/Scripts/activate

native tide
#

Okay you have got to start at the beginning here

#

I don't even know how to set directories in Git Bash

vagrant adder
#

What do you mean by setting directories

native tide
#

Setting the directory for my Flask application

#

if I just start setting variables outside of the app it's not going to do anything

#

I don't know how to use git bash at all so this is really confusing to me

#

I figured that part out but now I'm stuck trying to get it to run without debug

#

alright @vagrant adder I got everything working in git bash then set export FLASK_DEBUG=1 and got the same issue

vagrant adder
#

You have to setup debug withing app context

#

Not flask

native tide
#

How do I do that?

#

I also realized during this that the guy who made the tutorial has been using git bash for his examples

#

@vagrant adder

vagrant adder
#

app.debug = True

#

Inside __init__.py

native tide
#

Do you know how I get get debug turned off before I try that?

#

I used export and now it's permanently set to on

#

setting app.debug to true in the init.py didn't do anything @vagrant adder

vagrant adder
#

debug turn off?

native tide
#

I just restarted git bash

vagrant adder
#

export FLASK_ENV='production'

native tide
#

yeah I tried that and it stayed on

vagrant adder
#

Now restart git

#

And it should turn off permanently

native tide
#

I need it on though

vagrant adder
#

Ffs

#

Do you want it on or off

native tide
#

Did you not read my original question?

#

I'm having trouble because I can't get debug to work in Powershell

#

and now we've determined it also does not work in Git Bash

#

and gives me the same problem

#

Regardless I'm having the SAME ISSUE in git bash

willow garnet
#

@vagrant adder don't use the r-word on this server please

native tide
#

^

#

appreciated

vagrant adder
#

What tutorial are you following

native tide
#

The Flask-Mega-Tutorial by Miguel Grinberg

vagrant adder
#

How are you running the script

#

Are you working with 1 file or more files

native tide
#

a lot of files

#

I'm running the script using flask run

#

it works when debugging is off

vagrant adder
#

In your init.py file

#

Where are you pulling config from

#

Different file?

native tide
#

yes

vagrant adder
native tide
#

yes

vagrant adder
#

Okay

#

Can you send code of it

native tide
#
import os
basedir = os.path.abspath(os.path.dirname(__file__))

class Config(object):
    SECRET_KEY = os.environ.get('SECRET_KEY') or 'you-will-never-guess'
    SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \
        'sqlite:///' + os.path.join(basedir, 'app.db')
    SQLALCHEMY_TRACK_MODIFICATIONS = False```
vagrant adder
#

Under sqlalchemy_track_modifications put this line:
DEBUG = True

#

And if you need it off, change to False

native tide
#

That didn't effect anything when I run flask

vagrant adder
#

Is your script working fine?

native tide
#

the program works absolutely fine when debug is off

#

it's a blog app, I can go through the different pages and login and out

vagrant adder
#

Try running with debug off

native tide
#

what I'm saying is setting that variable in the config didn't change anything

#

debug remained off

#

I can turn debug on from git using export FLASK_DEBUG=1

#

and turn it off setting it equal to zero

#

but I can't get the app to run when it's on

vagrant adder
#

Okay, it isn't working through cli

#

Let's try it through code

native tide
#

It doesn't matter because that' snot the issue anymore

#

it doesn't work in Powershell or Git Bash

#

I can get debug turned on but the application simply won't run

vagrant adder
#

Read on this

native tide
#

k I'll get at it

#

thanks for all of the help even though the problem isn't solved yet

vagrant adder
#

👍

native tide
#

It still doesn't work, I've tried all of these and have the same issue

#

I've set FLASK_ENV=development

and FLASK_DEBUG=True

#

and still nothing, same problem as the original question

vagrant adder
#

Although, i always use code version

civic rampart
#

Ah

vagrant adder
#

Wadup chapo

native tide
#

so I have tried downgrading Flask and run into the same issue

#

tried it in command prompt as well

lime thicket
#

@native tide Werkzeug 0.15.5 introduced an issue for windows users that sounds like what your experiencing

#

Try downgrading Werkzeug to 015.4

#

Or run with python -m flask run to bypass

native tide
#

@lime thicket That works! Thank you!

#

Can you explain what's going on or have a resource that can explain it?

lime thicket
#

Here is a link to the issue on Werkzeug https://github.com/pallets/werkzeug/issues/1614 the short and sweet is that the reloader used during debug mode attempts to rebuild the args used to execute the code initially and fails to do it correctly

#

A lot of back and forth occurred as the issue only happens if you install flask a certain way so it was hard to pinpoint

native tide
#

Interesting

#

Yeah it works fine downgrading

#

How did you find the solution?

lime thicket
#

Found the code that contained the reloader string via some googling (Werkzeug) and then noticed they had shipped a new release a few hours prior. Started digging into the code to see if the release changed the reloader and it did

native tide
#

Neat, I'll have to keep that in mind to check out different packages for errors when I search.

vagrant adder
#

Damn

#

@lime thicket nice one

#

Flask head

winter flint
#

Does anyone know how to ping a redis server hosted on heroku?
locally i can just do:

r = redis.Redis(host="127.0.0.1",  socket_connect_timeout=1)
r.ping()

but REDIS_URL when using heroku is something like redis://h:839453h94h3fh@ec2-34-25-15-236.compute-1.amazonaws.com:16969

#

and i'm not sure exactly what to use with the host argument

#

All I really want is a way to check if redis is currently running

vagrant adder
#

I think you can use that env var as a host argument

tough star
#

I have a little sortable list made with jQuery UI.
How I can disable the auto resize of the window when I drag a element of the list out of the borders?

native root
#

The reason it's expanding is because the sortable ui moves the element according to position: absolute

#

when elements move outside their containers, and there's no other properties specified, css's overflow property defaults to scroll

#

which causes the scrollbar to appear and the element to continue to expand

#

if you wish the content to be cut off, you can set overflow to hidden

honest dock
#

Anyone here ever worked with DJango and Angular?

winter flint
#

@vagrant adder just to update what I was asking about before: you can just use the env var if you use redis.from_url() instead of 'redis.Redis()'

vagrant adder
#

So you need actual adress to ping a redis server?

opal schooner
#
.ellipsis-anim span {
    opacity: 0;
    -webkit-animation: ellipsis-dot 1s infinite;
    animation: ellipsis-dot 1s infinite;
}

.ellipsis-anim span:nth-child(1) {
    -webkit-animation-delay: 0.0s;
    animation-delay: 0.0s;
}
.ellipsis-anim span:nth-child(2) {
    -webkit-animation-delay: 0.2s;
    animation-delay: 0.2s;
}
.ellipsis-anim span:nth-child(3) {
    -webkit-animation-delay: 0.4s;
    animation-delay: 0.4s;
}

@-webkit-keyframes ellipsis-dot {
      0% { opacity: 0; }
     50% { opacity: 1; -ms-transform: scale(20); /* IE 9 */; -webkit-transform: scale(20); /* Safari */; transform: scale(20); }
    100% { opacity: 0; }
}

@keyframes ellipsis-dot {
      0% { opacity: 0; }
     50% { opacity: 1; -ms-transform: scale(20); /* IE 9 */; -webkit-transform: scale(20); /* Safari */; transform: scale(20); }
    100% { opacity: 0; }
}```
```html
<html>

    <link rel="stylesheet" type="text/css" href="css.css">

    <body>
        <h1>
            Loading<span class="ellipsis-anim"><span>.</span><span>.</span><span>.</span></span>
        </h1>
        <h1>
            <span class="ellipsis-anim"><span>.</span><span>.</span><span>.</span></span>
        </h1>
    </body>
</html>```
#

How can I resize the ellipsis at 50% through the animation ?

#

I tried scale 1.5 but it didnt work (so i put a huge value just to make sure)

native root
#

I don't see anything in that code that would prevent transform:scale() from functioning

#

...cut, the issue is that transform:scale does not apply to non-block elements

#

which span is

#

See here

woven surge
#

Just looking for a bit of direction not a full blown answer as I assume this isn't a quick question.

I'd like to have a table on my website. This table will pull data from a database. When the database updates I'd like the website to update only the values that have changed in the database automatically. I'd like to do this as efficiently as possible, is python the way to go or is this a problem that will likely be solved by JS/JQuery/Ajax or something ?

tough star
#

I have a sortable list by jQuery UI:

<div id="draggable-cards">
    <ul>
        <li id="item1">Item 1</li>
        <li id="item2">Item 2</li>
    </ul>
</div
$(function(){
    $('#draggable-cards').sortable();
});

How I can save the order of the list and read it with flask?

lime thicket
#

@woven surge without reloading the page and having the templating engine handle the changes to the table you will need some sort of JavaScript to fetch updates from an API and then modify the dom

woven surge
#

so the JS needs to keep checking if there has been an update

lime thicket
#

@tough star you could grab the list of <li>s and post it back to flask via an endpoint. With jquery it could be something like $( "li" ).toArray() to gather the list in the order it is

woven surge
#

or can JS listen and then when the DB updates it can send a signal

lime thicket
#

Yes unless your okay with the whole page reloading, and if so you can just use the templating engine

woven surge
#

that way it doesn't need to keep querying the DB

lime thicket
#

JS can’t listen, you could do some sort of socket setup possibly with the database update triggering an event but that increase the complexity significantly

woven surge
#

right

#

thanks very much @lime thicket

tough star
#

@lime thicket Can I use a sort of ajax?

lime thicket
#

Yeah to send the data back to flask you would likely do some sort of Ajax POST or PUT

tough star
#

@lime thicket But I don't know how to do

lime thicket
#

The jquery documentation has some nice examples if you scroll towards the bottom https://api.jquery.com/jquery.ajax/#jQuery-ajax-url-settings. Try to start small, get a simple post to work that prints some string on the server side, then try and post the list order, then post the list order and save it however you need to

tardy nova
#

been following a django tutorial and my redirect function is returning a null value

meager anchor
#

!ask

lavish prismBOT
#
ask

Asking good questions will yield a much higher chance of a quick response:

• Don't ask to ask your question, just go ahead and tell us your problem.
• Try to solve the problem on your own first, we're not going to write code for you.
• Show us the code you've tried and any errors or unexpected results it's giving
• Keep your patience while we're helping you.

You can find a much more detailed explanation on our website.

tardy nova
#
from django.shortcuts import render
from django.shortcuts import redirect
from django.contrib.auth.forms import UserCreationForm
from django.contrib import messages

def register(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            messages.success(request, f'Account created for {username}!')
            return redirect('blog-home')
    else:
        form = UserCreationForm()
        return render(request, 'users/register.html', {'form': form})
#

from django.urls import path
from . import views

urlpatterns = [
    path('', views.home, name ='blog-home'),
    path('about/', views.about, name ='blog-about'),
]
#

this is where 'blog-home' is in

#

when I do submit the form I get an error saying the returned value was null

tardy nova
#

ping me with answer if anyone does help, im ganna sleep

native tide
#

I have a question , how do I prevent the user to click the browser back button after moving to another page

#

I have tried window.location.replace and it doesn’t work

proper hinge
#

There's a web history API they may be able to do that

tardy nova
#

No one has a clue on my issue?

vagrant adder
#

I think you have to remove your form from inheritence from conditional statement

sweet wharf
#

I am trying to set my django website in prodution with heroku, but if I change debug mode to False the website doesn't work and it gives me an Server Error (500) If debug mode is on True the website does work completely.

steel tiger
#

So I have a webapp with a frontend and a seperate backend with an api. Regerstering works fine but how could I start a user session with my api?

#

Like I have a user log in and the frontend sends the login info to the api

#

Then it starts a user session

#

How would I make that work in flask? Would I have to implament oauth and all that rigamaroll like how discord does it with it's api (bots, clients)

vagrant adder
#

Jwt is almost deprecated rn

#

You are better off managing your sesssions completely on frontend

#

What frontend are you using?

ruby palm
#

What's the use for python3 manage.py makemigrations?

flint breach
#

Preapares changes of your models

vagrant adder
#

It commits changes to django folder

#

Prepares webserver for running with new changes pretty much

ruby palm
#

Ohh

#

Thank you so much!!!

tough star
#

How I can make a google login using Authlib?

vagrant adder
#

Authlib?

#

I try to avoid it whenever i can

#

I use other 3rd parties oauth plugins/modules since those actually have more recent code

tough star
#

@vagrant adder I want to use it with flask. I used the Flask-Oauth "plugin" but in the docs it says to use authlib.

hushed burrow
#

does anyone mind going over how to tie reactjs frontend to a flask backend on a high-level? i have a react repo with create-react-app but how can i connect that to flask that's running separately?

rigid laurel
#

Generally you design the flask app as a rest api that communicates with json data. Then you call the flask endpoints using ajax requests in react. But the main thing is to design your flask side as a rest api which you can find a lot of resources online for

hushed burrow
#

so i've been reading that's one way to do it. where the flask api is consumed by the react frontend. but is there also another way to do it where I can just run the flask app and have it serve up react without running a separate react instance?

rigid laurel
#

You could have a single view that includes a script tag of your react app

#

On the same app that the react is consuming

#

You might need babel js or Web pack or something to compile to the pure js. I'm not 100%

sweet wharf
#

I am trying to set my django website in prodution with heroku, but if I change debug mode to False the website doesn't work and it gives me an Server Error (500) If debug mode is on True the website does work completely.

normal karma
#

@hushed burrow you'll have to break down create-react-app's default config and set it to compile all the code in the directory of your flask app. Don't know if an api would be a viable option here

native tide
#

anyone here able to answer a question about django? ))

vagrant adder
#

Probably

tough star
#

@vagrant adder The last version was released on 2014...

#

But this is also very old

zealous igloo
#

jsut curious in django you do a createuser thing ot create a user but what if you extended from the user class and created ur own sorta user, is there any way to create a user from teh command line again after that?

frigid egret
#

@zealous igloo Yes, if you make custom classes from django built in classes and your program is going to treat them as though they are built in classes.

zealous igloo
#

oh okay so then i can createsuperuser and stuff and it would create that sorta user and would it change my token authentication process at all?

frigid egret
#

I've actually just finished doing such thing on my training project, put phone field in place of username

#

It wouldn't if you do it correctly. What you have to do is go to library files, find the class that you need, copy-paste it into your models.py and make changes you want there.

#

Here's my example if that helps:

#

...how do I use code paste thing? Keep forgetting

#

nvm, I'll just send you the file. What I did there is I copied library classes that I need and made my custom changes to them. So now django treats my custom classes as though they are library.

gleaming herald
#

Is there a load limit on flask

#

Its not accepting more than 4000 request per min

#

Any way to use multiple cores or just anything so that it accepts more request per second

zealous igloo
#

dang okay thanks a lot @frigid egret this looks rela tough so i can't understand it at the moment but i'll defintiely use htis and waht u said as reference as i go thru it. Tanks for shwoing me the file it's really ehlpful

#

This is just a training project? did u just get into django or something?

frigid egret
#

@zealous igloo Been studying it for last few months. I've also got a mentor that's helping me.

zealous igloo
#

oh wow jsut a few motnhs dang, i haven't studeid it for a few motnhs yet but im sure i won't be close to where ur at

frigid egret
#

Nah, trust me, this was an easy thing to do. Just wait till you get to making something that django wasn't designed for, that's where real tough part starts XD

zealous igloo
#

by the way i was kind of thinking about it and wanted to get ur opinion on if i really need to change the default user class. So like i have a program where the user can write a list of stories they have read and i was thinking i was supposed to extend the user model to include stories read but instead could i just use the default user model and on the front end it can request for the data of the user by sending a get request with it's primary key and the database just finds whatever info is associated with that primary key and sends it

#

ommmggggg scarrrrryyyyyyyyyy

frigid egret
#

I mean as long as there are tutorials (and there are plenty on user handling) it's relatively easy. Once you get into territory where there are no articles or any information, it gets real tough

zealous igloo
#

this is my first time using django for a site so yeah just like being able to develop these client-server applciations(i think that's waht it called when frontend and backend compeltely seperate) and it been tripping me up

#

ohh yeah for sure that must require insane thinking

frigid egret
#

So yea, start with tutorials and that'll give you general understanding of what django is capable of.

zealous igloo
#

oh okay yeah thanks i'll be sure to

frigid egret
#

yw

gleaming herald
#

Is there a load limit on flask
Its not accepting more than 4000 request per min
Any way to use multiple cores or just anything so that it accepts more request per second

#

or is it a server issue ?

zealous igloo
#
axios.get('http://127.0.0.1:8000/api/info/', {'authorization': 'Token' + this.props.token})
#

im using react wtih django rest frameowrk and i am trying to use the token I get from succesfuly logging in and just curious how do i perform requests now with axios adn teh token? in Postman I go to Headers and type Authorization as the key and the value is Token (some arbitrary token), so i'm guessing i would have to do an equivalent of that with axios, how would i go about that?

native root
#

@gleaming herald flask can only serve one request at a time, see its deploy documentation to get around that

#

@zealous igloo Try capitalizing "Authorization: and making sure there's a space between "Token" and the token

gleaming herald
#

@native root

#

I tried the documentation did not find anything

native root
zealous igloo
#

I tried the authorization capitalizing and with teh token i added space and i console logged it to confirm the value and yeah it does get the token but it still doesnt work, do i somehow have to include the word "Headers" in there cuz iwth Postman Iput the info in body but the token goes in palce called headers

gleaming herald
#

@native root I have my own server

#

with 8 cores

#

but python is using only one

#

and during load testing it shows that 4K is the limit

native root
#

Vraj, are you using flask's dev server, or a wsgi frontend?

zealous igloo
#

omg thanks @native root this helped so mcuh

native root
#

Someone able to tell me why this is rendering wrong?

#

jinja2 template:

#
<a href="{{ link.1 }}"
 title="{% if link.2 %}{{ link.2 }}{% else %}external link{% endif %}"
 {% if link.3 %}id="{{ link.3 }}"{% endif %}
 {% if link.4 %}target="_blank"{% endif %}>{{ link.0 }}</a>
#

input is a 5-element tuple of strings

#

...

#

maybe its not 5 elements

#

sigh

#

still unhappy that the if-else isn't functioning, it's rendering an empty string, which, as far as I can tell, shouldn't be possible?

#

output:

#
<a href="/about-us" title="">About Us</a>
ruby palm
#

Can you send a screenshot of the code instead of pasting it here? Because it looks weird

native root
#

Here's a passed-in tuple

#
('About Us', '/about-us.html', 'About us', None, False)
vagrant adder
#

Boi

native root
#

I would, if this were A) dynamic, B) not manually passed in ;-;

#

It's pulled from a config file, and not always intended to be internal

#

gives the code on the page a glare Change nothing, suddenly its working?

#

Was a stale render showing on live

ruby palm
#

Hi

#

Why are migrations useful in Django?

vagrant adder
zealous igloo
#

i tried doing request and request.data but it says request is not defined

native tide
#

new to web dev

#

idea

#

is there a way to have a folder with a bunch of markdown files.
And that folder is named like blog or smth
and so when you go to mywebsite.com/blog/subpage it displays the markdown file with the name subpage.md inside of the blog folder.
I think you could have some kind of python parser file but I am not sure.

Essentially I want to be able to create markdown files, directly into the folder, upload it, and boom, html page created.

#

Another functionality I would like to have is someway to extract variables stored inside of the markdown files, such as:
subpage.md:

[blogpage-name]: My Blogpage Name

I don't remember if that's how you create vars but point remains

left lynx
#

@native tide django or flask?

pliant hound
#

Hey all. I'm using Bulma sass with Flask and something, somewhere is breaking my hamburger menu

#
sass_bundle = Bundle(
    'custom.sass',
    filters= 'libsass, cssmin',
    depends= ('sass/**/*.sass'),
    output= 'css/bundle.css'
    )

In my app.py file

#
@charset "utf-8"
    
@import "sass/custom/my-colours" // Set custom colours for site

// Import Bulma
@import "sass/utilities/_all"
@import "sass/base/_all"
@import "sass/elements/_all"
@import "sass/form/_all"
@import "sass/components/_all"
@import "sass/grid/_all"
@import "sass/layout/_all"

// Custom sass elements
@import "sass/custom/fixed-footer"
@import "sass/custom/logo-img"
@import "sass/custom/tabbed-content"
@import "sass/custom/index"
#

is my custom.sass file

#

I've tried removing all of my customizations from the custom.sass file and rebundling the css file and still nothing

#

I've found the 3rd span in the burger div is broken, but cannot for the life of me find the culprit

native root
#

Well, the issue is that there isn't a space around that + operator

#

why, well, depends on where it comes from in the code

pliant hound
#

Okay let me try removing the cssmin filter

#

... that was it

#

lmao

#

Thank you!

#

Is there a way I can avoid that when the site is ready for production?

#

does css minification really even matter?

native root
#

It does matter, but not that much

#

see if theres a fix for the filter

pliant hound
#

Alrighty I'll look into it

#

Thanks so much 😃

balmy forge
#

@native root do you still have your IDE open

native root
#

I mean I never close them, why?

balmy forge
#
import timeit
import itertools
import string


def run():
    def chunks(products, chunksize):
        itertools_chain = itertools.chain
        itertools_islice = itertools.islice
        for startz in products:
            yield itertools_chain([startz], itertools_islice(products, chunksize - 1))

    alphabet = string.digits + string.ascii_letters

    products = itertools.product(alphabet, repeat=4)
    chunksize = 10000

    with open("test.txt", "w+") as outfile:
        _write = outfile.write
        # _join = ', '.join
        inner_join = ''.join
        for chunk in chunks(products, chunksize):
            _write(inner_join(inner_join(c) for c in chunk))


run_time = timeit.Timer(run).timeit(1)
print(f"Done in {run_time:2f}s")```
#

how long does this take for you

native root
#

...interesting optimization

balmy forge
#

it takes 4s for me

#

on a blue moon it runs at 3.8s but meh

#

I'll see what else I can do before I toss it into cython

#

it's a known thing to look up functions even built in beforehand and store in local variables, known to have greater performance but it's a rare thing

#

and I think I posted in the wrong channel, rip me

vagrant adder
#

@balmy forge
This is web dev channel my dude

balmy forge
#

Sorry, it was a continuation of another channel, I somehow opened this. My bad

tough star
#

I get this error when I open a flask page:

  File "C:\Users\Matteo's PC\AppData\Local\Programs\Python\Python37-32\lib\site-packages\flask\sessions.py", line 375, in save_session
    val = self.get_signing_serializer(app).dumps(dict(session))
  File "C:\Users\Matteo's PC\AppData\Local\Programs\Python\Python37-32\lib\site-packages\itsdangerous\serializer.py", line 166, in dumps
    payload = want_bytes(self.dump_payload(obj))
  File "C:\Users\Matteo's PC\AppData\Local\Programs\Python\Python37-32\lib\site-packages\itsdangerous\url_safe.py", line 42, in dump_payload
    json = super(URLSafeSerializerMixin, self).dump_payload(obj)
  File "C:\Users\Matteo's PC\AppData\Local\Programs\Python\Python37-32\lib\site-packages\itsdangerous\serializer.py", line 133, in dump_payload
    return want_bytes(self.serializer.dumps(obj, **self.serializer_kwargs))
  File "C:\Users\Matteo's PC\AppData\Local\Programs\Python\Python37-32\lib\site-packages\flask\json\tag.py", line 296, in dumps
    return dumps(self.tag(value), separators=(',', ':'))
  File "C:\Users\Matteo's PC\AppData\Local\Programs\Python\Python37-32\lib\site-packages\flask\json\__init__.py", line 179, in dumps
    rv = _json.dumps(obj, **kwargs)
  File "C:\Users\Matteo's PC\AppData\Local\Programs\Python\Python37-32\lib\json\__init__.py", line 238, in dumps
    **kw).encode(obj)
  File "C:\Users\Matteo's PC\AppData\Local\Programs\Python\Python37-32\lib\json\encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "C:\Users\Matteo's PC\AppData\Local\Programs\Python\Python37-32\lib\json\encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
TypeError: '<' not supported between instances of 'str' and 'NoneType'
native root
#

What's your flask code?

#

There's something going wrong internally there, but maybe I can figure out what's triggering it

tough star
native root
#

I'm not sure, but a few things stand out to me

#

First of which is maybe one of your JSON files is failing to load

#

the other is that check_user can return None

ruby palm
#

What is name button's attribute for in HTML?

native root
#

Perhaps it's being triggered by trying to serialize an openauth state?

tough star
#

@native root I don't know 😦

ruby palm
#

What is name button's attribute for in HTML?

#

For example:

<input type="password" name="password">
native tide
#

@left lynx both

#

django first I guess

river obsidian
ruby palm
#

@river obsidian thank you very much!!!

ruby palm
#
background-position: 50% 0;
#

What does it do? It looks like it centers the background image

#

(It's CSS)

mint canyon
#

50% is the middle, yeah

#
 background-position: center; 
#

you could also use this, much cleaner

#

@ruby palm

ruby palm
#

Oh ok

#

Thank you!!!

#

So it does the same thing as background-position: 50% 0?

proper hinge
#

I don't think so

#

yours only centers the x axis

#

but raizo's would center both I believe

mint canyon
#

well background-position: center; would be 50%,50% i just figured

#

so well the middle of the screen

proper hinge
#

the second argument was 0 though

plucky fiber
#

Is there a modern alternative to JWT? Seems like the difficulty in revoking access tokens is kind of a big deal, and it seems like an issue that something else would solve

vagrant adder
#

Flask login

open forum
#

How would you generally go about logging incoming requests that may contain sensitive information such as passwords? I've been considering if it's worth encrypting the sensitive data just for this purpose, or if I should create a logging module that selectively filters sensitive data from the log entries or something.

balmy forge
#

for me I just hash the password then send the hash away

#

storing password is storing hash instead of actual password

open forum
#

That isn't going to work in my case, because I need to send the password on to one of multiple third-party APIs.

balmy forge
#

I guess then the only way is to do a 2-way hash method to hash sensitive data

#

and only convert it back in case you need it, but that's just as good as logging the sensitive data itself

open forum
#

I mean, I will have access to the plaintext password in the code in any case, it's just about protecting it from someone reading the log.

#

So I could selectively remove it from the log, which is the second option I thought of.

#

Just trying to get a second opinion. Maybe there are industry standards for this kind of thing.

#

I guess normally you would know the hashing scheme of the database storing the password.

#

So you could just hash it in the client.

balmy forge
#

normally, yeah, hash instead to keep "evidence" which helps tremendously in debugging and tracing as well

open forum
#

Hrm, yeah, my situation is a bit awkward in that regard.

stray nexus
#
ZDNet

A small but unspecified number of GitHub staff could have seen plaintext passwords.

open forum
#

@stray nexus I know I shouldn't, I was just asking about the best way to avoid it.

stray nexus
#

well, to not log the password anywhere is the best way imho. strip it from your log if you want to keep a log of all succesfull/failed login

#

what is the usefulness of having passwords, hashed or not, in the log anyway ?

ruby palm
#

Thank you very much, @proper hinge and @mint canyon !!!!

mint canyon
#

@proper hinge right, thats why i said that

ruby palm
#

With

background-position: center; 

Does Y equal to 0 by default in that case?
So is it the same to write

background-position: center 0;
```?
native root
#

No, background-position: center; is the same as center center

leaden vessel
#

@open forum Is it possible to use some form of federated login across the services? That would provide a more cerntralised setup at least (think Oauth and other possible options)

open forum
#

@leaden vessel I have no control over the third party APIs, and the credentials passed around are those of end-users of our customers.

#

We are merely facilitating communication between our customers and these APIs.

#

@stray nexus I have no specific need to log passwords, I was just wondering whether it's better to strip the logs or to encrypt the sensitive data.

#

I guess it's generally better not to send any sensitive information in plain text, even if it is over https.

#

Though I can't think of any obvious way to exploit it.

ruby palm
#

@native root Ok, thank you!!

ruby palm
#
ul ul {
    list-style-type: circle;
}
#
ul > ul {
    list-style-type: circle;
}
#

Are those CSS codes the same?

#

Or does it make a difference to put a >?

native root
#

‘>’ indicates that the elements must be immediate descendants

tranquil steeple
#

Can someone help me please

#

I'm building a Python Flask contact page

#

for some reason my contact form want allow me to put input in 🙈

#
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired, Email

class ContactForm(FlaskForm):
  name = StringField('Name')
  email = StringField('Email', validators=[DataRequired()])
  subject = StringField('Subject')
  message = StringField('Message',validators=[DataRequired])
  submit = SubmitField('Submit')```
#

{% block title %} Contact {% endblock %}

{%  block head %}
<link href="{{ url_for('static', filename='css/contact.css') }}" rel="stylesheet" type="text/css">
{%  endblock %}

{% block content %}

<div class="container contactustext">
    <h1>GET IN CONTACT</h1>
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Impedit voluptates minima cum odit eligendi, ut fuga suscipit dicta harum repellat assumenda dignissimos! Ad consequuntur ipsam deleniti quidem, quos obcaecati alias.</p>
  </div>

<div class="container">
    <div class="content-section">
        <form method="POST" action="">
          {{ form.hidden_tag() }}
          <fieldset class="form-group">
            <legend class="border-bottom mb-4">Contact Us</legend>
            <div class="form-group">
              {{ form.name.label(class="form-control-label") }}
            </div>
            <div class="form-group">
                {{ form.email.label(class="form-control-label") }}
            </div>
            <div class="form-group">
                {{ form.subject.label(class="form-control-label") }}
            </div>
            <div class="form-group">
                {{ form.message.label(class="form-control-label") }}
            </div>
          </fieldset>
          <div class="form-group">
              {{ form.submit(class="btn btn-outline-info") }}
          </div>
        </form>
      </div>
</div>
{% endblock %} ```
#
def contact():
  form = ContactForm()
  return render_template("contact.html", title='contact', form=form) ```
ruby palm
#

Thank you , @native root !!

native tide
#

Having some trouble sending an email from a script using Flask-Mail

#

getting the error smtplib.SMTPServerDisconnected: please run connect() first

#

I'm attempting to use gmail and send an email to another gmail account

iron sinew
#

Which web API is better?

#

flask or django

humble portal
#

does anyone know how to return a json object to a template? returning a JsonResponse(data) does not give me the option to render it to a template

tranquil steeple
#

Is anyone familiar with Flask SQLAlchemy?

plain veldt
#

@humble portal wdym by return it to a template? do you mean pass it to a template? then just jsonify it and pass it as a variable to the render function, use flask.json.dumps (its exactly like json.dumps but is context aware)

ruby palm
#

Hi

#

See that blue nav bar?

#

I want that blue nav bar's width to occupy 100% of the web page

#

But I can't figure out how to do it :(

#

Help!!

ruby palm
#
* {
    padding: 0px;
    margin: 0px;
}

body {
    background: #e6e6e6;
}

.main, header, footer {
    margin: 20px auto;
    width: 80%;
}

.main {
    clear: both;
}

header nav ul {
    list-style: none;
}

header nav ul li {
    float: left;
    background: #66b3ff;
}

header nav ul li a {
    display: block;
    padding: 10px 20px;
}
#

That's the CSS code

autumn bobcat
#

Have you tried

body, html {
    width: 100%;
}
dark geyser
zenith lily
#

Value error :couldnot convert string to float how can i solve that?????

balmy forge
#

Well how do you convert “abc” to number, what’ll be the expected result

#

You can wrap it into a try except ValueError as well

zenith lily
balmy forge
#

Whats in line 538

#

Owait that inside numpy

zenith lily
#

how can i solve this brother

balmy forge
#

What’s handling the get request for prediction?

#

What’s the code

vagrant adder
#

@iron sinew
Its a lot easier to write apis in flask

#

@tranquil steeple i'm pretty familiar, just ask the question

vagrant adder
#

@humble portal what framework are you using

iron sinew
#

@vagrant adder Thanks. I'll try to find some tutorials for that

vagrant adder
#

Corey schafer has a great flask walkthrough

spring dragon
#

anyone work with amazon mws api

zealous igloo
#

just curious with django i had this sorta website idea and im kinda wondering if it even possible in django. so just in very brief summary i have a site sort of like a excel for tv shows it has columns like wha tyou would rate teh show, how much u liked it outta 10 etc so i have models for the table for each column

#

would it be possible to make it so each user can customize their tables by adding/deleting their own columns but then im assuming this would mean that for every single user that changes their table from teh default there would have to be a diff model for every single one.

#

is that doable in django?

unborn terrace
#

@zealous igloo yes

candid basalt
#

It is doable in django, although you what you are talking about is much more then django itself.

unborn terrace
#

Is it doable in <ANY BACKEND WEB FRAMEWORK EVER> ?
Also yes

zealous igloo
#

oh am i right that every user would have to have their own model for the table

candid basalt
#

Depends on what you are referring to as 'model'.

zealous igloo
#

im just trying to conecptualize how i would do this, having a really hard time planning it out

#

u know like model with the datefields integerfields charfields etc

candid basalt
#

In that case - probably no. All users will have a single table/model, but there will be a field in it specifying which user each record belongs to.

unborn terrace
#

@zealous igloo well, the “user-defined models“ would not be Django models in that case, they will probably have their own representation, this is usually done using NoSQL data storage

candid basalt
#

Django ORM is supposed to be used with relational databases.

zealous igloo
#

would i have to use a non relational/NoSQL thing database?

unborn terrace
#

@candid basalt well, there is PostgreSQL's JSONField allowing to do some cool schemaless stuff when needed

candid basalt
#

There is, but it also produces a lot of issues. =]

unborn terrace
#

@zealous igloo as you wish

#

@candid basalt well, issues would happen too using other databases 🤔

candid basalt
#

@zealous igloo everything depends on what you want. It's possible to do with either relational or document-based or any other database of your choice. Each approach has it's own pros and cons.

zealous igloo
#

i see wait so hwo could i do this without giving a table a model?

candid basalt
#

@unborn terrace depends on the use case. When you work with the data structure that needs to be consistent and maintain it's integrity - most of the time you will want relational DB. When you want a lot of horizontal scaling - nosql may be a better choice.

unborn terrace
#

@candid basalt sure, but it does seem appropriate here, where users should benefit from a kind of custom-defined database

#

Well, the app may also use “real” databases to represent them, but this involves so much more work than most apps of that kind store these user-define DBs in NoSQL storage

candid basalt
#

Yes, that's true. NoSQL DBs tend to be better for prototyping.

#

Yet Django has a lot of stuff automated for you, such as schema generation and migrations, to name a few.

#

@zealous igloo if you want to use Django ORM - you will have to design your data structure around the relational DB paradigm and will have to use Django models. If you want to use something else like MongoDB or similar tech - it may make sense to use it directly instead without involving Django ORM.

unborn terrace
#

Sure but these are not made for user-defined databases, they are for the app developer

zealous igloo
#

oh okaya nd if i do use DJango ORM would i create a new Model for every singel user who wishes to have a differnet table?

#

if i useed a nosql database would mongodb be best choice for that?

unborn terrace
#

do use DJango ORM would i create a new Model for every singel user who wishes to have a differnet table
@zealous igloo no, that's what I am just saying

zealous igloo
#

i see it just @candid basalt said i would have to use DJango Models i just don't get how i would have ot use it and not have to create a new model for every single user

#

i saw your solution about how they would have a unique datbase representation but taht is just for nosql

unborn terrace
#

That's the thing, these apps usually implement their own kind of “ORM” to manage that

zealous igloo
#

oh so it might be more of a hassle to use djangos?

unborn terrace
#

Very usually leveraging flexible schema-less datastores

#

No more than something else

zealous igloo
#

i see it jsut so how would i use Django models for this?

candid basalt
#

There are few ways to handle this:

  1. Make a predefined set of additioanl fields users can choose from. This way you can still get away with clean RDB structure.
  2. Make use of JSONField to store custom user columns (may have issues later down the road with querying them).
  3. Use non-relational DBs such as MongoDB to store all your data (may have issues with attaching that with regular Django user management etc, which generally wants RDS under the hood).
  4. Not use Django at all and go with flask+mongodb+something else (will loose Django's "batteries included" functionality).
unborn terrace
#

You don't, your Django models will be used to model your application entities, not for the users to define them themselves

candid basalt
#

If I were to do this - I'd try JSONField approach first. It seems the most convenient and less intrusive if you want to keep using Django/PostgreSQL.

unborn terrace
#

^

zealous igloo
#

oh wow okay thanks for the option idk whta jsonfield is atm but i'll look into it rn and i'll keep those other ways in mind for sure

candid basalt
#

Credits go to @unborn terrace for that one. =]

unborn terrace
zealous igloo
#

thanks you both provided a ton of helpful info

silent girder
#

Is someone here who use Django-CMS?

#

Can i use Django-CMS with Django 2.x?

dim axle
#

if i understand something wrong or if you guys have anything to add, please let me know

#

I have done an overview concerning webframeworks, please comment or correct me, if i understand something wrong.

dense salmon
#

does mod_wsgi work for python 3.7 (windows)?

vagrant adder
#

Yes

#

@dim axle
Forgot about nosql databases and servers such as wsgi/uwsgi and gunicorn

#

But that's about it

native tide
#

PixiJS 5.1.0 - ✰ WebGL ✰ http://www.pixijs.com/ ♥♥♥

#

Do you have those characters in a console after calling the function PIXI.utils.sayHello()?

rigid laurel
#

I never got an answer in #databases, but is there any reason to run/store/write db create scripts as python code, rather than just running them on the db directly via sql?

plucky fiber
#

With Flask Blueprints, how would I assign a wildcard route? Like if I want /foo/bar/* to route to a particular function (or Flask_Restful resource)?

vagrant adder
#

What do you mean by wildcard route

plucky fiber
#

Like, I want /foo/bar/<arbitrary name here> to route to a particular function/Resource, and have access to whatever string was specified in <arbitrary name here>

#

Basically, I'm going to do some customizable database models, and I need for the REST API to be able to serve the arbitrary models/fields

rigid laurel
plucky fiber
#

Ahh, perfect! Didn't realize Piers Morgan was a Flask expert!

rigid laurel
#

Gotta find something to do when there are no sausage rolls to rant about

vagrant adder
#
@app.route('/<int:wildcard_hete>')
def saki(wildcard_here):
    return wildcard_here```
#

@plucky fiber

plucky fiber
#

Thanks!

vagrant adder
#

I think only supported types are int and str

dim axle
#

@vagrant adder thank you!

warm narwhal
#

Mon Aug 5 04:39:13 2019 - SIGPIPE: writing to a closed pipe/socket/fd (probably the client disconnected) on request
i randomly get this in my logs on a nginx/uwsgi/flask setup. anyone can shed some light on what i should be checking ?

gleaming herald
#

While lightweight and easy to use, Flask’s built-in server is not suitable for production as it doesn’t scale well and by default serves only one request at a time.

#

Any alternative

#

or ideas how to make it production ready ?

balmy forge
#

there are many other scalable alternatives - django is popular, so is tornado

#

sanic is also a great alternative to flask as well

gleaming herald
#

@balmy forge Sanic sounds promising

#

There's a thing called waitress to make flask fast I guess

zealous igloo
#

is it possible to still use rest frameowrks AuthToken thing if you are using a custom user model because I created a custom user but everytime i create a user there isn't a token taht is generated along with it

vagrant adder
#

What are you using

#

Flask or django

zealous igloo
#

django

vagrant adder
#

Oof

#

I'm no help then

zealous igloo
#

oh no worries i appreciate u asking tho

vagrant adder
#

@gleaming herald
Try googling gunicorn

gleaming herald
#

I'm using nginx

#

as a temporary solution

#

trying sanic

#

next i'll try gunicorn

vagrant adder
#

Gunicorn is sooo eazy to use

#

I used it on heroku vps

gleaming herald
#

Oh

#

i have my own server

#

so no heroku

#

do you have a code or something for quickstart @vagrant adder

#

Like if I want to improve the number of request it process on flask

vagrant adder
late gale
#

Does anyone know how to track my website using Google analytics

#

I wrote the tracking code and but nothing happened

gleaming herald
#

Yea

#

Did you try this

#
Concurrency Level:      200
Time taken for tests:   15.718 seconds
Complete requests:      5000
Failed requests:        0
Non-2xx responses:      5000
Total transferred:      710000 bytes
HTML transferred:       180000 bytes
Requests per second:    318.11 [#/sec] (mean)
Time per request:       628.713 [ms] (mean)
Time per request:       3.144 [ms] (mean, across all concurrent requests)
Transfer rate:          44.11 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    3  36.6      0    1056
Processing:   243  618  69.2    607     841
Waiting:      230  604  64.3    596     827
Total:        248  621  75.6    608    1538

Percentage of the requests served within a certain time (ms)
  50%    608
  66%    636
  75%    646
  80%    653
  90%    676
  95%    706
  98%    829
  99%    834
 100%   1538 (longest request)
#

@balmy forge The test results on sanic

#

Workers are 2

#

Threaded = True

#

Flask gives same result when used with nginx

balmy forge
#

Ye sanic is pretty fast

#

Tornado is great too

gleaming herald
#

IDK

#

It's hard to setup I guess

#

Documentation not that good

frigid egret
#

Hi all

#

Can someone help me figure something please?

#

I'm working on a practice website on Django.

#

It has users and also orders.

#

There is a User profile page and I'd like to have a list of orders made by that user on that page, next to basic user information.

#

Can't find a proper example or tutorial as this seems to be a somewhat non-standard task.

dusky bough
#

How are your Users and Orders currently connected?

#

If you have a User page, you have the ability to query your Orders based on the User who's page you are on.

frigid egret
#

@dusky bough Order object has a ForeignKey to User. But the way I'd like to filter them (and that is how I filter them on Admin site) is by "phone" field. Both User and Order have that field so it's easy to filter orders.

#

Basically, what I'm trying to do is to make a list of filtered Order objects on a User page being filtered by "phone" field.

late gale
#

@gleaming herald I put the tracking code as said and nothing changed in Real-time Overview

#

I've also disabled my Block tracking add-ons to be easy to be tracked but still

late gale
#
{% load static %}
<!DOCTYPE html>
<html>
<head>

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="/static/blog/main.css">


    {% if title %}
        <title>{{ title }}</title>
    {% else %}
        <title>Mazen</title>
    {% endif %}

<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=TRACKINGID></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', TRACKINGID);
</script>
</head>
#

Here is the code

dense salmon
#

When I'm trying to deploy my python flask on apache server, on the local host page it just shows a directory of all my files and not the pages itself

late gale
#

What is the hosting service that you use ?

#

@dense salmon

#

The best hosting service for python is pythonanywhere so i recommend to host your website there

dense salmon
#

I was using Apache

#

This is for an intern thing, they said I should only use apache and not pythonanywhere.

zealous igloo
#

so with django rest mixins i get that there are things like Create Update whatever that are triggered by certain HTTP requests. What request triggers the RetrieveModelMixin?

proper hinge
#

A GET

#

@zealous igloo

zealous igloo
#

oh so it's a get plus a lookup, thanks

rich walrus
#

Does anyone know if flask does any crsf stuff by default? I think its messing up one of my projects but Im not sure.

dense salmon
#

Is anyone familiar with Apache24 And flask?

jagged lark