#web-development

2 messages · Page 7 of 1

brittle copper
#

@unborn terrace

#

This is the best monkey patch I can come up with but again I have no idea how databases work

#

lol

#

Oh you do migrate it and this would be a problem when you migrate it yeah my bad

#

Welp sorry for the ping then

polar robin
#

if i make a subdomain i.example.com point to example.com/directory can i do i.example.com/file.png where file.png is example.com/directory/file.png

brave mantle
#

that's known as a rewrite

#

although it depends what webserver you're using

#

anyway, yeah just set the root of the domain to start with

#

that's probably all you need

polar robin
#

see i don't have a webserver yet

#

i'm planning to use digitalocean 5$ droplet and install a preferred webserver on it

brave mantle
#

I usually recommend nginx

polar robin
#

ok and would the above be possible with nginx

brave mantle
#

Yup

polar robin
#

Great, thank you ;')

long zinc
#

Is it possible to use Pelican / ISSO with Github Pages? Or do I need a VPS for that?

polar robin
#

You may not, Github Pages are for static sites only.

long zinc
#

Based on this tutorial, it seems like there is a service that needs to be run

#

oops, no markdown?

meager anchor
#

Discord sadly only supports a subset of Markdown

long zinc
#

better than irc

hearty birch
#

github pages only supports static content iirc

long zinc
#

What VPS is recommended for something simple like a Pelican blog with comments. AWS? Are there any other options? I just want to set up a personal blog.

hearty birch
#

pelican generates static content right? i'm not too familiar

#

DigitalOcean has a 5/month plan

#

it's pretty good

long zinc
#

pelican generates static pages, but the comment plugins I guess are not static.

#

@hearty birch That does sound pretty good. I will have to give them a try. Thanks.

quartz maple
#

I have a question

strange thorn
#

bot.tags["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.

strange thorn
#

@quartz maple

quartz maple
#

I was going to continue

#

I want to make a script - with flask that acts like a job card.

#

You input your values and it goes to a db. There's a place where the job cards can be viewed.

#

Is there any basw code for this?

strange thorn
#

base code

quartz maple
#

Code

strange thorn
#

well

#

first of all it depends on your database

#

what database

#

there are so many

quartz maple
#

MySql

strange thorn
#

ew

quartz maple
#

Ew

strange thorn
#

yes ew

#

anyway

quartz maple
#

Ew

strange thorn
#

for mysql you have to types of libs either an ORM lib like sqlalchemy (allows you to write classes which represent your db inside your code) or a lib where you directly write the sql on your own like PyMYSQL

#

up to you

quartz maple
#

Yeah is there any base code or tutorial on what I want

#

Or anything I can work from

strange thorn
#

Not that i knew

quartz maple
#

Based on my

strange thorn
#

do you know sql?

quartz maple
#

Description

#

Nah

strange thorn
#

as a language

#

well then either go for sqlalchemy or learn sql first

#

(i recommend learning it)

quartz maple
#

Okay....

#

Well

#

I don't really have the time

#

I really just want to make a job card system for my small business

#

And I might have to use php anyway since its a cPanel system

strange thorn
#

you should take your time learning sql

#

its really worth it

quartz maple
#

Okay but I

#

Possibly couldn't even run a flask script

#

On

#

CP system

#

No ssh access unless the host allows it

dense sapphire
#

i weed weelp 😦

#

Flask shell is being a bitch

strange thorn
#

flask shell?

dense sapphire
#

yes

#

i am creating that microblog from miguel's blog

strange thorn
#

but whats flaask shell

dense sapphire
#

ooo

#

it helps you build stuff without importing over and over

#

it opens a python shell with your Flask App environment giving it a push

strange thorn
#

yes but what is it, link? code ? pix?

dense sapphire
#

so you'll start from there

#

on your terminal write flask shell in a flask project

#

it's like flask run, etc ...

#

terminal commands

strange thorn
#

why would you use a shell to develop persistent code?

dense sapphire
#

it's a mean to test your code quickly

strange thorn
#

and whats your problem with it

dense sapphire
#

I've manipulated the shell to have extra stuff imported in it on launch

#

it's not working properly

strange thorn
#

how have you manipulated it

dense sapphire
#
@app.shell_context_processor
def make_shell_context():
    return {'db': db, 'User': User, 'Post': Post}```
#

db, User, Post are imported in the py file. I can then call db for example in the terminal and directly have it in there

#
in shell> db
> returns the db object```
#

Idk why but i feel like my env variables aren't being set.

(venv) PS C:\Users\Thunder\Documents\microblog> set FLASK_ENV=development
(venv) PS C:\Users\Thunder\Documents\microblog> flask run
 * Environment: production```
#

and i can't seem to find a file in venv concerning the env variables 🤔

brave mantle
#

are you using pipenv or just a venv on its own?

#

pipenv (and I think flask cli as well) supports dotenv

dense sapphire
#

i am using venv

#

i am following simply the guide, and then i research after each post on stuff

#

but this one broke ... If at least I can see the flask environment variables ...

brave mantle
#

so you make a file named .env and put your env vars in it

#

but I'm not 100% sure if you can do that without pipenv

dense sapphire
#

i'll have a look at it

#

the ugly thing is that I can't see in any place a thing on env variables for flask. Like where they're stored, or why they are not being set, etc.

#

i found for linux, but am on windows

brave mantle
#

well on linux you often just

#

FLASK_ENV=development flask run

dense sapphire
#

same to windows!

#

idk where i fucked up (or my pc isn't working with me)

#

i've checked over and over what am doin

brave mantle
#

doing that only sets it for the single command

dense sapphire
#

lemme check

brave mantle
#

you have to do it all at the same time if you do it like that

#

but maybe look at dotenv

#

alternatively run your app from an IDE instead

dense sapphire
#

on windows nuh, doesn't work

brave mantle
#

dotenv isn't platform-specific

#

you need the flask runner docs

dense sapphire
#

im sure miguel will be using dotenv later on in the blog

brave mantle
#

ok, it does support it

#

you need to install python-dotenv to use it

dense sapphire
#

i'll have a look at it after i check why it's tripping

#

i want to know what's going on

tame viper
#

what's a recommended database library for simple small-scale projects with flask?

brave mantle
#

You'll need a database server regardless of size because of flask workers

#

We use rethinkdb

tame viper
#

yeah alright, i'll see what i can do ^^

dense sapphire
#

@brave mantle i've created a new venv in a new directory. Tried setting environments and running it. They didn't affect shit as well biskthink

#

Is this shit normal yo?

#

or you don't have much to tell me on this case specifically?

brave mantle
#

I don't use powershell

#

This isn't a venv thing

dense sapphire
#

icic

#

worked

#

god i've been searching for 2 hours for this

#

the title of that SO question is so fucking bad!!!

stiff vessel
#

how do you phrase that you built something with flask and python

#

flask over python? python over flask? flask with python? python with flask?

molten tide
#

something like, python with the flask library maybe?

meager anchor
#

"a flask app"

limber zealot
#

"i made this thing with the python language and i also used this thing called flask which is a library for the python language what makes it easier to make websites with a good object oriented style rather than just writing to a file with html tags", should sum it up quite nice for anyone wanting to know quickly what you've made. GWchinaNayuSmile

deep cave
#

@stiff vessel on our website, when faced with the same question, we simply went for "Python and Flask." as in "This website uses Python and Flask, and was developed collaboratively on GitHub."

brittle copper
#
-- Hey, I made a website!
- Oh, nice what tool did you use?
-- I coded it myself.
- Nice, which language?
-- Python.
- Oh, what framework did you use?
-- Flask.
#

So in essence you only say you made a website with python if they don't ask any further :D

neat nest
#

normally I'd hit with "what'd you use?", first, and expect "Flask"

#

if I'm interested enough to ask about its implementation I want to know more than the language it was implemented in

#

if you mock up a WordPress site you shouldn't say you made it in PHP and HTML

pearl kite
#

"Python ft. Flask"

lofty reef
#

Yeah don’t most ppl say python-flask?

#

That’s how i’ve always heard it descibrs

deep cave
#

maybe not @neat nest but you hardly have to write any PHP to get a wordpress page running

#

most people will never write a single line

#

you certainly do have to write some python for a flask app though

neat nest
#

WordPress may have been a poor example. my point was not so much to exclude the language used, but rather that the language in which you wrote something says very little about it and the framework that you used is probably what someone's interested in

#

assuming that you did, in fact, use a framework

deep cave
#

yeah

polar robin
#

They can always Google the framework and figure out the language

still briar
#

Need some help with Django, Redis and websockets. It works fine locally, but when I run it on my server it 404's to socket routing.

#

Should log

[2018/05/22 20:52:29] WebSocket HANDSHAKING /socket/tictactoe/ [127.0.0.1:53658]
[2018/05/22 20:52:29] WebSocket CONNECT /socket/tictactoe/ [127.0.0.1:53658]

But on the server

Not Found: /socket/tictactoe/
[22/May/2018 20:54:52] "GET /socket/tictactoe/ HTTP/1.1" 404 4332
#

routing.py

application = ProtocolTypeRouter({
    "websocket": AuthMiddlewareStack(
        URLRouter([
            path("socket/tictactoe/", TicTacToeConsumer),
        ]),
    ),
})
#

The rest of the website works perfectly, just not sockets.

delicate otter
#

Yo, someone here is using Plesk ? I have a plesk server on top of a Ubuntu on Google Cloud Compute Engine. Everything is working well, but im afraid.

I want to host multiple companies. I build websites with Django and Flask. Is Plesk secure ? I host Django app so I use passenger_wsgi and NGINX. I want to make sure all my clients are isolated at maximum.

smoky elk
#

Anyone know of a free dictionary api or text file version that is free to use?

#

Just checking if a word exists

neat nest
#

free tier API access is 3,000 requests per month, 60 calls per minute

willow mirage
smoky elk
#

@lucy Thanks!

marsh canyon
#

hey guys

#

im having problem with flask and sqlit

#

sqlite*

#
db = SQLAlchemy(app)


class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(20), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
    image_file = db.Column(db.String(20), nullable=False, default='default.jpg')
    password = db.Column(db.String(60), nullable=False)
    posts = db.relationship('Post', backref='author', lazy=True)

    def __repr__(self):
        return f"User('{self.username}', '{self.email}', '{self.image_file}')"


class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100), nullable=False)
    date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    content = db.Column(db.Text, nullable=False)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)

    def __repr__(self):
        return f"Post('{self.title}', '{self.date_posted}')"```
#

my code (classes as models for db)

#

when i add a user,like user_1 = User(username='Rohan' , email='rog@blog.com' , password = 'password')

#

from cmd

#

and then db.session.commit() , it gives an error calledsqlite3.IntegrityError: NOT NULL constraint failed: user.id

#

Help plz

neat nest
#

where's the image_file in your User() call?

#

@marsh canyon

marsh canyon
#

It's default set

#

So I dint provide one

#

Default = 'default. jpg'

#

@neat nest

neat nest
#

I see

#

your backref is 'author', I notice

#

where's that get used?

marsh canyon
#

its like every post has an author

#

in Post : user_id

neat nest
#

but you don't use it there

#

your foreign key is 'user.id'

marsh canyon
#

that is what he did in the video

#

Corey Schafer

#

i deleted my code (which i typed seeing the video thinking that i might have done some error) and got the code from his github and still the same error

#

he is like it will be the id of the user who wrote the post

#

ill delete the db ,make a new one and try again

neat nest
#

hmm, well I can't speak for what does or doesn't work for Corey Schafer, unfortunately

marsh canyon
#

oh

deep prism
#

your PK should have autoincrement=True if you want it to be generated.

neat nest
#

isn't that the case by default?

marsh canyon
#

so what should i do to make it work @neat nest

deep prism
#

Ah, you are right lucy

neat nest
#

well I assume the name passed as backref ought to have meaning. is 'author.id' the proper foreign key?

#

I honest to goodness have never used SQLAlchemy before so I'm flying in the dark

marsh canyon
#

even in the docs he used user.id in the address class

neat nest
#

right but the backref is also 'user' there

#

unless you mean what Corey Schafer did and again I can't speak for why that might work

marsh canyon
#

oh,should it be same?

deep prism
#

This is a reduced example of what I have in some of my code:

class Client(db.Model):
    __tablename__ = 'clients'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)

    amounts = db.relationship("Amount", back_populates="client", lazy=True)


class Amount(db.Model):
    __tablename__ = 'amounts'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)

    client_id = db.Column(db.Integer, db.ForeignKey('clients.id'))
    client = db.relationship('Client', back_populates='amounts', lazy=True)
marsh canyon
#

so i change author to user

deep prism
#

your back_populates needs to be the name of the db.relationship attribute in the other class

marsh canyon
#

so for me it will be

user = db.relationship('User', back_populates = 'post', lazy=True)```
#

and for user_id ,it will be user_id= db.Column(db.Integer, db.ForeignKey('user.id'))

#

right?

deep prism
#

'posts' instead of 'post'.

marsh canyon
#

okay

#

btw im using flask-sqlalchemy

#

same thing what i did,why isnt it working 🤔

neat nest
#

not the same thing what you did!

#

once again, you've got a backref='author', but the name "author" never shows up anywhere else!

deep prism
#

it does have a backref=person in the docs which doesn't exist. I didn't know that was possible.

marsh canyon
#

something is weared with my code,lemme check for some spelling mistakes if any

neat nest
#

your error is sqlite3.IntegrityError: NOT NULL constraint failed: user.id, user.id does not exist, I'm reasonably certain you ought to either change your backref or use the name you specified for your backref in defining the foreign key

marsh canyon
#

i changed backref to user

#

let me see if it works

#

nop,same error

deep prism
#

could you show what tables it made in the DB?

marsh canyon
#

im using flask-sqlalchemy

deep prism
#

I know, it's the same though.

marsh canyon
#

i dint declare relationship on 2nd table

#

sending img,insted of code,tought it would be more clear without word wrap

deep prism
#

can you type .schema user in sqlite console (assuming user is the tablename sqlalchemy generates)

marsh canyon
#

saying invalid syntax at user

neat nest
#

"in sqlite console"

#

that's a Python REPL

marsh canyon
#

in cmd,i type python

brave mantle
#

There is no sqlite repl with the sqlite module

#

And sqlalchemy will not allow you to directly manipulate the database like that

#

If you want to inspect your database, find a tool online for it

marsh canyon
#

i used metadata.tables.keys() and it came

#
dict_keys(['user', 'post'])```
#

@deep prism

#

best thing to do is change my database to flask-MySQLdb

#

sqlalchemy is giving me a headache

brave mantle
#

Then take a break

marsh canyon
#

yea ,gonna take a break after i set up mysqldb

#

best thing in it is i dont have to write models (classes) in flask ,i can do it directly from mysql shell or workbench 😁

brave mantle
#

That's missing the point

deep prism
#

Yeah, and then you still have to write your queries manually.

#

(I was pulled in a meeting)

marsh canyon
#

😁

#

But it's easy then wasting my time on thay sqlalchemy

brave mantle
#

Let's see if you feel the same way when you're writing inner joins yourself

deep prism
#

I'd first try to just change the DB url to mysql and see what happens.

I still don't believe your PK was set to auto-increment. Did you, ever, write the model definition without setting the id column as primary key, or did you never delete the DB and retry?

#

Hell, just comment the Post class and the relations and see if you can create a User without relations.

brave mantle
#

Yeah, sqla isn't going to update the schema for you

#

You need to write migrations for that, using eg alembic

deep prism
#

And in the case of setting up the first database, as you are doing. It's a matter of deleting the database - Which for sqlite is deleting the file i think - and db.create_all() after all DB models are imported.

marsh canyon
#

i did db.create_all() stuff n all

#

i followed the video exactly

#

and this error starting popping up

#

the error which i posted up

dry portal
#

Hey everyone, I've been getting into some Flask and Gunicorn-based web development recently and have a question. Currently, I'm running a Discord bot with an OAuth 2.0 flow that requires a website, and these run independently from each other. Ideally I would like to have some sort of communication between the bot script and website, so I wanted to test out running the website as a cog within the bot. Only issue there is, I don't know how to execute gunicorn from within a .py file. Is there a way to do it?

brave mantle
#

@dry portal No, there is not. They must be separate.

#

You might consider writing a REST API for the bot to use, or websockets

dry portal
#

Ah Christ it's never easy is it? 😛

#

Thanks!

brave mantle
#

well you can do it the way that works, or the way that's easy

#

:P

dry portal
#

I saw something about using multiprocessing to pass information over separate scripts but I could never get it to work

brave mantle
#

yeah don't do that

#

separation of concerns is a good thing

deep prism
#

fwiw, this is how you run a flask app with gunicorn with python:

from gunicorn.app import base
from gunicorn.six import iteritems

from xxx import application
from xxx.common import config


CFG = config.CFG

class xxxApplication(base.BaseApplication):

    def __init__(self, options=None):
        self.options = options or {}
        super(xxxApplication, self).__init__()
        self.application = application.app

    def load_config(self):
        config = dict([(key, value) for key, value in iteritems(self.options)
                       if key in self.cfg.settings and value is not None])
        for key, value in iteritems(config):
            self.cfg.set(key.lower(), value)

    def load(self):
        return self.application


if __name__ == '__main__':
    application.init()
    options = {
        'bind': '%s:%s' % ('0.0.0.0', CFG.app.port),
        'workers': CFG.app.workers,
        'threads': CFG.app.threads,
        'preload': True
    }
    xxxApplication(options=options).run()

Sometimes you have to do this if you want custom config.

#

It's mostly from somewhere in the gunicorn docs

dry portal
#

Hmm thanks, but is there any reason not to do this?

#

@deep prism

deep prism
#

Running gunicorn with python: No reason not to
Running a website in a discord bot: Kinda weird to do. A discord bot is a discord bot, and a website is a website...

brave mantle
#

you can't really embed much into a discord bot

#

aiohttp, maybe

#

but you definitely won't be using gunicorn

dry portal
#

Gotcha. In that case I might go a different route then. Thanks again for the help to both of you 😄

velvet trellis
#

Anyone have any experience with Flask + SQLAlchemy? I'm trying to figure out a way to filter an error in jinja2.

#

I'm trying to render a user profile on a webapplication and one of the database entries is a team_id. If they have a team_id in the DB, the profile page of the user renders.

#

If the value of team_id=NULL I get File "/Users/scott/PycharmProjects/agoge/app/routes.py", line 145, in user return render_template('user.html', user=user, team=team.team_name, posts=posts.items, AttributeError: 'NoneType' object has no attribute 'team_name'

#

and my route looks like this

#

@app.route('/team/<team_name>') @login_required def team(team_name): team = Team.query.filter_by(team_name=team_name).first_or_404() return render_template('team.html', team=team)

meager anchor
#

thats a different route

velvet trellis
#

woops you're right.

#

One sec.

#

@app.route('/user/<username>') @login_required def user(username): user = User.query.filter_by(username=username).first_or_404() team = Team.query.filter_by(id=user.team_id).first() page = request.args.get('page', 1, type=int) posts = user.posts.order_by(Post.timestamp.desc()).paginate( page, app.config['POSTS_PER_PAGE'], False) next_url = url_for('user', username=user.username, page=posts.next_num) \ if posts.has_next else None prev_url = url_for('user', username=user.username, page=posts.prev_num) \ if posts.has_prev else None return render_template('user.html', user=user, team=team.team_name, posts=posts.items, next_url=next_url, prev_url=prev_url)

#

I think the way to go is put an if statement in the jinja template

#

but it doesn't seem to work.

meager anchor
#

well, your error is in your python code, not template

velvet trellis
#

pseduo it would be... - if team == None do X

meager anchor
#

you can use something like team.team_name if team is not None else None or if you're lazy getattr(team, 'team_name', None) to pass None if the team does not exist

#

or just pass the team itself, and do that is not none checking in your template

velvet trellis
#

You're talking about in the route render_template function?

#

or in the user function

#

because the user function displays just fine if there is a value in the database

neat nest
#

you've got team=team.team_name. your error is telling you that team doesn't have a team_name attribute because it is None

velvet trellis
#

Oh I see, so its erroring in the render_template function and never returns values to display.

neat nest
#

erroring in your user function because it can't call render_template with something that doesn't exist, but you've got basically the right idea

velvet trellis
#

Right ok

#

So would I put a check within the user function?

#

if Team is not none?

neat nest
#

yup, that's essentially what Volcyy recommended

#

although he gave you snippets for doing it inline

#

what you proposed works as well

velvet trellis
#

Right I was trying to figure that part. Sorry, pretty beginner. I'm doing the miguel grinberg tutorial for flask and trying to expand on it now.

neat nest
#

that's awesome! let us know if you have questions with anything else

velvet trellis
#

awesome. getattr() worked. Time to learn a new function 😃

brave mantle
#

turns out there are stock photo sites that license under the CC0 license

#

free images, no attribution whatsoever

still briar
#

Yoink. 📸

brave mantle
#

:>

still briar
#

Except

brave mantle
#

then you didn't read the site properly did you

#

you went to their partner

#

free stuff first, then there's a break where it says "look at this premium stuff from our partner"

still briar
#

Aah right, Sorry, no pictures found! Here are some search tips: and then there's Sponsored Photos

brave mantle
#

yep

hearty birch
#
                           {% if form.email.errors %}
                                <div class="uk-inline">
                                    <span class="uk-form-icon uk-form-icon" data-uk-icon="icon: user"></span>
                                    {% for error in form.email.errors %}
                                        {{ form.email( **{ 'class': 'uk-input uk-form-large uk-form-danger', 'placeholder': 'Email Address', 'uk-tooltip': {{ error }} } )}}
                                    {% endfor %}
                                </div>
                            {% else %}
                                <div class="uk-inline">
                                    <span class="uk-form-icon uk-form-icon" data-uk-icon="icon: user"></span>
                                    {{ form.email(class="uk-input uk-form-large", placeholder='Email Address') }}
                                </div>
                            {% endif %}

pretty disgusting but i'm trying to use a tooltip to display the error in a field.. as you can see this is horrible and not working either. any suggestions?

brittle copper
#

Is that django or jinja

hearty birch
#

jinja

#

using flask

brittle copper
#

Hmm I don't know much about jinja but in django

#

After you open a {{

#

You don't need an inner one to enter variables

#

{{ error }} } )}}

#

Like this

#

Don't know if it is related

hearty birch
#

so how would I access {{ error }}

#

it probably is

brittle copper
#

You just write error

hearty birch
#

oh wow

#

ty ❤

brittle copper
#

Worked? :D

hearty birch
#

I did not know that

#

yeah :p

brittle copper
#

Nice :D

hearty birch
#

that is great actually, fixes a lot of problems I had

#

can I do something like

#

'uk-tooltip': error + '; pos: right;'

brittle copper
#

In django yes

#

Don't know about jinja but probably

#

But the whole thing needs to be in {{}}

hearty birch
#

great

#

I'll try later

brave mantle
#

wait what

#

you're applying this to a tag in your template surely

#
<div uk-tooltip="title: {{ error }}; pos: right;">
    ...
</div>
hearty birch
#

its in a template yeah

#

if that's what you meant o.o

#

oh wait

brittle copper
#

They were using multiple variables so I think {{ var + 'foo' + var2 + 'bar' + var3}} is better than 3 {{}}

hearty birch
#

hmm

#

ok now im confused

brittle copper
#

About?

hearty birch
#

what gdude's talking about

brittle copper
#

Why

#

If you are using a single variable that is how you put it in

hearty birch
#

i'm using wtforms

#

so i can't really do that I think

brittle copper
#

I don't know anything about wtforms but that is the usual way how jinja works

#

Like it is the exact way of using jinja for a single variable

hearty birch
#

its working so far

#

but, looks pretty ugly

#

the code

little nexus
#

ive got a problem somewhere in my website on the backend. im using the dash python framework (which allows interactive graphs) which itself is built on flask. when the dash callback finishes (this is code i have written to respond to a button being pressed), the data is sent from the flask backend through gunicorn, which is then proxied through nginx. however, somewhere in the line, my large set of data being sent via a post request is getting delayed. the data consists of 8MB of json data. the callback in python finishes in 15 seconds, but my browser does not start receiving data until 60 seconds after the button press. any ideas on where to look for the delay. other callback which send small amounts of data (a few KB or so) are instant and have no problems

#

the callback starts at algo parse stats and finishes at callback timer stats

little nexus
#

ok im pretty sure this is a problem with gunicorn in some way now

#

gunicorn is regestering connection closed (debug mode enabled) 45 seconds after the callback function is finished

still briar
#
def register(request):
    if request.method == 'POST':
        form = forms.RegisterForm(data=request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            basic_password = form.cleaned_data.get('password1')
            user = authenticate(request, username=username, password=basic_password)
            login(request, user)
            return redirect('home')
    else:
        form = forms.RegisterForm()
    return render(request, 'register.html', {'form': form})
#

I'm using Django, and here's a register form. On submit, post, you create a new account.

#

But when I double-click on the register button, sending two requests at the same time, it crashes on form.save(). User is not unique.

#

So my guess is that in sending two requests quickly, it tries to create the user twice, which creates a IntegrityError: UNIQUE constraint failed: auth_user.username

#

How can I solve this?

hearty birch
#

just a quick question, is there a way to select a random string from a list in jinja.. or should I be handling that in python itself

pearl kite
#

That's pretty easy in Python itself

#

random.choice(list_of_strings)

#

iirc

brittle copper
#

You can probably add functiona in Jinja just like in Django templates

#

@hearty birch

#

Search for template tags jinja2

#

Yup write the function in python

#

Use them in jinja

hearty birch
#

yeah I know how to do it in python, just thinking if it’s better to write it in jinja or python

brittle copper
#

Like list|function_that_returns_random

hearty birch
#

I just want to randomise a legend for my login

brittle copper
#

I am explaining how to do it in jinja

hearty birch
#

was answering Lord Greyweather

brittle copper
#

Oh

hearty birch
#

sorry i am a bit tired but go on how would I do it in jinja?

#

because it is something small so idk if it’s worth me writing it in python - but then again it’d probably look ugly in jinja

brittle copper
#

Apparently jinja and Django templates are a bit different here

#

Here is how you register a function for jinja templates

hearty birch
#

i think they’re called macros or something right

brittle copper
#

Django calls them functions

#

Lol

#

Well it calls them template tags actually

hearty birch
#

I see a flask specific answer

#

pretty complicated for what i’m trying to do but probably the best way I guess, thanks ^^

brittle copper
#

You already should be using your view if possible

#

There are some things that incredibly hard to do in view and sent to the html

#

Use template functions only then

hearty birch
#

I shall keep that in mind

#

ty (:

still briar
#

Anyone familiar with RedisChannelLayer?

fierce sandal
#

woah didnt see this channel

deep cave
#

maybe thane knows about redischannellayer. pretty sure he's worked with redis. @still briar @safe python

#

he's probably busy at work right now though

safe python
#

Got to work 5 minutes ago. My stuff is on redis. I do not know what redis channel layer is.

still briar
#

@safe python

#

Oh whoops

safe python
#

@still briar

#

Hi

still briar
#

So I'm using websocket and consumers in Django.

safe python
#

If I had the time, I'd move to another database solution

still briar
#

The AsyncJsonWebsocketConsumer (BaseConsumer) requires a channel_layer, which is set in settings.

#

I dunno, the redis solution works. We wanted something more light weight with expiries?

#

It's just that the consumer has only access to a "channel_layer" which is some blob using redis, and it only really supports group_add and send_group stuff.

safe python
#

If it work, use it. I wasn't saying not to. I want to use different DBs for sake of experience.

still briar
#

True true.

safe python
#

I also want 48 hours in a day, though

still briar
#

Oh definitely.

deep cave
#

just sleep every second day

#

problem solved

safe python
#

Then I just have double work every other day

still briar
#

So anyhow, it seems we managed to connect to the channel_layer's redis by using ```python
index = self.channel_layer.consistent_hash(table.id)
return self.channel_layer.connection(index)

safe python
#

Problem shuffled

still briar
#

Where the returned value is an redis object that has get, set, delete, etc. Feels like I'm playing with cookies.

#

Although I noticed only today that the consistent hash is only necessary if you have multiple hosts which I think there's only one of in my django settings, so the index always ends up at 0.

#

So whoops, the redis database was global for the entire project, which caused some problems. 💦

native tide
#

Hello!

still briar
#

Well, we wanted it specific per table, so a solution is to just add the table id to the cookie key. redis.get(str(table.id) + 'gameinfo') ish

#

I barely know any redis. Are you supposed to use it just with get set delete? What other cool stuff are there?

safe python
#

Lmao redis #databases have a whole bunch of other commands. Get, set, and delete work with single string items. There's sets, lists, hashes (equivalent roughly to dicts, a key val mapping), and sorted sets with scores

#

Have you been through the docs for redis.StrictRedis?

still briar
#

I'll check it out!

#

As of now I guess I've done everything in strings. Json dumping the game data, getting/setting it.

safe python
#

Redis values don't have layers, like, you can't directly map multi level dicts/JSON to it, but it does have namespaces

#

I think the default separator is a semicolon

#

Get yourself Redis Desktop and play around with it on a local database. You'll get a feel for what redis can do real quick.

still briar
#

Right right.

safe python
fierce sandal
#

What kind of data can I store in a session? Integers? Strings? lists?

#

What can the lists contain? Can I store objects, or their references in a session? Not that I ever would, just wondering

brave mantle
#

Sessions basically just store strings

#

Although it depends on the framework

#

Flask sessions are encrypted JSON

#

(for example)

fierce sandal
#

I see

still briar
#

In Django, is there a way to tell the difference between two sessions/requests of the same client?

#

If I'm logged in and open a new tab, I'm still logged in, and the request.user is the same.

brave mantle
#

It's just a cookie

#

so there is nothing really

still briar
#

When it comes to http requests I suppose it doesn't matter. I'm playing around with sockets and consumers though. You can reach that same user object with self.scope["user"]

#

But I'm trying to make a user list where when someone joins, they're added, and removed when they leave.

#

And the problem is when you join with a second tab and leave, the first one is kicked out as well.

#

Oh hello.

#

self.scope['cookies'] -> {'sessionid': 'rth25htmrbhmfoit0wnsew8xgd0n5640' ...

#

Actually I got access to both sessionid csrftoken, which are both really long strings?

subtle tinsel
#

Anyone awake in web-dev have a second? I have a few questions that are probably pretty dumb

#

Bonus points if familiar with Wordpress

deep cave
#

don't ask to ask.

#

dumb questions are welcome.

#

there's always someone here.

subtle tinsel
#

I guess mostly the issue is im not exactly sure what the correct question is

#

I dont have much of a computer background but have done some simple hobby coding for years. I recently put up a personal website using AWS EC2 and have some questions about how to integrate data from simple scripts ive written in python to my webserver

deep cave
#

aha

subtle tinsel
#

Like

deep cave
#

well what's your website running on now?

subtle tinsel
#

Bitnami image of wordpress

deep cave
#

is it wordpress? since you mentioned that

subtle tinsel
#

so

#

php

deep cave
#

I see.

subtle tinsel
#

Like

#

Basically

#

Im trying to document my process of learning to code

#

so it would be nice to be able to realize and understand capabilities of displaying my data

sturdy sapphire
#

wordpress has alot of tools to import data, I have successfully used many of them in the past

deep cave
#

it might be that wordpress is a bad choice for this. what you're asking is theoretically possible, though.

subtle tinsel
#

or do I / can I run flask next to my WP site

#

Like WP for blog and ease of use and a flask app next to it

#

if possible

sturdy sapphire
#

but you rely on third party tools, and they might break when you update WP

deep cave
#

technically your flask app could be a page on your WP site.

subtle tinsel
#

Can I use the same hostname for that etc

#

Yeah Ive kinda seen what you mean @sturdy sapphire

#

Am I able to just write a flask app and use the same domain to point to it?

deep cave
#

yes absolutely

subtle tinsel
#

Would be easier to integrate python

sturdy sapphire
#

i had a WP api that i could communicate with, getting data in and out from an android and IOS app, but it broke after a year...

#

I have also an flask app at work that have been running for 2 years without issue

deep cave
#

I would personally recommend that you do that. because trying to execute and fetch data from python scripts from a wordpress site is.. icky.

#

suboptimal

subtle tinsel
#

^

#

Thats what I came to see after doing some research

deep cave
#

but you can definitely point part of your blog at the flask app

subtle tinsel
#

I just dont know enough about web dev to know how to configure all that

deep cave
#

it's quite trivial to do so

#

we can help with it

#

the obvious way is to just set up a subdomain

#

and point that at the flask app

#

and then make a menu item or whatever in your WP app that points at that subdomain

subtle tinsel
#

Ah

#

I see

#

I figured It was possible just wasnt sure what to look for

deep cave
#

so you can have like scripts.mypage.com or something pointed at your server

subtle tinsel
#

bam

#

thank you

deep cave
#

and in your apache or nginx or whatever you're using, you can tell that subdomain to load your flask

#

and then on wordpress you just add a menu item that points at that

subtle tinsel
#

that makes sense

deep cave
#

and on the flask app, you add menu items that point back at wordpress

#

maybe have the same sort of navbar

#

and it will all look like one page

#

be quite seamless.

subtle tinsel
#

tyvm

deep cave
#

np, let us know if you get stuck on any step :)

#

in the long run, you might wanna just use flask for your blog, too. when you get more confident, perhaps.

subtle tinsel
#

Yeah i would like to

deep cave
#

it's a good learning project.

subtle tinsel
#

Its just

#

The wizards and plugins make WP so easy

#

lol

deep cave
#

yes it does.

#

and I'm guilty of using wp for a few projects myself

subtle tinsel
#

Lol

deep cave
#

but writing from scratch is sooo satisfying, and you get complete control of every aspect

#

and WP does kinda suck

#

and PHP is a crime against humanity

subtle tinsel
#

"Bam look at my website" (I did in under 3 hours with minimal experience)

sturdy sapphire
#

I use WP alot, but for my personal blog it just gets cluttered up and i stop using it..

#

so i am also thinking about making everything in flask

subtle tinsel
#

Yeah

#

The constraints of the plugins seem cumbersome

sturdy sapphire
#

or django, but i have no experience with django

subtle tinsel
#

but the ease of implementation is so tasty

#

I wanna tackle flask until it frustrates me, then use django but I wanted something up quick because I want a new job yesterday

buoyant ledge
#

Is there a reason why flask wouldn’t work as a full web server without Apache or something in the way?

subtle tinsel
#

It would but I'm a novice programmer so its easier for me to host WP now and work on a flask app once I feel more confident

#

My current job is not in the CS industry, it's in the electricalk industry so I'm using the site currently as a pseudo-resume

#

But I'd like to migrate to IT or similar so I figure work on it now and eventually Ill have something

buoyant ledge
#

Sorry. I didn’t mean that directed at you. I just meant in general why does flask say not to use in prod when you start it up. Like what does it lack that Apache has

subtle tinsel
#

O lol

deep cave
#

flask is not a server. the development server is not fit for production use. there are a great deal of reasons why, but most of them boil down to security and performance.

#

you'll be exposed to DDOS attacks and it'll all be running on a single worker, which means if more than one person use your web service at the same time, you're gonna run into trouble.

buoyant ledge
#

Ah fair. So you need something like Apache to handle load balancing and such in the background but there’s nothing wrong with using flask inside of it to serve the content?

deep cave
#

flask is wonderful when used together with something like apache, yes.

#

personally I use gunicorn and nginx

brave mantle
buoyant ledge
#

So as a general web dev question. Let’s say I want a service that acts as a phone book between users and their devices at home. This is kind of a continuation of my doggy cam project in #303934982764625920 just to learn more about stuff.
If I wanted to allow users to sign in and get the feed of their webcam. Would the best way to do that be to store IP/Port of flask app in a database using the username as a key? Or something similar?

hearty birch
#

to handle logging in and stuff there is an extension for flask that helps

#

flask_login

#

but yes, you'd need a database most likely

brittle copper
#

Or if you want to learn it you may even write the authentication yourself

hearty birch
#

learning what is that

#

😄

brittle copper
#

The thing that I'm too lazy to do

buoyant ledge
#

I was probably going to do the authentication in php cuz I’m miles more familiar but I might stick to flask just to learn it more

brittle copper
#

ew php

buoyant ledge
#

It’s the future man

marsh canyon
#

Lol

buoyant ledge
#

PHP has 3 letters, python has 6 so you save 3 characters googling

brittle copper
#

You type to google stuff?

#

So 1990s

mystic sparrow
#

I have a simple flask app that interacts with a database. I'd like to keep checking the database for changes (24/7) and send notifications based on that info. Is it feasible and a good idea to use flask for constantly checking the database? If so, any suggestions on what I should be looking into? celery? Advanced Python Scheduler? something else? Shouldn't use flask?

brave mantle
#

Celery would work

#

but you should just use cron if you have that option

mystic sparrow
#

Thank you very much for the input 😄 wasn't thinking of cron as an option, but I guess I would be fine with checking every few minutes instead of every few seconds.

brave mantle
#

it can do that too

#

but you should really consider whether that's an appropriate thing to be doing

#

depending on the database, reading might lock access to the tables for a moment

#

slows everything down

obtuse turret
#

I'm just wondering, what are the differences between Flask and Django?

proven stone
#

Django is batteries included. It's all the bells and whistles whether you need them or not

#

Flask is more like a simple base to start but expandable

#

I've only made a few simple web apps so flask was perfect for me

#

I imagine if you're building something large and complicated Django would be beneficial

obtuse turret
#

Yeah, I'm going to work on small sites, so I think flask will work for me, thanks

#

Is it possible to combine them?

proven stone
#

You wouldn't want to

obtuse turret
#

How about using Django for security

proven stone
#

As far as I know flask can do pretty much anything Django can with extra modules

#

I feel like if you're using part of Django you may as well use the whole thing

#

Using 2 frameworks that serve the same purpose seems like an inefficient complication

#

But I'm a beginner so I could be incorrect

#

You could go through a blog tutorial in each one pretty quickly then decide

meager anchor
#

well, django has built-in utilities for pretty much everything and is easily extendable too

#

just install some thing and add it to INSTALLED_APPS

dusky lake
#

Anyone have a bit for a voice chat on pycharm/windows/django?

polar robin
#

No. We do not provide one-on-one tutoring - you can hire someone locally if you really need that. We also prefer that questions are answered in a public channel as it means that everyone else present is able to learn from them. If you're working with code that you are unable to disclose for any reason, you should try to make your question more general and write a separate, small piece of code to illustrate your problem.

eternal thunder
#

Hello

#

I was wondering, what is the best way to collect stats in Sanic?

#

Like

#

We want to know the amount of requests per ip per day/week/month

#

What would be the best approach for this?

meager anchor
#

look into middlewares

#

have one run on each request

#

access the request ip and save it somewhere

#

by the way

#

also asvetlov is an aiohttp team member & python core dev and worked heavily on asyncio iirc. so thats not just coming from some random dude

hearty birch
#

but he’s just promoting his own!!!!!!!!

#

lol, the thread is pretty funny

meager anchor
#

it is, and the guy didnt even plug aiohttp in the post itself lol

eternal thunder
#

yeah but @meager anchor what would be the best way to store the data

tame viper
#

spent ages wondering why CSS wouldn't work
had browser cache enabled
😎

still briar
#

F12 no cache is the only way to go

neat nest
#

Ctrl+Shift+R to refresh always no matter what

hearty birch
#

^^

#

@tame viper been there. very sad 😦

brittle copper
#

Why don't you people just turn off the cache on your browser for 127.0.0.1/*

little nexus
#

found my problem

#

dash json encoder takes 43 seconds to encode the response

#

😠

tame viper
#

so i have a flask app with a divisional folder structure. in my app/views/main.py file, i have a route and two helper functions defined. is there any better place to put the helper functions rather than in the views script like i have here?

...
main_bp = Blueprint("main", __name__)


def get_access_token():
    # code here ...
    return as_json


def get_user_info(token):
    # more code here ...
    return response.json()


@main_bp.route("/")
def index():
    user_info = get_user_info(current_token)
    return render_template("main/index.html", user=user_info)
tame viper
#

ok i need help (@grand badge suggested i post it here). i have a flask app which is running on my website, and one part of it uses the msg. subdomain. however, when i try to view that subdomain, it just sends me straight to the main page (w/o subdomain). i imagine this is because nginx isn't telling the docker container which subdomain is being viewed, though i can't think of why that would be. i've tried loads of different things, but this is what reproduces the outcome i just explained:

server {
        server_name codingbykingsley.co.uk www.codingbykingsley.co.uk msg.codingbykingsley.co.uk;

        location / {
                proxy_pass http://172.17.0.2:5000;
                include /etc/nginx/proxy_params;
        }
}

i've also tried this, but it just makes all of my subdomains point to a different subdomain of the website which is referenced by a completely different nginx config:

server {
        server_name codingbykingsley.co.uk www.codingbykingsley.co.uk;

        location / {
                proxy_pass http://172.17.0.2:5000;
                include /etc/nginx/proxy_params;
        }
}
server {
        server_name msg.codingbykingsley.co.uk;

        location / {
                proxy_pass http://172.17.0.2:5000;
                include /etc/nginx/proxy_params;
        }
}
proven stone
#

i think you have to use proxy_set_header

#
    proxy_set_header Connection "upgrade";
    proxy_set_header Host $http_host;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header X-Forwarded-For $remote_addr;
    proxy_set_header X-Forwarded-Port $server_port;
    proxy_set_header X-Request-Start $msec;
#

in the location block

tame viper
#

include /etx/nginx/proxy_params; does most of those lines, but i'll give it a shot ^^

proven stone
#

o ok i was looking into my conf's for how dokku handled it

#

dokku does all this for me automagically

tame viper
#

just tested it, got the same as the top code i showed. thanks anyways :D

proven stone
#

do you have a server block with subdomain.domain.tld

#

o duh forget it

tame viper
#

:D

proven stone
#

is the container for msg.domain.tld the same as domain.tld

tame viper
#

yes, because they're in the same flask app

#

i figured it wouldn't be an issue as flask allows you to put subdomains on your routes

proven stone
#

what if for X-Forwarded-For you used $proxy_add_x_forwarded_for

#

eh shit that's not it

#

weird

tame viper
#

i think i can see what is happening, but i have no idea why or how to fix it

proven stone
#

ok i have one last thing to to try

#

proxy_pass http://172.17.0.2:5000$request_uri;

#

for the subdomain

tame viper
#

nope, doesn't work

proven stone
#

😦

tame viper
#

thanks for trying though ^^

proven stone
#

have you checked if msg.subdomain.tld works directly, without the proxy

#

connecting to the container

tame viper
#

how do you mean?

proven stone
#

so on that machine you could edit your host file to point that subdomain to the docker ip

#

then try to accesss it

#

bypassing the nginx proxy, to see if the problem is flask/docker

tame viper
#

sure

#

would i have to check it from within the server?

proven stone
#

yes

tame viper
#

very well

#

give me a moment then

proven stone
#

that would at least let you focus on one part

tame viper
#
ubuntu@ip-172-31-34-189:/etc$ curl msg.codingbykingsley.docker:5000

this returned the HTML for the main page 🤔

#

hmm

proven stone
#

im not expert im just starting out so just a disclaimer

#

but i would guess that means flask is the problem

#

do you have SERVER_NAME defined in your flask app?

tame viper
#

oh, apparently not. i thought i had.

#

might that be the issue then?

proven stone
#

i believe subdomains can't work without that

tame viper
#

well, i'll have a tinker

proven stone
#
app.config['SERVER_NAME'] = 'local.com:5000'```
#

ugh why dont i do that right

tame viper
#

very well haha

proven stone
#
# IMPORTANT! subdomains will not work without the SERVER_NAME config
app.config['SERVER_NAME'] = 'local.com:5000' ```
#

there we go

tame viper
#

yay :D

proven stone
#

give that a shot replacing local.com with the correct info

tame viper
#

give that a shit

proven stone
#

haha

#

and don't forget when you're finished to fix your hosts file

tame viper
#

yup already reverted that

proven stone
#

let me know if it works

tame viper
#

if my docker container is running on 172.17.0.2:5000, would i also add :5000to the SERVER_NAME?

proven stone
#

i was wondering if you were going to ask that because honestly i don't know

tame viper
#

haha well, we'll see

#

no harm in trying

proven stone
#

but my guess is yes

tame viper
#

well that's making all of my pages return 404 so let's see if it works without port

#

oh hey, it works now :D

proven stone
#

sweet

tame viper
#

thanks a lot ^^

proven stone
#

no problem

tame viper
proven stone
#

first step which we skipped in the beginning should always be test things seperately

#

make the problem smaller

tame viper
#

yeah, that's a good technique

proven stone
#

because we might have still been fiddling with nginx all night for no reason

tame viper
#

i usually do that but it's 4AM and i feel like my brain has come out of a blender

proven stone
#

and just so you know i used almost no prior knowledge to help you it was pretty much all google lol

tame viper
#

well i already tried google but apparently i'm not good enough :D

proven stone
#

well time for bed for me im glad it works

copper forge
#

Gn fam

tame viper
#

goodnight ^^

hearty birch
#
{{ form.picture(class='uk-button uk-button-default', type='button', tabindex='-1') }}

Getting an error on this line in Jinja2

TypeError: html_params() got multiple values for keyword argument 'type'
#
<button class="uk-button uk-button-default" type="button" tabindex="-1">Select</button>
#

using Flask and WTForms

#

or

#

probably a better question,
which class would I use in UIKit to allow WTForms to access File Upload
I know in bootstrap it is form-control-file, I would like something similar

#

excuse the poor terminology ^^

#

ohh I understand the error now

#

I think the WTForms already says that type='file so I was trying to overwrite it when specifying a type, thus giving the TypeError

#
<div uk-form-custom="target: true">
    {{ form.picture() }}
    <input class="uk-input uk-form-width-medium" type="text" placeholder="{{ form.picture.label.text }}" disabled>
</div>
<button class="uk-button uk-button-default">Submit</button>

I just did something like this and it kinda works

velvet trellis
#

Anyone familiar with flask-upload? I'm trying to create a form that has several fields with a file upload button but I want uploading a file optional
and it seems like flask-upload requires a file. I can't figure out how to except the None type.
if I add a file everything works perfectly fine.

sick forum
#

anyone good at django REST framework? im trying to figure out how to generate docs for function-based views. i want to be able to specify things like parameters, etc, in the comment and have them show up in the docs

native tide
#

Hello. Anyone know how to create your own Register/Login/Logout form in django?

sick forum
#

the easiest way is to use the built in auth views with your own template

from django.contrib.auth import views as auth_views

path('accounts/login/', auth_views.LoginView.as_view(template="yourtemplate")),
meager anchor
#

I don‘t think you even need to make your own view

#

Overriding the template should suffice

sick forum
#

can anyone answer my django question?

anyone good at django REST framework? im trying to figure out how to generate docs for function-based views. i want to be able to specify things like parameters, etc, in the comment and have them show up in the docs

native tide
#

@sick forum in this moment i using this form, but i would like to create my own. Okay, thanks for Your answer.

meager anchor
#

When do I need to request consent for stuff collected by my website? Simply speaking, the website itself does not collect any data, does not track its users, and does not use any third-party services for analytics or tracking. The only thing it uses is Discord's OAuth, and it uses that when a user logs in. For everyone else that's visiting, that's irrelevant. Do I need to get consent only on the log in view or globally?

brave mantle
#

Only on login

#

but you should do it before they actually give you their info

#

not after

meager anchor
#

Yeah, okay

#

Thanks

hearty birch
#

how easy is tracking things such as time spent on a website, and other statistics like these on Flask

polar robin
#

so you can track users around the website

hearty birch
#

ah!

#

that's pretty nice

neat nest
meager anchor
#

@vestal hinge can you try passing the request to the authenticate call

hasty wing
#

@neat nest thanks, I'll do that

meager anchor
#

also, what are your AUTHENTICATION_BACKENDS defined as

hasty wing
#

Basically, I wanna be able to have a view called "remove" that will remove a quote from favorites when activated. I can't figure out how to make this happen. I'm really bad at queries I guess lol

meager anchor
#

Can you post your code somewhere online instead, e.g. hastebin, please? Most people will probably not go through the process of downloading a zip file

meager anchor
#

Yes, thank you
You want to delete a single object, correct?

hasty wing
#

I wanna delete a single entry in the many to many field, sorry for the late response

#

@meager anchor So in my many to many there's an id, user_id, and quote_id. I wanna filter and find the user_id and quote_id that match and then delete that entry from the field

meager anchor
#

But the issue is that you don‘t currently have any ID to reference in the deletion view, right?

hasty wing
#

I have the reference id but i just have no idea how to make the query

#

So idk what code to write that would make this work

meager anchor
#

I don‘t think you need to interact with the manytomanyfield directly

hasty wing
#

For reference as to what I'm doing. When a user clicks "add to favorites" I'm logging the user's ID and the quote's ID in a many to many field. What I need is a way to get rid of field that I created when I use "remove from favorites"

meager anchor
#

From the user‘s quotes, that is

hasty wing
#

I'm trying to remove the many to many relationsip though not delete the quote outright

meager anchor
#

Not sure I follow. You want to remove the Quote entry where userid = request user id and quote id = unfavourited quote id, right?

hasty wing
#

yes! exactly

#

When i remove it from my many to many relationship it will naturally go back to the "Quotable Quotes" field

meager anchor
#

What I would do is get quote objects which have user_id=request.user.id and quote_id=the unfavourited quote ID

#

however, looking at your models, I just noticed that the user ID is stored as a charfield on your quotes

#

Well, the poster_id

hasty wing
#

Quote.objects.filter(user=request.session['id']) should give me all the users favorites

#

So from there I just need to filter it more so I get the favorite with the ID I'm trying to unfavorite, right?

meager anchor
#

Yeah

hasty wing
#

Quote.objects.filter(user__quote=id, user=request.session['id']).delete() is what I just tried but that deletes all of a users favorites and deletes them from the whole database. I just want them out of favorites lol

meager anchor
#

I don‘t understand what the first condition is doing, so maybe its getting ignored or something. The quote should have an id attribute since you didn‘t give it any that you can compare against

hasty wing
#

"id" is the id of the quote I'm trying to delete. "user__quote" was the way I thought I could call the quote object in user

meager anchor
#

What I meant was, if you don't specify a field with primary_key=True, Django will (probably) autogenerate an id field as the primary key

#

Like, in the fave method, you also filter by id:

    def fave(self, user_id, quote_id):
        self.get(id=quote_id).user.add(User.objects.get(id=user_id))
hasty wing
meager anchor
#

Ohhhhhhhhh

#

God damn sorry, I completely forgot. I kept thinking that the Quote model are the favourited quotes, but you use the manytomanyfield for that, right?

hasty wing
#

yeah

meager anchor
#

Let's hope I got everything right..

Quote.objects.get(id=quote_id).user.all()

That should give you all users who favourited the given quote. Then, you should be able to filter by the user ID with ```py
Quote.objects.get(id=quote_id).user.filter(id=request.user.id)

And you can delete that by using `.delete()`
hasty wing
#

Just deleted it and opened the zip. Old file seems broken beyond repair lol.

meager anchor
#

Hmm

hasty wing
#

Quote.objects.get(id=id).user.filter(id=request.session["id"]) will work (it seems) but now I need the delete to work without ruining my entire project lol

#

Yeah, everytime I use the .delete() everything ends up screwed

meager anchor
#

What is

Quote.objects.get(id=id).user.filter(id=request.session["id"]).all()

?

#

It should only be a sequence of favourited quotes by the user

hasty wing
#

ill test it, one sec

#

It returns only 1 object

#

not multiple objects

meager anchor
#

How did you run the .delete()?

hasty wing
#

added it in the same space where you put .all()

meager anchor
#

And that deleted all the objects of the ManyToManyField?

hasty wing
#

It kinda fucks up the entire app, but idk why.

meager anchor
#

Oh wait, no. I think the issue is that my example is filtering by the ID of the ManyToManyField, not the user ID. try ```py
Quote.objects.get(id=id).user.filter(user_id=request.session["id"]).all()

instead
hasty wing
#

i'll try

#

"Cannot resolve keyword 'user_id' into field. Choices are: alias, dob, id, name, password, quote"

meager anchor
#

what even

#

but that's the manytomanyfield?

hasty wing
#

yeah it should be in the manytomany

#

yeah

#

thats it

meager anchor
#

That's weird, but the ORM is probably mapping the user objects above it, soo I have another idea, yay... Try the same with user__id. user_id resolves the literal field user_id, and user__id checks user.id

hasty wing
#

user__id isn't working either. this is so odd...

meager anchor
#

Same error?

hasty wing
#

yeah

meager anchor
#

I think I found the issue.

#

I've been giving you wrong examples for using the ManyToManyField 🙃

#

So in your case, I guess that would be:

user = User.objects.get(id=request.session['id'])
quote = Quote.objects.get(id=quote_to_unfavourite_id)
quote.user.remove(user)
hasty wing
#

IT WORKED!

#

Holy shit

#

thanks so much!

meager anchor
#

Don't thank me, I wasted your past 2 hours because I was looking in the wrong spots :P

deep prism
#

Reading that makes me think you should rename the user field to users in the quote class

hasty wing
#

I'm gonna read that article so I remember this for next time.

#

@deep prism Yeah I prob should

native tide
#

Is there anybody who didn't know how to create test's in django?xD

native tide
#

I have a problem with this error in my Django project: "'WSGIRequest' object has no attribute 'user_is_authenticated'" . I using Django 2.0 version and i have a optional MIDDLEWARE class. Anybody know how to fix it?

brittle copper
#
request.user.is_authenticated```
#

@native tide

#

Also I've never ever used tests in django nor in python at all if you are talking about unittests

native tide
#

@brittle copper# I have it in my views.py file, I mean request.user.is_authenticated but django show me this error message xD

brittle copper
#

'user_is_authenticated'

#

user.is_

native tide
#

O MAN

#

i find it xDD

#

Okay, Thank You

brittle copper
#

Anytime

native tide
#

now everything works xD

brittle copper
#

Nice

native tide
#

Yes i know, i just have second option where was 'user_is_authenticated'

#

XD

#

Thank You very much!

brittle copper
#

Anytime

hearty birch
#

To edit base colours in a css framework, like UiKit for example, what do you guys do?

deep cave
#

what the framework suggests - edit the scss

#

there are docs for it.

#

at least in bulma

#

but it boils down to just overwriting the variables they use for the base variables and then importing the scss - then using that file to generate the css for your page

#

also scss is awesome and you should learn it anyway.

hearty birch
#

ah okay, I’ll probably have to try that out

#

the base colours are nice but get boring :p

vestal hinge
#

@meager anchor wdym

pearl vessel
#

how do you guys deal with memory limits when deploying a website? aws free tier allows 1 GiB memory

brave mantle
#

Memory isn't really a problem for most sites

meager anchor
#

@vestal hinge wat

#

with GDPR, do I need to collect consent for caching static files?

#

because that would be absolutely awful

#

seeing as nginx does the caching and i would have to move all of it to django

brave mantle
#

Huh? Of course not

#

Static files are your files

meager anchor
#

No I mean

#
    location /static {
        expires 1h;
        add_header Cache-Control "public";
        alias /path/to/static/files/;
    }
#

With the Cache-Control header

#

That means its saved on the client, iirc

native tide
#

Hello! I have a question about display images in django TEMPLATES. I have one template like 'base.html'. And i would like to display there one of the pictures. What is the simple method to do it? I try with static~but django didn't see my picture.

native tide
#

@native tide, I'm just guessing, but you may have to use the collect static command so Django recognizes the static files

wary mantle
#

Hey. What is the difference between HTMLPY , Django and Flask?

polar robin
#

that question is really googlable

wary mantle
#

@polar robin Can't find it.

meager anchor
#

htmlpy is apparently some sort of electron for python

#

django and flask are web frameworks

#

django is fairly opinionated (which doesnt have to be a bad thing) and follows the batteries-included approach, while flask gives you more freedom and is rather minimal & customizable

hearty birch
#

never heard of htmlpy before

#

o.o

#

how long should flask's secret key be?

#

rn im using

import secrets
secrets.token_hex(16)
#

is that okay?

meager anchor
#

are you regenerating that on every run?

hearty birch
#

nope

#

I just generated it once and put it in my config file

meager anchor
#

i guess that works, although i usually aim for 100+ chars with passwords and keys like this

native tide
#

hey guys

#

I made a flask app

#

while it runs just fine locally

#

I'm having problems deploying it on a VPS

#

everything I do results in a 404

#

can anyone help me XD

meager anchor
#

depends on the web server you're using

rigid turtle
#

Ok, so it looks like I am finally going to be entering the wonderful world of web development (and unmuting this channel)
Have a large application that is currently CLI-only
Need to build a stateful long-lived network-accessible API
My current thinking is a REST API with a ORM-wrapped DB backend that maintains the state
The first request of a specific category and unique thing with state will return a state ID, and all future requests to that category require the ID referencing the state for the unique thing
The reason for needing to maintain state is the API is a way to interact with a large number of devices that are connected to the server hosting the API in a variety of ways (vary by protocol and physical interconnect)
Most of you are either web developers or have web experience...what are your thoughts?

still briar
#

What are you making?

tidal charm
#

If I am getting into web develpment what language should \

#

I use

rigid turtle
#

I'm making an API for an existing program

#

@tidal charm Python?

tidal charm
#

Yeah

native tide
#

@meager anchor I'm using apache

native tide
#

I'm using flask with flask-socketio and I'm having problems with long-polling connections not upgrading to websockets

#

I've installed uwsgi

#

and I'm running my app with this command:
uwsgi --http :5000 --gevent 100 --http-websockets --master --wsgi-file pecho/wsgi.py --callable app

#

this is my wsgi.py:

python
import os
from pecho import create_app

application = app = create_app(os.environ.get('FLACK_CONFIG', 'development'))
#

I'm also using gevent

#

I haven't installed gevent-websocket, because the documentation says I don't need it, if I'm using uwsgi

native tide
#

I have it working now! 😃

#

Before I initialized my connection on the client side with io()

#

but I'm not there yet, because now my frontend proxy isn't working for websockets

deep cave
#

@rigid turtle sounds like a good plan. I'd have gone with flask but ORMs are far easier in Django since it comes with one.

rigid turtle
#

Yeah, that was my thinking

#

Flask was first choice, but Django is very "batteries included", and I don't have the time or energy to put into assembling my own custom flux capacitor 😛

deep cave
#

yeah. I mean, to be clear, I would still have used flask. sqlalchemy ORM with postgres is pretty straight forward and I have no great love for django, but you are right that it is more work to set up.

#

if you want migrations you need alembic too

rigid turtle
#

This isn't that permanent

deep cave
#

but django sounds fine for this.

rigid turtle
#

Think of temporarily setting up a server while stuff is going on, then getting torn down after everything is done

deep cave
#

right.

rigid turtle
#

Though it might be used long-term, but persisting the data isn't a huge deal

#

We'll see how this goes tomorrow

#

Fridays are nice and quiet so they're the most productive for getting coding done

native tide
#

got my proxy working too 😃

native tide
#

Hey all

#

Anyone know how to create a simple search bar in django? I have a class with ListView and i don't know how to do it

grand badge
#

yes i do @native tide

#

you will need to override the get_queryset() method in your class

#

here is an example:


class SearchView(ListView):
    model = Post
    template_name = 'posts/post_list.html'
    context_object_name = 'posts'

    def get_queryset(self):
        term = self.request.GET.get('term')
        posts = self.model.objects.filter(title__icontains=term)
        return posts
#

get_queryset() as the name suggests, gets a queryset based on the data you give it

#

in your html template, the <input> must have a name attribute and you must supply that name in the get_queryset() method

#

in my example, i supplied the name in term = self.request.GET.get('term')

#

because in my html template, the <input> has the name attribute set to term

#

then what i did next was that i got all the posts and filtered them based on the title and then return the queryset you want

meager anchor
#

very clean implementation 👍

#

i've always wondered how you build these dynamic search bars

#

that like, work on the same site

#

probably some JS magic

grand badge
#

thanks :)

#

@meager anchor what happened to the Programming site?

meager anchor
#

its up

#

also on django :D

grand badge
#

you changed the domain name?

meager anchor
#

yeah

sudden lily
grand badge
#

take the <p> tags off, see if that does anything

#

@sudden lily

sudden lily
#

unfortunately nothing

grand badge
#

   <ul class="list-inline">
        {% for res in search_results %}
            <li>
                <div class="col-md-1" style="overflow: 'hidden'; padding-left: 0px; padding-top: 10px; padding-right: 0px;">
                    <div class="col-md-1 container">
                    <div class="row">
                        <img style="border-radius: 3px; width: 250px; height: 200px" src="{{ res.file }}">
                    </div>
                    <div class="row">
                        <p>BOGO Dog collar</p>
                    </div>
                    </div>
                    </div>
            </li>
        {% endfor %}
#

its wrapped in ul

#

and it has a class of list-inline which im guessing puts stuff in a list like fassion?

sudden lily
#

the way i set it up

#

it the jinja is constructing each part of the list and putting them all side by side

#

but I suppose I could just utilize the column features bootstrap gives

#

and not use a list at all

#

I'll try to refactor this

#

looks like it worked

#

Just need to reduce spacing now

native tide
#

@grand badge thanks for your answer! I will check it in one moment

#

@grand badge It still doesn't work. I do something wrong, and don't know what xD. Can i show you my code in views and templates?

native tide
#

So i have a simple template with BookList, and simple View

#

#BookList View
class BookList(ListView):
model = Book

template_name = book_list.html'
context_object_name = 'book'

def get_queryset(self):
    term = self.request.GET.get('term')
    posts = self.model.objects.filter(book_title__icontains=term)
    return posts
lavish prismBOT
#
codeblock

Discord has support for Markdown, which allows you to post code with full syntax highlighting. Please use these whenever you paste code, as this helps improve the legibility and makes it easier for us to help you.

To do this, use the following method:

```python
print("Hello world!")
```

This will result in the following:

print("Hello world!")
native tide
#

Ou! Okey, sorry

brave mantle
#

template_name = book_list.html'

#

you have an extra quote mark at the end of this line

native tide
#

I just forigve to write this in Discord

#

In my code i have '''template_name = 'plibrary_hearth/book_list.html'''

brave mantle
#

ah right

#

So what's the issue?

native tide
#

When i try to move in to my book list in my website i have this error

#

ValueError at /books/
Cannot use None as a query value

#

i think is something in my urls

brave mantle
#

Yeah, probably term is missing

native tide
#

Do you know how can i fix it?;<

brave mantle
#

It seems like you would have to check whether the value is None or not

native tide
#

I have a button with my book list and there is a search panel. Now, when i add get_queryset method to my BookList view and move in to Book List button in my website i have this error.

brave mantle
#

Well, you're expecting a term query parameter

#

so http://your/url/books/?term=whatever

grand badge
#

can you show me the current code you have again please? @native tide

native tide
#

Yes, can i send you with pastebin using?

grand badge
#

yep

#

the view for search

grand badge
#

class SearchView(ListView):
    template_name = 'book_list.html'
    context_object_name = 'book_title'
 
    def get_queryset(self):
        term = self.request.GET.get('term')
        books = self.model.objects.filter(book_title__icontains=term)
        return books

#

in the template you sent, is that the template that is meant to have the search bar?

native tide
#

No, my search bar is in base.html template

grand badge
#

show base.html please

native tide
#

here you are

grand badge
#

okay, in this code:

class SearchView(ListView):
    template_name = 'book_list.html'
    context_object_name = 'book_title'
 
    def get_queryset(self):
        term = self.request.GET.get('term')
        books = self.model.objects.filter(book_title__icontains=term)
        return books

#

change term = self.request.GET.get('term') to term = self.request.GET.get('search')

native tide
#

Okay, i change it

grand badge
#

try the search

#

oh wait

native tide
grand badge
#

theres something you are missing

#

you forgot to set the model

#

self.model doesnt exist

#

add a variable called model and assign the model you want to it

#

before template_name

#

ListView needs a model