#web-development

2 messages Β· Page 32 of 1

vagrant adder
#

twice the queries, twice slower

#

take a look at that video

#

3:20

hollow glacier
#

@vagrant adder can I pm you so I don't clutter the channel?

#

I have a few questions if that's ok with you

vagrant adder
#

ask here

#

if it's web dev based

hollow glacier
#

@vagrant adder I get this error:

[SQL: INSERT INTO todo (content, "isCompleted", user_id) VALUES (?, ?, ?)]
[parameters: ('hello', 0, None)]```

This is my models now:
```class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(15), unique=True)
    email = db.Column(db.String(50), unique=True)
    password = db.Column(db.String(80))
    todo_items = db.relationship('Todo', backref='user', lazy=True)

class Todo(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    content = db.Column(db.String(200))
    isCompleted = db.Column(db.Boolean)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)```
vagrant adder
#

just a sec

hollow glacier
#

ofc

vagrant adder
#

did you do db.drop_all()

hollow glacier
#

yeah

#

The problem is when I'm trying to create a todo item

#
    if form.validate_on_submit():
        new_todo = Todo(content=form.content.data, isCompleted=False)
        db.session.add(new_todo)
        db.session.commit()``` This is the code for adding tasks
vagrant adder
#

you gotta provide the author

#

since user_id is not nullable

hollow glacier
#

@vagrant adder Oh yeah

#

Do you know if flask_login has a good way to get the users id?

#

Isn't it something like current_user.id?

vagrant adder
#

yes

hollow glacier
#

@vagrant adder I get this error SyntaxError: positional argument follows keyword argument

#
db.session.add(new_todo)
db.session.commit()```
#

Nvm fixed it

#

I'm just dumb

vagrant adder
#

nice

brave otter
#

anyone know if it's possible to build Q objects dynamically in Django?

#

for example if I have a list of fields I want to OR together like Q(exchange='blah') | Q(exchange='otherblah'), but exchange is a string in a list?

#

nevermind - got a solution - thanks anyway!

modest garnet
#

Is anyone nice enough to help me out with some django? I'm attempting to add a simple dropdown select menu where I have a list of all the choices already. I'm having issues figuring out how I can put the menu on the page and how to retrieve the data from the field.

marsh canyon
#

Maybe model choice field?

modest garnet
#

yeah I'm trying to figure out how to use it

#

Anything I see online is either super basic or not what im trying to do

#

what im trying to do is make a dropdown menu, and then have a button that adds that selection into a list on the screen

#

@marsh canyon if you understand what I want to do could you send me a pm?

#

or anyone else

marsh canyon
#

Sure, i will look into it a bit, just woke up πŸ˜…

#

Drop down menu in html can be done using section

#

Or

#

Lemme do some research

modest garnet
#

thanks, im about to go to bed actually so could you pm me anything you have?

stiff totem
#

Hey guys, How do you guys manage PKCE authentication? especially in Django?

pseudo fjord
#

Strange issue, getting __init__() should return None, not 'coroutine' with the following:

class User(Object, UserMixin):

    _name = ''
    _id = ''

    async def __repr__(self):
        """
        Output:
            User('username', 'username@example.com')
        """
        return self.__class__.__name__ + '(\'{0}\', \'{1}\')'.format(
            self.username,
            self.email,
        )

    async def __init__(self, email, password, username, *args, **kwargs):
        self._id = username.casefold()
        # Mandatory
        self.email = email
        self.set_password(password)
        self.username = username
        # Optional
        if 'name' in kwargs:
            self._name = kwargs.pop('name')

    async def set_password(self, password):
        self.pass_hash = bcrypt.generate_password_hash(password)

    async def check_password(self, password):
        return await bcrypt.check_password_hash(self.pass_hash, password)

    @property
    async def id(self):
        return self._id

    @property
    async def name(self):
        return self._name

    @name.setter
    async def set_name(self, value):
        self._name = value
#

Any ideas why I'm getting this?

native root
#

You cannot have an async __init__

#

if you want the same kind of behavior, you must implement an async __new__

pseudo fjord
#

Alright, cheers buddy

hollow glacier
#

How do I set a default value for a WTForm?

hard moon
#

Hello here

#
import os

ENV = os.getenv('GLITCHYWARE_ENV', 'dev')

if ENV == 'dev':
    print('DEV')
    from .dev import *
elif ENV == 'prod':
    print('PROD')
    from .production import *
    
#

This is the content of an init.py file

#

It's supposed to get an environment variable and execute a file according to it.

#

But both files are executed.

#

It prints 'PROD' only, so it means that ENV == 'prod' and the first if is skipped, but for some reason it runs the code in dev.py

#

I'm using Wagtail a Django based CMS and deployed it on Heroku for information.

magic blade
#

looks kinda like .production imports .dev ?

hard moon
#

I solved it but

#

I cannot access my media files anymore.

modest garnet
#

I have a list of all objects and I want to just display a delete button that I can click that would delete that entry in the DB, I can't for the life of me figure out how to do this

marsh canyon
#

Still need help? @modest garnet

marsh canyon
#

u need to use a backend framework to do that :/

#

well u will be storing the data in a database

#

the user will make a post request which will be captured by a function

#

lemme link u to a resouce which can explain better

stiff totem
#

Hello, guys, how to implement oauth2 with pkce ???

pliant hound
#

Hey folks. I want to store product info in a database in my flask project

#

Using sqlite and flask-sqlalchemy, I've got a little Model set up:

class Products(db.Model):
    __tablename__ = 'products'
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String, nullable=False)
    overview = db.Column(db.Text)

    def __repr__(self):
        return f"Products('{self.title}')"
#

So if I wanted to store multiline paragraphs in that field, are there any caveats/best practices I need to know about?

vagrant adder
#

@hollow glacier
I'll show you when i get home

#

@pliant hound
Class name put in singular, and remove __tablename__, sqlalchemy does that for you by putting it in singular

pliant hound
#

Sorry- what do you mean by put it in singular @vagrant adder ?

vagrant adder
#

class Product(db.Model):

pliant hound
#

Oh. Right I see

#

But other than that, It should be smooth sailing?

#

I'll be able to store multiline strings in the overview?

vagrant adder
#

Yeah

pliant hound
#

Wicked. Thanks fella πŸ™‚

vagrant adder
#

πŸ‘Œ

#

Remove tablename @pliant hound

pliant hound
#

Will do

#

A book I'm reading sugested I define tablename because sometimes SQLAlchemy can get confused?

vagrant adder
#

Nope

#

Exactly different

#

Sqlalchemy shits itself when users fiddle with tablanames

pliant hound
#

Oh dang. Good to know

#

Thank you

vagrant adder
#

πŸ‘Œ

native tide
#

yo what do you guys think about DJango in comparison to ExpressJS?

#

is Django any better

#

honestly trying to get into Django so i can strengthen my python skills, a friend of mine told me a while ago he like Django better because it takes care of so many things for you

rigid laurel
#

Express is a poorly documented pain in the arse

#

Assuming you want to do a standard CRUD web app then Django is a pretty good choice IMO

native tide
#

@rigid laurel but what’s so good with Django though

rigid laurel
#

Well, if you want to do Python web development, you have two options: Flask, or Django

#

Flask is a more lightweight option where you have to pick and choose exactly what you want, whereas Django is opinionated and does a lot of things for you

#

the main difference being that Django has an ORM (Object relational mapper) built in for database stuff where Flask doesn't

vagrant adder
#

flask is like race car, you have to add some stuff to it

#

and django is like a lambo

rigid laurel
#

But, both options are vastly better than JS

vagrant adder
#

you get everything, comfort,speed

#

@native tide take a look at sails.js

native tide
#

why what about sailsjs should I know about

#

ima try out django later tho

#

I’m bored of express and JavaScript

marsh canyon
#

Js can be an advantage if ur also a front end dev? I maybe wrong

#

Btw can anyone explain what can a front end frame work do?

rigid laurel
#

JavaScript is necessary if you want to make a modern front end. But it isn't great for anything beyond basic backend stuff

marsh canyon
#

Isn't regular js enough for a modern website? What do these front-end frameworks like react add?

rigid laurel
#

A JavaScript framework is a way you can make a responsive application on the web. They generally handle the rendering of the actual HTML on the page rather than just letting the browser make a request, that way you can have the page change without refrsehing

marsh canyon
#

So like live searches before I hit the search button?

#

I mean i am typing in the search bar and the results appear as I type

rigid laurel
#

Yeah, thats one example

marsh canyon
#

Can't that be done in regular js?

rigid laurel
#

It can, but when you're doing a million similar asynchronous things then it becomes much easier to offload that work to a framework

native tide
#

Yes I know Angular already but I’m bored of node lol

marsh canyon
#

Okay, thanks for the info mate @rigid laurel :)

rigid laurel
#

Especially if you end up with complex state that you need to manage

marsh canyon
#

Oki

#

I have been wanting to learn JS from a long time but never really started, haha

#

Diving deeper into css

native tide
#

Did you check the docs on the library to see what those errors could be

#

Usually they have it listed

peak thicket
#

Sadly not.

native tide
#

Does the thing work if you try using it in a basic script file like without flask just the library

peak thicket
#

yes

peak thicket
#

Anybody know why this instantly closes?

from sanic import Sanic
from sanic.response import json
import asyncio

app = Sanic()

@app.route("/")
async def test(request):
    return json({"hello": "world"})

async def startServer():
    await app.create_server(host="0.0.0.0", port=8000)

def main():
    asyncio.Task(startServer())

if __name__ == "__main__":
    main()
native root
#

asyncio.Task()'s do not guarantee complete execution, you would need to have an event loop actively running to make sure it stayed alive long enough to be processed

misty dune
#

Can someone explain to me how to get Json stock data from IEX api?

supple loom
#

Hey

#

Can anyone help me with flask...i am working on an API and got stuck in authorisation endpoints

marsh canyon
#

ask your question and people will answer if they know it

supple loom
#

I created this test file but when i run test JSONDecodeError is showing up....shall i paste the code so you can see what's the error ?

vagrant adder
#

Yeah i'd like to see the code and full traceback

marsh canyon
#

I am having a little problem in my django project on implementing likes and dislikes for a post, kinda complicated to explain, so is djangoner free to voice chat?

vagrant adder
#

Not home :|

marsh canyon
#

oki

#

@ me if anyone can

native tide
#

I need to make an application that i can give in dimensions in pixels and then it makes a window with a coordinate system in it(2D) and then i can give in an x and y and it puts a dot on that point. how would i go about doing this. i have some knowledge in python so i would like to do this in python. anyone have any tips?

#

it would be an web app

snow willow
#

@native tide
As instructed in #help-<int> you can not make a web app in python.
Browsers do not suppot python language

native tide
#

django

#

is what i would want to use

supple loom
#

https://medium.com/free-code-camp/structuring-a-flask-restplus-web-service-for-production-builds-c2ec676de563 @vagrant adder this is the link pls take a look.... Everything works fine except two things first running test after creating file auth_test.py and logout operation in swagger documentation

Medium

In this guide I’ll show you a step by step approach for structuring a Flask RESTPlus web application for testing, development and…

snow willow
#

the way i see it is compute the dimensions in django based on request, and respond with the needed dimensions for js canvas

#

and make js render the graphics.

supple loom
#

Am i the only one using flask here?

native tide
#

so i would need to use js to make it?

snow willow
#

for web app yes

rigid laurel
#

The only thing Flask or Django can do is render static HTML/CSS

#

the use of them is to load data or logic from a server into that static page

#

but it doesn't change the page after it has been rendered

#

no matter what you will need JS if you want to change the page at all after it has been initially loaded

native tide
#

guess il have to learn js then

snow willow
#

REST API

rigid laurel
#

adding Django or Flask into the mix is pretty pointless

snow willow
#

and some form of REST for Django or Flask.
Backend here is not that important

supple loom
#

What is a good language to make front end for APIs developed using flask?

rigid laurel
#

the REST api adds no value to Hydrovo's problem

#

ReactJS, VueJS are two highly reccomended front end libraries

snow willow
#

if you want to store the values??

supple loom
#

Cool

rigid laurel
#

nowhere has he mentioned that he wants to do that

#

and even if he did want to store the values

snow willow
#

you can send them from frontend

rigid laurel
#

it makes more sense to write hte javascript first

supple loom
#

Can anyone look into my problem?

rigid laurel
#

ReactJS, VueJS are two highly reccomended front end libraries

supple loom
#

Not that...the link above it

snow willow
#

@native tide
JS create app first and then you can decide latter if you need a backend or not

rigid laurel
#

what is the actual problem @supple loom?

supple loom
#

And i play dota too 😍😍

#

when i run auth_test.py file it raises JSONDecodeError

rigid laurel
#

are you just using the code verbatim from the github repository?

supple loom
#

Well i did some extra....but i am sure i didn't modified that part and it should work

#

The link doesn't tells to run tests...but since i added i naturally ran to check whether it's working or not

#

There is one more problem i mentioned above

#

The logout endpoint.....login is working fine...
But logout says please provide a valid authentication token

#

Say something

#

Check the link once

rigid laurel
#

I'm afraid I'm not willing to install this random repository to see where the problem might be

#

and I can't really help just by looking at this code

supple loom
#

Yeah...one needs to run to see what is actually happening

#

And i am sure you will run through the same error

#

I have posted screenshots in the issue section of same github repo

#

The link i send is just an article in which he has taught

mint shuttle
#

so i have a django backend and django templates being served with csrf tokens in the POST forms to add models.

but i've made a vue frontend that queries the GET endpoint (only one in my app) and i'd like to add functionality to create records with it as well, but if i try to make a form, i get the error at not having a csrf token or whatever. what's the 'proper' way to do this?

supple loom
#

Mention me if anyone checks on mine...thanks

snow willow
#

@mint shuttle
On your POST method from VueJS you need to send the CSRF token along with POST data.
I have not done this in a long time but i can search for a proper method in my archive

#

CSRF is in the cookies

mint shuttle
#

ok that makes sense, how do i get the csrf token? for my situation should i just disable that protection? (it's just an example thing, i don't have any sort of user authentification, and i just assume that everyone in the world has the same data to keep track of/there's only one person?)

snow willow
#
    url : 'YOUR_URL_HERE',
    headers: {'X-CSRFToken': $.cookie('csrftoken')},
    type: 'POST',
    dataType: 'json',
    data: {}
#

if the token is not there you need to create a method to retrieve it from django

#

i do not know how you setup vue to work with django

#

best way to find out is to load the index page and check it with browser developer tools if you have that cookie

mint shuttle
#

ok, ty for the info! i think that'll be enough for me to have direction with my searches now (i was just getting a bunch of stuff on what csrf protects against and stuff, not practical stuff)

right now it's not really. i'm just using axios to send http requests

snow willow
#

you are wellcome

mint shuttle
#

although i think... it might be bed time right now lol have a good night!

snow willow
#

πŸ™‚ i am 15:13 here

#

different time zone.
good night

supple loom
#

Night

fossil swift
#

Within Flask is it possible to make something happen without editing every single route? So I can add a suspend function to user without adding a statement on all my routes.

rigid laurel
#

Before request I think is something that can do that

elder nebula
#

Do you know any Rich Text Editors for Django, that can be used for free commercially and dont have to pay for licence?

#

Oh, I found it

#
You can modify, integrate and use the Open Source CKEditor 4 and the Open Source CKEditor 5 in your commercial websites and products for free as long as our source code and your modifications remain open and accessible to others under the same Open Source license terms.

native root
#

I have used tinyMCE, and CKEditor 4 and 5

#

MCE is alright and functional. CKEditor is better, in my opinion, but be wary that they have significantly changed things in ckeditor5 so that it no longer supports html source view

elder nebula
#

in CKeditor 4, we could write harmful html source code, could that be the problem

#

Well if it goes to customer, he doesn't need html view

native root
#

Whether harmful html makes it through your editor onto your templates is a template design problem. My use cases required HTML input, however, so that was not an option

#

Django automatically escapes out html tags, unless you mark it with |safe, which disables auto-escaping

elder nebula
#

I didnt use CKeditor for the reason that someone could make alerts, I only used it if it was behind password

#

Yeah

#

|safe is a must, otherwise it shows html tags too

#

Well, I think its allowed to use CKeditor 5 on commercial websites

#

I sent them email just to confirm

native root
#

If you want to use user-edited html-based code on your site, I'd point you towards https://github.com/marksweb/django-bleach

#

Which you can use and configure instead of django-safe, to only allow some tags

#
CKEditor 4 is distributed under three copyleft Open Source license options: GPL, LGPL and MPL.

CKEditor 5 is distributed under a GPL 2+ copyleft license.
#

It links to the GPL3, so I would suggest not using it for a commercial program in my limited experience, or at least discussing it with someone who is knowledgeable about licensing

peak thicket
#

Anybody know how to get user input into forms using Sanic? Here is the code I currently have in the main py file;

@app.route('/data', methods=['POST'])
def handle_data(request):
    cid = request.form['cid']
    print('cid')

And here is the html:

<form method="POST">
    <input type="text" name="cid" placeholder="CID" action="/data">
</form>

But whenever I send the user input, the page in my browser then says; Error: Method POST not allowed for URL / & in console I receive the error:

[2019-10-02 16:58:21 +0100] [17566] [ERROR] Exception occurred while handling uri: 'http://localhost:8000/'
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/sanic/app.py", line 920, in handle_request
    handler, args, kwargs, uri = self.router.get(request)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/sanic/router.py", line 407, in get
    return self._get(request.path, request.method, "")
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/sanic/router.py", line 447, in _get
    raise method_not_supported
sanic.exceptions.MethodNotSupported: Method POST not allowed for URL /
[2019-10-02 16:58:21 +0100] - (sanic.access)[INFO][127.0.0.1:50035]: POST http://localhost:8000/  405 40
native root
#

@peak thicket action is set on the <form tag, not the inputs

peak thicket
#

Thanks but now I get:

[2019-10-02 17:07:58 +0100] [40530] [ERROR] Exception occurred while handling uri: 'http://localhost:8000/data'
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/sanic/server.py", line 442, in write_response
    response.output(
AttributeError: 'NoneType' object has no attribute 'output'
[2019-10-02 17:07:58 +0100] - (sanic.access)[INFO][127.0.0.1:50162]: POST http://localhost:8000/data  500 28
native root
#

that's an error in your server code somewhere, you haven't shared it so I don't know what's wrong

#

That specific error I believe is that you are not returning a response from your code, so perhaps that function needs to return an httpresponse

peak thicket
#
from sanic import Sanic, response, request
from sanic.response import json
import fortnitepy

app = Sanic()
cid = ""

@app.route('/')
async def handle_request(request):
    print('/')
    return await response.file('buttonclicker.html')

@app.route('/data', methods=['POST'])
def handle_data(request):
    cid = request.form['cid']
    print('cid')

@app.route('/skin')
async def handle_request(request):
    await skullTrooper()
    return await response.file('buttonclicked.html')

#if __name__ == "__main__":
#    app.run(host="0.0.0.0", port=8000, debug=True)

client = fortnitepy.Client(
    email='',
    password='',
    net_cl=''
)

@client.event
async def event_ready():
    print('----------------')
    print('Client ready as')
    print(client.user.display_name)
    print(client.user.id)
    print('----------------')
    await app.create_server(host="0.0.0.0", port=8000, return_asyncio_server=True, debug=True)

client.run()
native root
#

Yes, you need a return response.etc for your post too, since when the browser submits the form it uses the response from the post request as the html to display

peak thicket
#

Thanks!

peak thicket
#

It works but /data never loads, it just says waiting for localhost and load forever.

#

Stopping me from doing anything on the website like click links as well.

#

Nevermind after like 5 minutes it says: Error: Response Timeout.

peak thicket
#

Fixed it by exiting debug mode.

dense slate
#

@elder nebula I really love Sublime Text

#

I dunno if that's considered rich, though.

magic blade
#

something i've never seen in a django project that just came up -- test data is being written to the live (well, dev, so, it's kind of ok?? but still) database.

#

database test_appname is empty, but database appname has a bunch of extra rows with data from factory_boy (using --keepdb to make it easier to inspect what's happening)

#

if i run tests for an app without --keepdb, and connect to test_appname via psql, it cannot delete the test database, but it still has not written anything to the test database.

#

new rows have appeared in the "live" db instead

peak thicket
#

How tf do I make a button be stuck to the right side of the page?

#

I've tried float right & pull right but neither work?

#

Don't use weebly.

#

Use herokuapp.

#

I think the websites run 24/7?

frigid egret
#

Hi all

#

Can someone help me with my training Django project?
Somehow I have to reactivate my venv every time I launch pyCharm, and even after that, when I run commands in shell, it tells me that I have to specify environment settings. Despite website and all of its functions working fine.

#

I've been working on it for several months now and not sure how I managed to break it tbh.

vagrant adder
#

@peak thicket
Free tier at heroku goes to sleep after 30mins of inactivity

supple loom
#

I need to know what all APIs i need to create to make a basic movie ticket booking system.

elder nebula
#

@dense slate We talked about HTML rich text editors, Not code editors

opal radish
#

I am using flask, and I wish to redirect to a URL and pass along URL params or other vars using redirect. How could I do that?

opal radish
#

I've seen it before im pretty sure i just cant remember where

vagrant adder
#

return redirect(url_for('some_func', form=SomeForm(),name=some_name))

vagrant adder
#

@opal radish ^^

native tide
#

Hello

frigid egret
#

Hi

vagrant adder
#

Alexa what's the weather like

fierce hare
#

How can I add sanic to an already existing loop?

marsh canyon
#

hey guys, i have a django project, its a social media site where users can post stuff. I also have likes for a post. A user can like a post which is from other users. So when i click on like button, the page refreshs and goes back to starting. I dont know js yet but it will be cool if anyone could give me a code snippet which i could use for not refreshing the page when someone clicks on the like button

#

u can make a PR to my django repo if u want to

rigid laurel
#

do you have the endpoint set up in Django to handle the AJAX yet?

marsh canyon
#

i guess not, not sure how AJAX works πŸ˜…

rigid laurel
#

So what you want is a button on the webpage that the user clicks that will do something with Django models to say that X post has been liked by Y user?

#

and the button doesn't refresh the page

marsh canyon
#

the button is functional and like feature is all working, the only problem is the page refreshs and goes to the top

#

kinda yea, on clicking the button, page should not refresh

#

kinda like a instant update?

rigid laurel
#

where is the code that handles the like currently?

#

the view and template for it

marsh canyon
#

in posts app

#

there are 2 templates

#

detail-post.html

#

display-posts.html

#

and u can see the view in views.py , should be the last one i believe

#

so depending on the user if he/she has liked the post, i change the icon, like solid thumbs up if likes and outline if not liked

rigid laurel
#

I'm not familiar enough with Django - def like_view(request, slug, destination): does that handle a get, post, or any request?

marsh canyon
#

get

#

it handles when someone clicks the button, the button is basically <a> tag, which goes to an endpoint handled by like_view which again redirects the user to the same page making it refresh

rigid laurel
#

I'm not sure on the correct way to do AJAX with Django is the thing. But from the JavaScript side its relatively simple.

what you want is a new view, or just rewrite like_view that returns a JSON instead of HTML. Then the JavaScript will make the AJAX request, which can be almost as simple as fetch('http://your-domain/like_view');, and make any necessary visual updates to the page

marsh canyon
#

i dont seem to understand, lol

#

maybe u can PR to it?

#

easy hacktoberfest PR too

rigid laurel
#

I'm not familiar enough with Django to know the correct way

marsh canyon
#

ohk

rigid laurel
#

and the JS kinda depends on the specifics of teh Django

marsh canyon
#

oh

rigid laurel
#

but someone who knows Django can probably explain it better than me. The actual JS side of this problem should be relatively minimal though

marsh canyon
#

okay

#

thanks!

primal drift
#

is there any models field that I can use to only get number but it can start with 0

#

because when i use IntegerField it keeps removing the first 0 which something that I need it to be shown

#

Django

native root
#

If Iceman is still looking, or someone else is trying to figure out how to do this

#

You bind an event handler to your "like" link, that sends an ajax request to your server. It may first increase the vote count, or it might wait for a response before increasing it or setting it to the new number (if it has changed server side since then). Jquery has some methods that make this easy, $.ajax(some_things). You generally have an endpoint defined for this, something like yoursite.com/post/like, and you do a POST ajax request from there. On the django side, you hook up the view to the post request, making sure that the post ID and other details you need (like authentication) are in place, which you should have already from setting up the precursors

#

The view would take the post request and handle "liking", and return a reply depending on what you want to do in the javascript (a JSON response with the new number of likes is an option that many use). The javascript then parses the response from the ajax request and updates the button

marsh canyon
#

@native root I dunno how to send Ajax request :/

#

I'm noob in js

vagrant adder
#

It'very easy

marsh canyon
#

Can u PR plz

floral seal
#

Hello, is there any way to manage user permissions in DRF?
I have a ModelViewSet of a Task model, and I would like it so only the user associated with the model can DELETE, GET, PUT or PATCH it, while any authenticated user would be able POST on the view.

native root
#

Change the a href=url to a data parameter, and using jquery, you'd want the template to look something like this:

<a data-like="{% post.slug %}" ...>
$(document).ready(function(){
    $("[data-like]").click(function(event){
$.getJSON('/like-this-url', { like-item: $(this).attr("data-like") }, function(data) {
    $("span.count", this).text(data['count']);
});
    });
});
#

Then you set up a view at /like-this-url, which takes a GET request with a parameter of like-item, does the "like", and returns a json result that includes an object with "count" equal to the new count

#

I don't actually have the spare time to fully tie it in, but that should be enough to get you where it ought to be workable

#

If you want it to be a post request you can adjust it to use this instead, which should just be a code rearrange:
(shamelessly stolen from stackoverflow https://stackoverflow.com/questions/8951810/how-to-parse-json-data-with-jquery-javascript )

$.ajax({ 
    type: 'GET', 
    url: 'http://example/functions.php', 
    data: { get_param: 'value' }, 
    dataType: 'json',
    success: function (data) { 
        $.each(data, function(index, element) {
            $('body').append($('<div>', {
                text: element.name
            }));
        });
    }
});
#

If you're looking for a more structured approach, you'd end up giving each of your "post"'s their own divs, which would then allow you to operate on them by id, which is the usual and easiest way of going about it

#

$() accepts css selectors, $(this) is the current element (in our case, the one being clicked), and if you do $("selector", this) you search under the current element

#

.text() changes the text

supple loom
#

Hey ....how do i use column of one table in function of another table ....in sqlalchemy ?

fierce hare
native tide
#

Hello

native tide
#

hi

#

help pointed me here

#

Can someone help me with django and gunicorn?
i am using 18.04 ubuntu on aws ec2 instance
following this tutorial https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-18-04#creating-systemd-socket-and-service-files-for-gunicorn
DigitalOcean
How To Set Up Django with Postgres, Nginx, and Gunicorn on Ubuntu ...

i am stuck on gunicorn
pastebin coming
https://pastebin.com/8esEr4wa
Pastebin
ubuntu@ip-172-31-43-53:~/myprojectdir$ sudo systemctl status gunic...

gunicorn[11094]: ModuleNotFoundError: No module named 'website.wsgi'
i mean module exist why gunicorn cant find it
?
with
(env) ubuntu@ip-172-31-43-53:~/myprojectdir/website$ gunicorn --bind 0.0.0.0:8000 website.wsgi:application [2019-10-05 00:41:52 +0000] [11150] [INFO] Starting gunicorn 19.9.0 [2019-10-05 00:41:52 +0000] [11150] [INFO] Listening at: http://0.0.0.0:8000 (11150) [2019-10-05 00:41:52 +0000] [11150] [INFO] Using worker: sync [2019-10-05 00:41:52 +0000] [11153] [INFO] Booting worker with pid: 11153
works fine
here is my gunicorn config file

DigitalOcean

Django is a powerful web framework that can help you get your Python application or website off the ground. Django includes a simplified development server for testing your code locally, but for anything even slightly production related, a more secure

frigid egret
#

Hello, people of the internet

#

Can someone please help me understand json requests? I feel really dumb but I for some reason I can't even find a proper tutorial on google.

#

For example, rn I'm trying to find how to add headers and all I can find are either specific API documentations for google and atlassian, or SO threads with errors.

#

While I'm trying to find general information on how to do it.

haughty haven
#

requests.get("https://google.com", headers={"User-Agent": "ME"})

frigid egret
#

Ok, thanks

#

But can you perhaps recommend a tutorial or article on how to json?

#

Also, since i'm working with Django, I get ALOT of rest framework info that I don't need rn.

haughty haven
#

JSON or web requests?

#

JSON is just a data format

frigid egret
#

requests with json. In particular, sending api requests to third parties

#

I guess requests then

haughty haven
#

This seems like a decent general introduction

#

it is python specific though

#

(REST requests are language agnostic)

frigid egret
#

As long as it's a general guide and not related to a specific API or rest framework

#

Since I want to understand the concept first, before moving on to rest

haughty haven
#

REST is the concept though...?

frigid egret
#

But that's a framework...

haughty haven
#

REST is not a framework

frigid egret
#

Essplane pls?

haughty haven
#

REST is a concept of represeting methods of getting, modifying and deleting data

#

it is implementationless

#

The guide I linked above does a decent job of at least introducing the concepts of what REST requests are when appropriate

frigid egret
#

Ok, I'll read it

native root
#

@native tide I believe your issue is that your wsgi file is in /project/project/wsgi.py, and gunicorn is being told to look under project/wsgi.py. Your manual run starts in myprojectdir/website, not myprojectdir. Also, you didn't actually post the gunicorn config file, so I can't confirm that suspicion.

#

I just say your #help-orange post, pretty sure what I said is correct

#

Also, for some reason, your lines have 183 spaces at the end

frigid egret
#

Hi all again

#

I have another question regarding Django.

#

I have a webpage with a form. Upon submit, it sends form data to the db, and also when pressed, js opens a "thank you" modal window. There's a method that checks submitted form and I'd like to return the result into that modal window, essentially to js so it can print it in that modal window.

#

How do I approach this task?

#

I assume I should do it with json, but that's just a guess, so I'm asking here.

native tide
#

Hello I have question, how do I connect React.JS and Flask in my project ?

#

I am creating a simple To Do App

vagrant adder
#

well, you have to run your api and frontend processes separately and figure out how to make requests with js

native tide
#

oh alright, so I create web UI and HTML shit with React JS and Flask is there for DB connection and handling logic for API ?

#

@vagrant adder

vagrant adder
#

well, you can integrate both react and flask into one server just like one of my classmates did

native tide
#

one server ?

#

wdym by one server ?

#

Just like start Flask or you need React and Flask working at same time ?

vagrant adder
#

yeah

#

that's what he did

native tide
#

@native root Thank you for answer, ill was afk and managed to solve it myself, problem was "working file" part of gunicorn configuration!
Thank you mate

native tide
#

Allo

#

So I'm making a flask app

#

and it includes some modules that "do a thing", for instance there is a module that text to speeches a lump of text to an MP3, and there is another module that converts e-books into a bunch of snippets for text to speeching

#

what should I be calling these 'modules that do stuff'. I feel like they should go in a folder in my project structure

#

I was thinking that the folder could be called 'services'

#

but that's probably not right...

#

usually the folders are named after a design pattern. What is a design patterny name for 'classes with a specific responsiblity'

#

I'm feeling like the correct answer might be 'your libaries that do stuff should be in their own repos, so the flask app can just be a flask app, install, import and use them'

native root
#

My opnion, services is just fine. Since that is what they are, services provided by your flask app. Separate repos is probably overkill for them--they aren't going to change rapidly, and are probably not big enough to be worth the management hassle

#

There is a balance to be struck between complexity and modularity. One end leads you to massive files, slow processing times, spaghetti code, and unmanageable branching and merging. Too far towards modularity and python begins to look and act like Java-tons and tons of boilerplate, modules that do nothing but import other modules and call singular functions

#

The reality is, if you go too far either way maintainability begins to drop

native tide
#

thanks, sometimes it's nice to have permission from the internet to call things stuff

#

I ended up trying to fix a firefox pluggin that was written as one of these... apps with classes implimented as one big file full of functions that do stuff

#

and it's much worse than I remembered

#

by slicing things up, you hopefully end up with really small scopes and not many variables in them. I think this, horrible lump of javascript I was staring at would have seemed normal back in the day, but having got used to "functions only use variables that turn up as parameters, no global variables"

native root
#

There is an optimal amount of complexity that ought to be shown on screen and considered at once. You can spread it out via classes, and abstractions, and you can bring it together with long procedural functions with variables

native tide
#

turns out a variable that belongs to a class is really just a global if your class is big enough

native root
#

yep

#

Gl!

vagrant adder
#

@native tide i agree with bast, i'll call them services

#

but don't isolate them from your flask app tree

fossil swift
#

using blueprints

vagrant adder
#

Yes

#

But instead of main, use init.py

raw oxide
#

is there a quick guide to django? I checked pinned messages dont see one

marsh canyon
#

U can check out YouTube tutorials like Corey, freecodecamp, coding entrepreneurs

raw oxide
#

Will do, thanks

supple loom
#

Someone help me with models in sqlalchemy pls

#

I made a model in which i created three tables

#

I am having problems in creating relationship and putting data in those models

native root
#

What kinds of problems, and what kinds of relationships?

supple loom
#

Should i post code here ?

lavish prismBOT
#

:incoming_envelope: :ok_hand: muted @supple loom until 2019-10-06 06:58.

tacit grove
#

!unmute 449446855491846145

lavish prismBOT
#

:incoming_envelope: :ok_hand: Un-muted @supple loom.

tacit grove
#

you got muted by our spam filter for attachments

#

for long pieces of code, please use

#

!paste

lavish prismBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

tacit grove
#

^ that website

supple loom
#

Ohh

#

Sorry

#

And thanks

#

this is the model code

#

and this is the service code

#

i am trying to achieve one to many relationship on two level

opal radish
#

Does anyone have any idea as to why my flask session variable is being reset in between requests?

#

I modify it, print it at the end of the request and see the difference, however at the start of the next request it has reverted

opal radish
#

Looks like I had to set session.modified - True

fossil swift
#

Can anybody help with Flask blueprints?

#

Currently getting an error AttributeError: module 'blueprints.general.login' has no attribute 'name'

supple loom
#

post the code

fossil swift
#

app.register_blueprint(login)

from flask import Blueprint, render_template

login = Blueprint('login', __name__)


@login.route("/login")
def login_func():
    return render_template('login.html')```
supple loom
#

i haven't worked with blueprints sorry

#

try .......app.register_blueprint(Blueprint)

flat elk
#

@fossil swift how does ur folder structure look like?

lapis heron
#

hi guys, Im reading book TDD with Python and got to the chapter 16 where the author recommends Javascript: the good parts book for complete beginners in JS. It's from 2008, but the recommendation was written in 2015. Is it still not outdated?

fossil swift
#

@flat elk

vagrant adder
#

get them out and rename init.py to __init__.py

lapis stump
#

is there much benefit to using libraries like flask-bootstrap as opposed to just setting up the static imports manually?

vagrant adder
#

not really

#

you can shave few miliseconds off loading webpage

lapis stump
#

cool

#

because flask-bootstrap does caching as well?

vagrant adder
#

yeah

#

i would rather link it on frontend since those miliseconds aren't noticeable

#

and flask-bootstrap just adds complexity on the backend part

raw oxide
#

Is there any benefits for using Flask or Django besides Flask is easier to learn?

vagrant adder
#

easier on resources(not something you should twist your head for)

#

flask's ease of use is just something django can't beat

#

it's modularity is good too

lapis stump
#

if my goal in using flask is to just quickly throw up webui's for some python code I'm running in the background (in other words, personal tooling and not public web facing)

#

any relevant libraries I should take note of?

rigid laurel
#

Depending on how usable you want the UI to be, probably a lot of JS stuff you should be aware of like possibly ReactJS or Jquery

raw oxide
#

Can't escape the JS 😒

lapis stump
#

blargh

native tide
#

Hello guys

#

How do i serve dynamic files?

#

In a popup

mint shuttle
#

so i have a table to keep track of a many to many relationship between two other tables, all using django to form the modles.

I have a modelform that lets you make the assignments to populate this table with the proper relationships

but currently it uses a drop down and shows modelobject(n) instead of something like the object's name. but I'm not finding the right search term to have this expose model.name instead of model.id. any ideas?

mint shuttle
#

i feel dumb, i just had to implement str

tall plaza
#

hi everyone

#

hi evryone
any one using django
btw i am trying to deploy django web app on heroku
but there is error
when i try to push on heroku master

#
weather_app) C:\Users\Deepak\Desktop\weather>git push heroku master
Enumerating objects: 174, done.
Counting objects: 100% (174/174), done.
Delta compression using up to 4 threads
Compressing objects: 100% (170/170), done.
Writing objects: 100% (174/174), 574.03 KiB | 2.02 MiB/s, done.   
Total 174 (delta 40), reused 0 (delta 0)
remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz
remote:        More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure
remote:
remote:  !     Push failed
remote: Verifying deploy...
remote:
remote: !       Push rejected to deepweather.
remote:
To https://git.heroku.com/deepweather.git
 ! [remote rejected] master -> master (pre-receive hook declined) 
error: failed to push some refs to 'https://git.heroku.com/deepweather.git' ```
#

please help me

native root
#

A requirements.txt must be present at the root of your application's repository to deploy.
To specify your python version, you also need a runtime.txt file - unless you are using the default Python runtime version.

#

That's the error message you get when you forget to specify requirements.txt

tall plaza
#

now i am getting

#

something different problem

#

when i try to run app on heroku i am getting ```
2019-10-07T08:26:19+00:00 app[api]: Build succeeded
2019-10-07T08:26:32.789867+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=deepweather.herokuapp.com request_id=2d66b796-1c62-411b-a10b-47ff03436c08
fwd="42.109.196.154" dyno= connect= service= status=503 bytes= protocol=https````

native root
#

Use a Procfile, a text file in the root directory of your application, to explicitly declare what command should be executed to start your app.

#

Currently you aren't, so it's not running any applications, and thus you get that error

primal drift
#

hey guys, I just change all my hardcode link on html into django url {% url 'homepage' %} ...The thing is how to navigate with django url that works just like http://127.0.0.1:8000/#hotel-container

supple loom
#

hey guys ....i am getting data in list of registered users while nothing in list of registered theatres

#

this is swagger documentation

elder nebula
#

@primal drift i am really beginner, but have you tried {% url 'home' %}#hotel-container

supple loom
#

i registered user and it's data shows in list of registered users....the same way i registered theatre but the data is null in the latter case

elder nebula
#

@supple loom What are you using, Django or Flask?

supple loom
#

flask bro

#

i structured both the same way but i don't understand why there is no data

hybrid citrus
#

Side note: screenshots are awesome

supple loom
#

sorry.....they are downloaded from whatsapp actually

frigid egret
#

Hi all

#

I have some weird problem with launching my website. It works fine except it won't update html content after git pull

#

I have restarted the server itself, nginx and gunicorn and checked that files are actually new. And it still shows the old version.

#

Can someone help me find what I 'm missing please?

native root
#

If you have not done a full refresh, it's likely the browser is caching the old files

#

On desktops, control-shift-r, or shift-f5, of cmd-shift-r triggers a cache-refreshing reload

#

On mobile, you'll generally have to go into the browser settings and erase the cache

frigid egret
#

Refreshing with cache, it became a habit once I got into web development XD

#

Also tried in another browser

#

@native root

native root
#

Do you have cloudflare between you and the app?

frigid egret
#

nope

native root
#

What are the headers you're getting from the server?

#

You can find those in a network tab of some dev tool in the browser

frigid egret
#

Hm.... where exactly? can't see them

#

can you make a screenshot? I'm using FF and Chrome

native root
#

This is firefox

#

Dev tools -> network tab -> click a non-updating item

frigid egret
#

ok

#

What should I look for in headers?

#

Or should I post them here?

native root
#

posting them here would be nice

#

date, last modified, and cache-control headers

frigid egret
#

response:

HTTP/1.1 200 OK
Server: nginx/1.14.0 (Ubuntu)
Date: Tue, 08 Oct 2019 03:26:17 GMT
Content-Type: text/html; charset=utf-8
Transfer-Encoding: chunked
Connection: keep-alive
X-Frame-Options: SAMEORIGIN
Vary: Accept-Language, Cookie
Content-Language: ru
Content-Encoding: gzip
#

request:

Host: 93.85.88.35
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:69.0) Gecko/20100101 Firefox/69.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,ru;q=0.8,ru-RU;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
DNT: 1
Connection: keep-alive
Upgrade-Insecure-Requests: 1
Pragma: no-cache
Cache-Control: no-cache
native root
#

odd

#

Well, I think with that we can probably rule out a user-facing cache

#

Which means that nginx probably is serving up the old files

#

the question is why

#

Something up with your nginx.conf, maybe?

frigid egret
#

Hm... idk. last time I checked everything was fine. And I have actually been updating code with git pull before.

native root
#

How did you restart gunicorn?

#

kill -HUP?

frigid egret
#

systemctl restart gunicorn

#

also

#

service gunicorn restart

#

just in case

native root
#

What's the systemctl status of gunicorn?

frigid egret
#

stete: running

#

copy the whole thing?

native root
#

The question is whether the restart of gunicorn failed, which could leave it running the older versipon

#

That would put errors in the logs if it's configured correctly

frigid egret
#

probably

#

but it says running since today

native root
#

hm

frigid egret
#

and failed: 0

#

I did restart the whole machine after all

#

and after that I had to restart gunicorn anyway. didn't set it up for auto launch

native root
#

gotcha

#

are you sure it git pulled to the proper new commit?

frigid egret
#

yes, I've checked a couple files with nano

#

html in particular

native root
#

hm.

#

So, on disk, the file is correct, but when served to the browser, it is not?

frigid egret
#

uh... how do I quit status?

native root
#

control-c?

frigid egret
#

oh, right

#

Yes, on disk files are updated

#

lemme double check

supple loom
#

@native root can you please take a look at my issue

frigid egret
#

Oh no wait... now I have old files

native root
#

Yay we found the problem !

frigid egret
#

apparently project did't get updated for some reason, even though it's been raising migration error when I tried to launch it earlier without migrating

#

That's weird

native root
#

@supple loom post your current code for the result fetch?

supple loom
native root
#

odd

supple loom
#

the code is Theatre.query.all()

#

that's all

native root
#

And how did you add them?

supple loom
#

lemme show u

frigid egret
#

Just to be clear, I have to activate venv, then git pull, then run migrate and collectstatic, right?

supple loom
#

def get_all_theatres():
return Theatre.query.all()

#

def get_all_users():
return EndUser.query.all()

#

both in different files

#

in their respective service

#

but the data is null

#

in theatre

#

i will try one thing

#

will ask u if that doesn't works

native root
#

Make sure you've run makemigrations or are committing your migrations too

#

Those requests seem fine, what's the code you're using to create the theatre and user objects?

supple loom
#

def save_new_theatre(data):
theatre = Theatre.query.filter_by(name=data['name'])
if not theatre:
new_theatre = Theatre(
public_id=str(uuid.uuid4()),
name=data['name'],
description=data['description'],
base_price=data['base_price']
)
save_changes(new_theatre)
response_object = {
'status': 'success',
'message': 'theatre successfully saved ',
}
return response_object, 201
else:
response_object = {
'status': 'fail',
'message': 'theatre already exists.',
}
return response_object, 409

#

def save_new_user(data):
user = EndUser.query.filter_by(email=data['email']).first()
if not user:
new_user = EndUser(
public_id=str(uuid.uuid4()),
email=data['email'],
username=data['username'],
password=data['password'],
registered_on=datetime.datetime.utcnow()
)
save_changes(new_user)
return generate_token(new_user)

else:
    response_object = {
        'status': 'fail',
        'message': 'User already exists. Please Log in.',
    }
    return response_object, 409

def generate_token(user):
try:
# generate the auth token
auth_token = user.encode_auth_token(user.id)
response_object = {
'status': 'success',
'message': 'Successfully registered.',
'Authorization': auth_token.decode()
}
return response_object, 201
except Exception as e:
response_object = {
'status': 'fail',
'message': 'Some error occurred. Please try again.'
}
return response_object, 401

#

have used token base authorisation in user

native root
#

You're missing .first() in the theatre code

supple loom
#

still null

native root
#

theatre = Theatre.query.filter_by(name=data['name'])
vs
user = EndUser.query.filter_by(email=data['email']).first()

supple loom
#

did that

native root
#

You've run the creation code again, to populate the db?

supple loom
#

no wait

#

yeah cool

#

that worked

#

thanks man

native root
#

πŸ‘

#

What happened is a query object is probably not falsy, so not query was always returning false, and therefore never adding anything to the database

supple loom
#

ohhh

#

i thought it added

supple loom
#

what does error means....."message": "Failed to decode JSON object: Expecting value: line 5 column 17 (char 73)"...

supple loom
#

https://paste.pydis.com/ocinezezoq.py this is my database model ...........if it's allright then i want to add the primary key of theatre into it's data which displays in list of theatres.....how can i do that?

native tide
#

I started a graphic design and web development studio and we are looking to expand our logo, identity, and web design portfolio. If anyone you know needs any creative services, we would always appreciate a referral! Check out our website at https://sleepycloud.me Thanks! UwU

#

mhm, so this is a commercial service?

vagrant adder
#

Guessing no

#

UwU

supple loom
#

@bpi.route('/<public_id>')
@bpi.param('public_id', 'The audi identifier')
@bpi.response(404, 'audi not found.')

class Audi(Resource):
@bpi.doc('get an Audi')
@bpi.marshal_with(_audi)
def get(self, public_id):
"""get an audi given its identifier"""
audi = get_an_audi(public_id)
if not audi:
api.abort(404)
else:
return audi

@bpi.route('/theatre_id')
@bpi.param('theatre_id', 'The theatre id')
@bpi.response(404, 'audi not found.')

class AudiT(Resource):
@bpi.doc('get an Audi in a theatre ')
@bpi.marshal_with(_audi)
def get(self, theatre_id):
"""get an audi given its theatre id"""
audi = get_audi_theatre(theatre_id)
if not audi:
api.abort(404)
else:
return audi

#

same function but i get this error (TypeError: get() missing 1 required positional argument: 'theatre_id') in Audit function

#

AudiT class

#

can someone tell why?

patent cobalt
#

You are not capturing the theatre_id, but adding the word theatre_id as the actual route/url:

@bpi.route('/theatre_id')
vs
@bpi.route('/<theatre_id>')
#

I think that's it

#

I'm not sure what you're using, though, but that looks different

supple loom
#

"message": "The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again. You have requested this URI [/Audi/1] but did you mean /Audi/<theatre_id> ?"

#

i did what u said

#

now it's this error

#

idk where i have requested this URI [/Audi/1]

patent cobalt
#

Wild guess, but you may need to have two different endpoints, one for the top function /<id> and one for the lower function /audit/<id> (or something), since otherwise it can not differentiate.

supple loom
#

ohh

#

cool thanks

#

that worked

patent cobalt
#

nice. which package are you using? I don't recognize it

supple loom
#

it's flask

#

restplus api

patent cobalt
#

right, I was just thinking that.. I've never really used flask and only ever used the @app.route standard form

supple loom
#

ohh

#

i am also new to this

#

my first project..so having a lot of dificulties

lofty matrix
#

With Django, I frequently have models with FileFields or ImageFields. When the model is deleted, the files are not deleted automatically. This means that for each model, I need to listen for the post_delete signal, and iterate over the files and delete them from the storage backend. This results in a bunch of the same function, but with different fields and listening for different senders, which is easy to forget to update if I change something. Is there a better way to handle this which would attach the logic to the model itself?

lofty matrix
mint shuttle
#

with django:
I have a model for items(cyphers) and a model for decks (lists of cyphers) its a many to many relationship.
I have DeckCypher which assigns cypher and deck ids.
I'm trying to write code that will generate a json object where the key is the deck name, and the object is the cypher. I have

data = {}
        for k, v in DeckCypher.objects.all().select_related():
            if k.name not in data.keys():
                data[k] = []
            data[k].append(v)
        json_data = json.dumps(data)
        return Response(json_data)```
but it doesn't know how to unpack model.objects.all().select_related() and I don't know how to perform the join operation later if I wanted to just track the ids for the loop. Any suggestions?
native root
#

Is your goal to select all pairs of decks and cyphers @mint shuttle ?

#

You can get a selection of Decks and all their component cyphers via Decks.objects.prefetch_related('ciphers').all(), with filtering wherever you'd want

#

If you can have duplicates, .distinct() is your friend

mint shuttle
#

ooh ill check that link out and look into those methods ty!

native root
#

πŸ‘

elder nebula
#

How do I add custom fonts to Django ckeditor (Google Fonts ect.)

#

I found it! Here's the code if anyone needs:

CKEDITOR_CONFIGS = {
    
    'default': {


        'toolbar': 'toolbar_Custom',
        'font_names': 'Roboto;',
        'toolbar_Custom': [
            {'name': 'Font', 'items': 'font_names'},
        ],
    }
},```
stray epoch
#

I have a flask app and I have this custom Jinja2 extension ```py
from flask import url_for
from jinja2 import nodes
from jinja2.ext import Extension

class StaticfilesExtension(Extension):
"""
A class that allows serving static files in the format {% static 'file/path' %} over the built-in {{ url_for(...) }} method.
"""

tags = {'static'}

def __init__(self, environment):
    super().__init__(environment)

def parse(self, parser):
    next(parser.stream)  # we have to call this
    filename = parser.parse_expression()

    return nodes.Const(url_for('static', filename=filename.value))

and it works as expected here ```html
    <link rel=stylesheet type=text/css href={% static 'css/reset.css' %}>
    <link rel=stylesheet type=text/css href={% static 'css/style.css' %}>
    <link rel=stylesheet type=text/css href={% static 'fonts/Overpass Mono/overpass-mono.css' %}>```
but when I have this ```py
<source type=audio/mpeg src={% static 'sound.mp3' %} >```
I suddenly get a syntax error ```py
File "D:\wowe\yert.pink\yert\templates\error.html", line 35
    )'/static/sound.mp3'```
#

any ideas on what is going on

#

the error is less than unhelpful

native tide
#

i've made a updated my website a week ago and i want to know your thoughts on this

#

what should i add and remove?

mint shuttle
mint shuttle
#

@native root i just wanted to follow up and say ty. i was trying to manually work a join table and not just use a manytomany field but your guidance pointed me in the right direction. ty!

tired root
#

Example: 10.10.10.1/:12 GET http://10.10.10.1:5500/js/render.js net::ERR_ABORTED 404 (Not Found) That was removed 2 days ago

#

HTML: <script src="js/render-plugins/bars.js"></script>

#

I am using the browser in incognito mode while doing webdev and this happens across all browsers installed, so I doubt it's that.

frigid raft
#
.hero-image-home {
    background-image: url("images/sailaway.jpg") !important;
    width: 100px;
    height: 100px;
    /* Set a specific height */
    height: 50%;
    /* Position and center the image to scale nicely on all screens */
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
    position: relative;

}

.hero-text {
    text-align: center;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    color: white;
}
#
{% extends "base.html" %}
{% block content %}
<div class="container">
  <div class="hero-image-home">
    <div class="hero-text">
      <h1> Hello </h1>
    </div>
  </div>
  {% for card in cards %}
  <div class="card bg-light mb-5 mt-5">
    <div class="card-header text-center h3 font-majormono">
      {{ card.card_title }}
    </div>
    <div class="card-body">
      {{ card.format_markdown|safe }}
    </div>
  </div>
  {% endfor %}
</div>
{% endblock %}
#

The background image in .hero-image-home isnt showing

#

ive been trying to figure this out for too long.

#

If anyone has a clue, help would be greatly appreciated

#

I'm using django if that is important

native root
#

@frigid raft /css/images/sailaway

#

{% static css/images/...

frigid raft
#

Where do you want me to put

{% static css/images/...

#

@native root

native root
#

Or perhaps /static/css/...

native root
#

If that doesn’t help, take a look in the dev tools network tab in your browser, usually gotten to via right clicking an element and β€œinspect”ing

#

That will tell you the resources requested and received

frigid raft
#

would this mean it is correctly requested and received

vagrant adder
#

@tired root
Try hard refresh

#

Ctrl-f5

native root
#

That would, yes. Interesting.

#

It is possible your image is so big that β€œcover” causes it to get lost in unclear colors, but I’m not sure

frigid raft
#

I think it is a fairly large image

#

well

#

it is 1920 x1080

#

when i hover over it in inspect element, it appears as 100x0 on the right

native root
#

x0 means that it's not displaying because the height isn't working

#

This depends on what's inside it, but if you've absolutely positioned the text inside, the container will have 0 height, and not show the background

frigid raft
#

Can you review the source code i have above?

#
html {
    /* To make use of full height of page*/
    min-height: 100%;
    margin: 0;
}
body {
    min-height: 100%;
    margin: 0;
}
``` I also have this if this matters
native root
#
position: absolute;
#

If you want to center your hero text inside it's container

#

In all honestly I would suggest flexbox

frigid raft
#

ahh it worked it shows

native root
#

?

frigid raft
#

The image now shows

#

not exactly how i want it

#

but it is progress

native root
#

yep

frigid raft
#

tysm I've been banging my head on this for a long time

native root
#

nw!

#

but good luck!

frigid raft
#

tyty

rare notch
#

Hi, I'm learning Web development with Python, and I stumbled upon this course from Real Python: https://realpython.com/products/real-python-course/
Is it worth the price ? Real Python is usually producing good articles, but the price is high so I need feedback.
Thanks

frigid egret
#

@rare notch The website itself is trustworthy, they have many useful articles. But I doubt there are many people who can tell you if that course is good.

#

Hi all. I have a question regarding launching an app on a live server.

#

I've tested it out on my local machine first, and everything seems to be working fine on live server as well except one feature. Is there a way for me to see full log, like I can see it in terminal on local machine?

gleaming herald
#

Hey All

#

Does anyone know how to build the chat app pop up on websites

frigid egret
#

That is not a simple question to answer

gleaming herald
#

I already have backend ready

#

a api which responds to messages

#

but I cannot figure out the front end part

frigid egret
#

Still, the concept has so many variables

gleaming herald
#

see here

#

when you click the chat application it opens a side bar

frigid egret
#

If you have backend ready, it's down to javascript to make front end

gleaming herald
#

I wanna do that

#

yeah exactly

#

can you send a github or a tutorial link

#

where I can learn

#

I made AI backend

#

but I am not much into front end

frigid egret
#

JavaScript (), often abbreviated as JS, is a high-level, interpreted scripting language that conforms to the ECMAScript specification. JavaScript has curly-bracket syntax, dynamic typing, prototype-based object-orientation, and first-class functions.
Alongside HTML and CSS, J...

#

JS is a language.

gleaming herald
#

That I know

frigid egret
#

As I was saying, there's no simple answer to that

gleaming herald
#

I wanna see some example code

#

where you can click on the chatapp logo in bottom down and it calls an API

#

and shows the response of API

frigid egret
#

You should try and look for webchat interface tutorials

#

That's probably the closest you can get

#

There are no ready-to-go out of the box solutions

gleaming herald
#

Okay

#

Thanks

#

I'll see some tutorials

#

I found one

sonic flicker
#

how ot oview pdf files

#

how ot view pdf files from s3 bucket

#

in webpage

#

is it possible

rigid laurel
#

PDFtoJs or an iframe

#

Assuming you have a url for it

dense slate
#

What might be a good (simple) implementation to track link/button clicks in Django?

#

Hopefully without using third party packages.

frigid raft
#

Django can't find my media files from ImageField

#

The is the media root when i print it

/home/kanelooc/code/personal/python-projects/youkaneduit-django/media/

#

Output when image isnt found:
Not Found: /media/blog_pics/4k-wallpaper-beach-bird-s-eye-view-2049422.jpg

#

Any idea what I can do to fix this?

ripe mango
#

Hey i've got a question about Django Admin

#

I have to create a page to make a new object (Intersticial)

#

but i have to call a special script when the object is created

#

what can i override to do that ?

unborn terrace
#

@ripe mango Django signals ?

ripe mango
#

Hmm not really

#

the "script when the object is created" is to creating an other object lol

#

so its just one-line

unborn terrace
#

Django signals allow that

ripe mango
#

yep but why using a signal ?

#

i can simply override the function called at the creation of an object

#

and insert my request to create a new object after the commit

#

so, the real question is: the function hmm

unborn terrace
#

@ripe mango signals are functions created at the creation of an object

ripe mango
#
   def add_view(self, request, **kwargs):
        super(IntersticialAdminForm, self).add_view(self, request, **kwargs)
        print("Adding new object.")
        print(self.fields['add_subarea'])
#

this is good ?

unborn terrace
#

Oh a form

ripe mango
#

Yepp sry

unborn terrace
#

I thought you were talking about a Model instance

ripe mango
#

i have not mentionned that is a form

#

nop, i'm in the form /add/ on the admin panel of django

#

and after that, the object will be create πŸ™‚

unborn terrace
#

So you want to add fields to the form right ?

ripe mango
#

hmm, i have self.fields that contains a list

#

and for all elements in this list, a new object will be created (in an other model of the form)

#

thats why i need to do that manually

unborn terrace
#

What are these β€œnew objects” ?

ripe mango
#

The form is set on Intersticial model, and I have to create new objects in GeoExclude model

unborn terrace
#

Okay, well in such case you have to work that in the form save method I guess

ripe mango
#

oh its save ?

unborn terrace
#

Yeah, well to me that's save's responsibility

#

Or a Django signal if you want to generalize the behavior beyond that model's admin interface

ripe mango
#
    def save(self, commit=True):
        intersticial_obj = super().save(commit=False)

        if commit:
            intersticial_obj.save()
            for geo_exclude in self.fields['add_subarea']:
                # Creating here my new object
        return intersticial_obj
#

what you mean of that ?

#

(edited)

unborn terrace
#

Could you please explain what Intersticial and GeoExclude are, and why do you want to create GeoExcludes objects after Intersticial here ?

ripe mango
#

Hmm, ok

#

an Intersticial can have some exclusion

#

like if you want to exclude the France country

#

you can have a lot of exclusion

unborn terrace
#

Please don't exclude my country

ripe mango
#

je suis franΓ§ais aussi lol

#

Γ§a doit se voir Γ  ma faΓ§on d'Γ©crire

unborn terrace
#

Les français s'excluent tout seul, c'est vrai 😏

ripe mango
#

aha

#

Intersticial model contains all informations relative to the intersticial.

#

GeoExclude model contains all country excluded, with a foreignkey to Intersticial

#

are you sleeping down on your keyboard ? πŸ˜‚ @unborn terrace

unborn terrace
#

@ripe mango I was typing a long β€œsolution” but I just remembered something

#

Why not using inline forms ?

#

Well, inline admins*

ripe mango
#

hm what is ?

unborn terrace
#

You'll get a nice dynamic form where you will be able to add all foreign-key associated objects you want

ripe mango
#

its mentionned "to edit", it work for add too ?

unborn terrace
#

Yes

ripe mango
#

it sound really better lol

unborn terrace
#

β€œto edit” is in the sense of β€œthat you'll be able to change in the form as any other form”

#

Yeah, that's the β€œstandard” one tbh

ripe mango
#

i will try first the method with save override

unborn terrace
#

No please try this method first

ripe mango
#

😦

unborn terrace
#

That's much much less technical debt

ripe mango
#

my lead dev are not online aha

#

and im seeing he has already using inline method, so he know it

#

but he don't say me to use that

unborn terrace
#

Whatever, if that suits what you want to achieve that's very probably the best way to do it

ripe mango
#

Yep I think too, i will ask it when he come back

#

(if he come back today 😒)

unborn terrace
#

Why don't you just try it ?

#

You'll be done in 5min

ripe mango
#

hmm im beginning on django

#

i don't know how to use this inline method

#

i have read the doc but it look complex

unborn terrace
#

That's in the tutorial if I recall correctly

frigid egret
#

Hi all. I have a question regarding launching an app on a live server.

#

It works fine on localhost, and for the most part on live server as well. But one feature doesn't work properly. Is it possible to have terminal output like I have on local machine?

rigid lily
#

is django dev server single threaded or just single processor??

#

if you dont deploy it to apache or nginx

mild spade
#

If anyone has any experience with POST/GET requests in python , let me know!

I'm trying to work out a sort of pattern a website is using to generate their links when adding an item to cart

#

Feel free to DM / Mention me as i'm AFK

unborn terrace
#

But you can disable multithreading

#

!ask @mild spade

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.

mild spade
#

!ask If anyone has any experience with POST/GET requests in python , let me know!

I'm trying to work out a sort of pattern a website is using to generate their links when adding an item to cart

Or if anyone has experience with anything similar let me know thanks πŸ™‚

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.

unborn terrace
#

@mild spade please read the text in !ask

#

That was for you

#

Especially the first bulletpoint

native tide
#

If anyone could help me with sockets, I'm having a weird problem with them #help-croissant

native tide
#

You guys. what is the best IDE for HTML and CSS?

#

i need recommendations

#

i used Webstorm and i liked it. but now i need to pay to use it so

#

we broke up

native root
#

take a look at adobe brackets

steel tiger
#

Don't really need a specialized ide

#

Just vscode and "live server" (extension for vscode) usually does the trick

tired root
#

notepad and http.server πŸ˜›

#

but yeah, vsc is good, live server just does automatic reloads

#

which I β™₯

dawn drift
#

VSCode

vagrant adder
#

@native tide vscode or atom

#

or even brackets

#

it has built in live server

native tide
#

i now use brackets. i like the animation

earnest trail
#

Anyone have expertise with python Babel? I have a question: specifically, is it possible to have multiple messages.pot? Our main pot will be human translated while we have some other translations that we would like to use a predefined definition coming from another source that gets updated frequently.

Is this the right place to ask? Can’t find anywhere in docs how I would achieve this. Tried asking on Github and got no reply either. What if I ask on the subreddit? Is that an appropriate channel or are there better subs for it?

Thanks! β€”Β please tag me if you reply

native tide
#

hello again.

#

when i visit my website on my phone ,the letters are black.

#

the background is dark so the text is pretty much unreadable

#

but when i tell other people to access my webpage .the text appears as it should.

#

in white color

#

i use google dark mode on my phone and i think that causes the problem.Is that true? if so.. How do i fix it?

steel tiger
#

Well your css is very non-standard and has no proper colour control (scss or similar)

#

All I can say

midnight prawn
#

!ask Hello, I was wondering what is the best Python IDE for web development?

open forum
#

Pycharm Pro is great, since it includes all the features of Webstorm, but it's unfortunately not free.

#

VSCode with the right plugins also works.

midnight prawn
#

Thank you!

#

Which ones have you used personally?

open forum
#

I use both.

midnight prawn
#

For VSCode what plugins do you recommend?

open forum
#

There are popular plugins for all the major languages you're gonna be using, like Python, JS, TS, CSS, etc.

#

It's easy to find in the extension browser, just make sure to use the ones with a lot of downloads.

midnight prawn
#

Okay, thanks again!

round saddle
#

Hey. I have a question if anyone uses gitlab. idk why but everytime someone wants to visit my website (even I once) has to login to gitlab first. Is it needed? Or it's cuz it's private repo?

sacred dagger
#

nvm i found the error

dawn drift
#

What is the best Python framework for a beginner? I was looking at Django but Flask seems to do what I need.

fathom sapphire
#

does anyone know html and js here?
not sure if my script is loading into my html or what might be up

icy stream
#

PM me the code

fathom sapphire
#

did you block me? the messages will not come through

safe garden
#

how are you loading in your js?

fathom sapphire
#

<script type="text/javascript" src="./Assignment2.js"></script>

#

just inside</body>

safe garden
#

what's in the script?

fathom sapphire
#

`(function() {
var add_row;

$('#add-row').on('click', function(e) {
var table_body;
e.preventDefault();
table_body = $(e.target).data().table;
if (table_body) {
return add_row(table_body);
}
});

add_row = function(table_body_element) {
var $cloner, $new_row, $rows, $tbody, count, inputs;
// Get some variables for the tbody and the row to clone.
$tbody = $('#' + table_body_element);
$rows = $($tbody.children('tr'));
$cloner = $rows.eq(0);
count = $rows.length;
// Clone the row and get an array of the inputs.
$new_row = $cloner.clone();
inputs = $new_row.find('.dyn-input');
// Change the name and id for each input.
$.each(inputs, function(i, v) {
var $input, $label, checked;
$input = $(v);
// Find the label for input and adjust it.
$label = $new_row.find(label[for='${$input.attr('id')}']);
$label.attr({
'for': $input.attr('id').replace(/[.]/, [${count + 1}])
});
$input.attr({
'name': $input.attr('name').replace(/[.
]/, [${count + 1}]),
'id': $input.attr('id').replace(/[.*]/, [${count + 1}])
});
// Remove values and checks.
$input.val('');
checked = $input.prop('checked');
if (checked) {
return $input.prop('checked', false);
}
});
// Add the new row to the tbody.
return $tbody.append($new_row);
};

}).call(this);
`

#

just used to grab the table thats above it and then clone it when the button is pressed

#

in basic

safe garden
#

are there any errors in the console?

fathom sapphire
#

thats what the browser consol picks up

#

t the top

safe garden
#

is jquery installed?

#

or linked

fathom sapphire
#

i dont know how to do that id be assuming no

safe garden
#

look up a cdn for jquery

#

and copy-paste the script tag it gives you

fathom sapphire
#

i thought i just had to code it? is it similar to using pandas in python that u have to call it

safe garden
#

no; jquery is a library

#

you need the library linked to be able to use it

fathom sapphire
#

ah

safe garden
#

it's like using a module in python without importing it

fathom sapphire
#

i shall look into that πŸ‘

#

ok πŸ™‚ i used it and now the consol has no issues

#

but my button doesnt work :>

#

thats what i used

#

but i think the button not working is my fault

native tide
#

Hey anyone interested to buy a website

light hull
#

This is a wrong place for that.

vagrant adder
#

@dawn drift
I would say flask because django has difficult to understand view routing and mapping

#

I started with flask and now i'm experimenting with quart

gleaming herald
#

@vagrant adder

#

Instead of quart try fastapi

#

It's way better

#

Here check em out

frigid raft
#

I'm using django and some of my CSS that are in the same file dont work and some of them do

#

they work in development

#

but theyre not working in deployment

native root
#

Define 'don't work'. Have you checked to see if they're being requested?

frigid raft
#

wdym requested? When I look at my sources through inspect/chrome dev console the classes are there

#

Here is an example

vagrant adder
#

@gleaming herald what's that

native root
#

That's good enough. The dev console includes a "network" tab, that lets you see if the files are being requested by your page and handed back by the web server

frigid raft
#

THe first one is on deployment

#

2nd is on development

native root
#

Hm

frigid raft
#

The other css in the site works

#

which is in the same file

native root
#

And the new css visible in development is being loaded by your browser, and not applied to the page?

frigid raft
#

wait actually let me correct myself

#

the classes dont appear in the dev console

#

sorry i thought it did

#

they ARE in the file though

native root
#

Ok

#

Did you try a cacheless reload?

#

Ctrl-shift-reload?

frigid raft
#

yeah i tried that

#

i tried a dif browser as well

native root
#

Hm

#

How are you deploying?

frigid raft
#

apache2 on a VPS

#

i tried restarting apache2 as well

native root
#

Also, if you go to the network tab, you can view the raw file being served by your live environment. Is that file different than what you've got on disk?

frigid raft
#

and i did collectstaic

#

let me check

#

it is the same file

#

with the missing classes though

native root
#

Ok

#

So what we've established is that the live server is giving out old copies of your css

#

Next step is to check the files on disk in the live environment, to see if they're up to date

frigid raft
#

It is up to date on my VPS

native root
#

And in the collectstatic folder on the vps it is up to date?

frigid raft
#

my css dir is in my staticfiles dir

#

So yes? If that is what you're asking

native root
#

yes

#

Ok

#

Well, that means apache is serving the old response, or if you've got cloudflare or similar? That would also be serving that old response

frigid raft
#

Wait i found a stackoverflow solution saying to clear static files first so im going to try that

#

1 sec

#

Okay that worked

#

Thanks for being here though!

native root
#

πŸ‘

gleaming herald
#

@vagrant adder Actually the performance and documentation of fastapi is better

#

if you just are good enough in flask

#

and looking for a change

#

I guess you should try fastapi instead of quart

#

its also async api

vagrant adder
#

The thing with quart is that it is compatible with almost all flask extensions

#

Because it's built on top of flask

#

And that's what got me intrigued

#

Also, async ability is just nice

native tide
#

Hello, if anyone uses django-rest, do you prefer django rest token auth, django rest knox auth or django rest jwt ?

gleaming herald
#

Oh Okay ! @vagrant adder

vagrant adder
#

@gleaming herald so i can build quart app but i can incorporate flask-sqlalchemy

gleaming herald
#

Yeah

#

That sounds like a good start

#

I thought if you are learning async backend

#

FASTAPI would be a good place to start

#

It has way more functionality

vagrant adder
#

Does it?

#

Hmm

gleaming herald
#

Yeah

vagrant adder
#

Such as ?

native tide
#

Hi! Anybody got an idea how to make a online purhcasing bot with selenium and chromedriver?

#

or any examples

robust vigil
#

depends on your use case
server rules mean nobody on here will help you with stuff that breaks ToS
https://pythondiscord.com/pages/rules/

#

Either way, simply following some basic selenium tutorials will teach you more than enough to get started with that

native tide
#

@robust vigil no its a program that will check out supreme automaticlly

fathom sapphire
#

hi seeking asistance to finsih this last part of the javascript to run my website

#

the if statement runs perfectly fine

#

but for some reason the while statment doesnt seem to be

#

even though they are both meant to run

#

if it helps the same code that the while is running

#

controlled by a different part

#

works fine

#

im just not sure, its just that the while statement lets me iterate instead of click im just not sure what might be incorrect

native root
#

@fathom sapphire

#

You're returning inside the loop, is that intended?

#

That will end the loop

fathom sapphire
#

oh, πŸ˜…

#

even still it doesnt seem to return

#

i have one table

#

which is what it adds a row to basically by cloning it

#

it doesnt add any extra rows

#

how would i get it to call the function without it being a return?

#

that's the table

#

but i dont want the button

#

i want it to take from the value and loop till it gets to the number of times

#

since that how many people there are

native root
#

just leave the function in the line

#
if (table_body) {
    add_row(table_body)
}
fathom sapphire
native root
#

yep

#

I'd also suggest indenting that } the line after, it's misleading as it appears now

fathom sapphire
#

that's what i ended up doing but it unfortunately still doesn't run

#

πŸ˜„ I'm thankful for the help so far though

#

hopefully you can see what I cannot unless its something bigger than that

native root
#

Is there anything in the console about it?

fathom sapphire
#

empty consol