#web-development

2 messages · Page 123 of 1

native tide
#

Yeah React is popular for the frontend w/ Django.

#

Btw are you using class-based components or function-based components in React?

native tide
#

gotcha

#

i'd recommend trying out the function based components though. w/ some react libraries class based components are incompatible

gusty gate
#

Hi guys
I built a small web server with Flask that connects YouTube PubSub to a Discord webhook.
Now I would like to add commands to subscribe or unsubscribe to a channel. Like "flask youtube subscribe Idh234had" I have seen that Flask even offers CLI command features. Is this possible with a running Flask app or how does this work?

fallen spoke
#

Thank you, so just to be sure, the expected outcome of using IsAuthenticated is to stop users who are not authenticated from accessing api endpoints?

native tide
#

Yep. If a user is not authenticated the browser will return an Unauthorized response status. (401)

Since there are different types of authentication (session, token), you need to set you DEFAULT_AUTHENTICATION_CLASSES so that Django knows what type of authentication must be checked.

fallen spoke
#

How safe are JWTs? I looked online and people seem to have mixed opinions on them. what is the standard best practice for having an api backend? cookies? JWTs? something else?

native tide
#

I use token authentication (storing the token via a cookie)

#

one reason for this is that I can invalidate the tokens while JWTs can't really be invalidated on your end

#

but I don't really know much about JWTs, when I asked I was told to avoid them at all costs by some pretty senior people.

native tide
#

Hi. Guys I am currently working on a Django project which is a gaming website. (It is for a minecraft server) My client asked me to do authentication with xbox account.
Thank God there is api in python.
But the question is how to integrate this to an Django project.

#

Here is the website

karmic egret
#

Does anyone can help me make my html friendly to mobile user? I am still kind new to html

#

Thanks

native tide
#

@karmic egret you can use bootstrap

karmic egret
#

can you give me more specific detail and instruction? I can send my code to you.Thank you very much @native tide .

chrome coral
#

Got it 😀...i know html and css but not that good with js. Will learn it..

sinful helm
#

otherwise, go ahead and develop in vanilla js using dom API

chrome coral
#

Thank you 😀

empty cargo
#

because of the roboter?

kindred osprey
#

Yee. I think using REST framework might make our lives a bit easier but it can be done without that as well. I will try it without django REST framework. Thanks :))

shy current
#

hello

warm shoal
#

hi

#

I'm a beginner at django and I need some help

#
from django.contrib import admin
from .models import Product, Offer


class OfferAdmin(admin.ModelAdmin):
    list_display = ('code', 'discount')


class ProductAdmin(admin.ModelAdmin):
    list_display = ('tag', 'price', 'stock')


admin.site.register(Offer, OfferAdmin)
admin.site.register(Product, ProductAdmin)```
#

this is a practice that I did

#

and this is the error I keep getting

#
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 783, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "C:\Users\Batata\PycharmProjects\Using_Django2\products\admin.py", line 1
4, in <module>
    admin.site.register(Product, ProductAdmin)
  File "C:\Users\Batata\PycharmProjects\Using_Django2\venv\lib\site-packages\dja
ngo\contrib\admin\sites.py", line 119, in register
    raise AlreadyRegistered(msg)
django.contrib.admin.sites.AlreadyRegistered: The model Product is already regis
tered with 'products.OfferAdmin'.```
#

can anyone help??

eternal blade
#

Did you register the Products class anywhere else?

warm shoal
#

yep in the modules file

eternal blade
#

I think that why you are getting an error. you have aldredy registered it in another place

warm shoal
#

so shall i not register it?

eternal blade
#

Unregister it from anywhere else you have registered it. It should work

warm shoal
#

yeaaa... it didn't work

eternal blade
#

You cannot register more than one ModelAdmin for the same model (this results in an AlreadyRegistered exception). -google

#

@warm shoal did it work?.

warm shoal
#

ummmm.... well this is weird... i tried it a couple different times and then exited the server and rewrote what was written before...... i ran the server again to find it working...??

eternal blade
#

Did you get any error

warm shoal
#

nope

#

though i am confused...

#

why did it work now if it gave me an error before?

#

well anyways thanks a lot for your help 😄

eternal blade
#

it sometimes happens to me also. I get get an error but when I run it again the error goes. wierd

stone wren
#

suppose I have list of something like this

[
  0: {id: 5, itemName: "test", quantity: 2},
  1: {id: 7, itemName: "test1", quantity: 1},
  2: {id: 2, itemName: "test2", quantity: 3},
]

how can I convert them to this list? I want to extract quantity

[
  0: {
      quantity: 2, 
      product: {
        {id: 5, itemName: "test"
      },
  1: {
      quantity: 2, 
      product: {
        {id: 7, itemName: "test1"
      },
  2: {
      quantity: 2, 
      product: {
        {id: 2, itemName: "test2"
      },
]
devout coral
#

Anyone know a good way to reference static files with Django?

#

When not in templates

quick cargo
#

@devout coral doesn't it have url_for?

devout coral
#

I do not quite follow

#

from django.templatetags.static import static This is what I am currently using @quick cargo But I am getting access denied.

quick cargo
#

Do you mean referencing them in terms of their paths?

devout coral
#

I want the url since it is in S3.

#

I could download it into temp and then use it but that seems kinda meh.

quick cargo
#

I'm pretty sure django has a url_for function which given X static file name will produce the relevant path for it but I don't entirely get what you want

devout coral
#

You know how in templates you use the static tag to reference a static file and it returns the full url. That is what I need.

#

I just need the url so then I can use it in reportlab to put it on a PDF.

quick cargo
#

You want url_for then iirc

#

But note it returns a relative path based of the location of the main file

devout coral
#

That is saying to use the method I am using now.... But I get an error.

#

logo_url = static('\main\\MV_Transportation_logo.png')

#

That is how I am implementing it in my code.

#

@quick cargo Any idea on why I would be receiving that error?

slender flare
#

Can anyone suggest me how can I make a django form dynamic. I mean I need to accept a response through a from and then check if the input already exists in the database. If no then I will simply save the response to the database. But if it already exists then I need to make another field(previously hidden input in HTML form) visible within the form along with the data last input pre-filled. I am a newbie in django and it would me nice if someone could help me.

quick cargo
#

If its Windows then it's normally only raised if its open in another process

#

But mostly a shot in the dark

devout coral
#

The thing is all the files are in S3...

#

Also this is all containerized and it is running on a debian based image.

devout coral
native tide
devout coral
#

Good thing about ajax is it is asynchronous so the user would not be waiting and it should be a good user experience

#

@quick cargo Also, I thought it could be my S3 policy but the static file I am trying to serve is the logo which is being used in the page already.

quick cargo
#

Hmm maybe

#

Im out of ideas though I'm afraid, don't do much work with S3 and django

devout coral
#

Alright, I will try for a little longer then I will just resort to downloading it and storing it temporarily.

slender flare
#

Thanks @devout coral but I don't know much about Js. Thanks @native tide I will try this out as it is much easier. Later on I will try AJAX to make this async.

native tide
# slender flare Thanks <@!202153796825120768> but I don't know much about Js. Thanks <@456226577...

great! If you want to try the AJAX-like client-side request approach I recommend fetch API, because it's pretty easy to use:
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Uploading_JSON_data

keen grove
#

Hi, not sure if this is the best channel for this since this is a deployment question, but I'm trying to deploy a flask app via uwsgi and I'm having trouble figuring out how to get uwsgi to run as python 3.7. It defaults to 3.6. Has anyone dealt with that before?
All this is happening in a venv:
(venv) ➜ venv which python
/apps/venv/bin/python
(venv) ➜ venv python --version
Python 3.7.5
(venv) ➜ venv which uwsgi
/apps/venv/bin/uwsgi
(venv) ➜ venv uwsgi --python-version
3.6.9

hybrid bobcat
#

How do I use the gmail api during development?

#

It’s in order for me to create client id or authentication, it’s forcing me to provide a public url

verbal snow
#

I keep getting AttributeError: 'User' object has no attribute 'pk' when trying to use django admin site

proven birch
#

Which fraemwork is good to use for web development, like php has some laravel, CI ?

#

MVC framework for Python

simple kite
#

ech tee em ehl

#

see ess ess

#

jawascri

#

fles

#

djeng o

#

pie then

native tide
#

@simple kite are u good?

simple kite
#

yes sar, i em wery good

#

mahk sure to subribe to my channal at click notification beell

native tide
#

uhm

#

nice

simple kite
#

zebra goes chirp chirp

final sequoia
#

hi everyone, i'm trying to send a post request to my django server using rest through react/axios, but the database never seems to get updated (request succeeds, returns 200 but the database doesn't update when i check on frontend): https://github.com/hanyuone/kanban

#

django server is on localhost:8000, react frontend is on localhost:3000

#

request is sent in frontend/index.jsx

#

sorry if i can't reduce the project down to a minimal example, not exactly sure how to reduce the problem by much since i'm new to webdev

vestal hound
#

did it get updated?

final sequoia
#

Not sure how to do that, what exactly do I print if anything

#

do I set up a breakpoint or smth?

#

like it does show the request going through for the PUT and GET afterwards when i fetch /api/boards but i'm not really sure how to check the full db

inland stirrup
#

a comment section to a non blog flask application ....any idea how to approach this?

eternal nimbus
#

how do i set up mongo Db ?

#

ive been struggling with settting it up for sometime now ?

#

hmmm

final sequoia
#

cause i did check the request coming in and the data all seemed fine, in the views section

#

but how would i make sure the data is updated after

vestal hound
final sequoia
#

How do I do that

vestal hound
#

alterantive

#

alternatively

#

just run the shell app and query the model objects

final sequoia
#

Yeah I know a little, should I just run the sql commands in shell?

#

There isn’t a place for me to query as python code is there

final sequoia
# vestal hound do you know SQL?

like i tried displaying the data that was sent and retrieved (console.log in axios in frontend/index.js), the put request seemed fine and the data seemed fine when i printed it out in views.py, but the actual PUT request doesn't actually update the database for some reason

vestal hound
#

there is

#

look up

#

the shell management command

final sequoia
#

as in pipenv shell?

final sequoia
#

ok i think the issue might be that PrimaryKeyRelatedField has a specific order and can't be swapped around

#

is it possible to swap around the order of keys displayed in PrimaryKeyRelatedField? because i have a kanban-like app, and i want to switch the order of certain tasks around on a specific board by dragging/dropping them

steel reef
#

can anyone tell how to style the dropdown menu in django?? I want to give a custom text in a select filter field instead of the ----(dashes)

native tide
#

hello

#

can we yse html module in python ?

open owl
open owl
open owl
#

in your models.py


MY_CHOICES = (
('ORANGE', 'Orange'),
('BANANA', 'Banana'),
)

class Fruit(models.Model):
    fruit = models.CharField(default='MANGO',     
choices=MY_CHOICES, max_length=20)


#

@steel reef try the code above

native tide
#

@open owl ok

icy canopy
#

@open owl the default is 'MANGO' and you don't have a 'MANGO' choice

#

How about this:
PROPOSED = 'Proposed' ACTIVE = 'Active' ONHOLD = 'On Hold' COMPLETED = 'Completed' CANCELED = 'Canceled' STATUS = [ (PROPOSED, 'Proposed'), (ACTIVE, 'Active'), (ONHOLD, 'On Hold'), (COMPLETED, 'Completed'), (CANCELED, 'Canceled'), ] status = models.CharField(max_length=9, choices=STATUS, default=PROPOSED, null=True)

open owl
gentle anchor
#

HOW TO START READING DJANGO CODE? because i want to code in Google summer of code ..HELP

steel reef
final sequoia
#

is there a way to "order" a serializers.PrimaryKeyRelatedField? i have a kanban-like application with a bunch of Tasks linked by primary key to Boards, and i want to reorder the Tasks by dragging and dropping

#

my models:

class Board(models.Model):
    title = models.CharField(max_length=120)

    def __str__(self):
        return self.title

class Task(models.Model):
    board = models.ForeignKey(Board, default=1, related_name="tasks", on_delete=models.CASCADE)
    title = models.CharField(max_length=120)
    description = models.TextField()
    order = models.IntegerField()

    def __str__(self):
        return self.title

my serializers:

class TaskSerializer(serializers.ModelSerializer):
    class Meta:
        model = Task
        fields = ["id", "title", "description", "order"]
        ordering = ["order"]

class BoardSerializer(serializers.ModelSerializer):
    tasks = serializers.PrimaryKeyRelatedField(many=True, queryset=Task.objects.all())

    class Meta:
        model = Board
        fields = ["id", "title", "tasks"]
#

what i originally did was PUT requests, but i didn't realise that the tasks prop of BoardSerializer can't be updated

stone wren
#

error starts from here, I am trying to access my model method (get_packages_by_package_state_value), then this happens

File "/home/kenan/exbir/exbir-api/exbir/database/models/package.py", line 113, in get_packages_by_package_state_value
    return cls.query.filter_by(current_state=PackageState(package_state_value)).all()
  File "/home/kenan/exbir/exbir-api/env/lib/python3.8/site-packages/flask_sqlalchemy/__init__.py", line 514, in __get__
    return type.query_class(mapper, session=self.sa.session())
  File "/home/kenan/exbir/exbir-api/env/lib/python3.8/site-packages/sqlalchemy/orm/scoping.py", line 78, in __call__
    return self.registry()
  File "/home/kenan/exbir/exbir-api/env/lib/python3.8/site-packages/sqlalchemy/util/_collections.py", line 1022, in __call__
    return self.registry.setdefault(key, self.createfunc())
  File "/home/kenan/exbir/exbir-api/env/lib/python3.8/site-packages/sqlalchemy/orm/session.py", line 3286, in __call__
    return self.class_(**local_kw)
  File "/home/kenan/exbir/exbir-api/env/lib/python3.8/site-packages/flask_sqlalchemy/__init__.py", line 136, in __init__
    self.app = app = db.get_app()
  File "/home/kenan/exbir/exbir-api/env/lib/python3.8/site-packages/flask_sqlalchemy/__init__.py", line 987, in get_app
    raise RuntimeError(
RuntimeError: No application found. Either work inside a view function or push an application context. See http://flask-sqlalchemy.pocoo.org/contexts/.
vestal hound
#

what i originally did was PUT requests, but i didn't realise that the tasks prop of BoardSerializer can't be updated
@final sequoia why not PATCH the order field

sonic ferry
#

I decided to close my submenu when a user clicks on a link inside. So now, when they navigate back a page, the submenu isn't still open. However, the focus is still inside the submenu(which is closed, display: none;). Was I wrong to close the submenu onclick?

native tide
#

@final sequoia if you don't know SQL you can get a visual DB browser, e.g. SQLite DB Browser and see what rows are in your DB

drowsy frigate
#

Hello, can i ask here for raw discord api?

fallen spoke
#

I have this line: user = User(*request.data) Is there any way that I can set user to equal request.data only for empty fields? so basically, get request.user and request.data check if there are any null values in request.data and replace them with whatever is under the same attribute in request.user without needing an if statement for each single attribute

ancient sorrel
#

html??

naive egret
#

Sup peeps

#

who is familiar with apache2 config for django deployment

#

Anyone?

native tide
#

hehehehehe

#

who can speak Russian, help pls

trail veldt
deep bloom
#

how do I install django python 3.9.1

dire fractal
#

use pip like normal?

#

Spooooky, ghost pings. Love me some

deep bloom
vestal hound
#

@deep bloom what happened

deep bloom
#

Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases.

vestal hound
#

...is Python installed?

deep bloom
#

nvm

#

it worked

vestal hound
#

🥴

harsh dome
#

I am using django and getting this error ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine can anyone help?

stable kite
#

are you using ajax?

near bison
#

Thanks. I found a way

stable kite
verbal bloom
#

How to upload a file (swf) on a page (Django)&

#

?

native tide
#

не возражаю

#

алё, ты куда пропал?

rustic fractal
#

Hello there, i am searching for someone who had used a reusable apps in django

amber harbor
#

i have been up all night trying to figure this out... help please why can't i cal postUser inside the else but i can call it before the addEeventListener?

#

 
let postUser = async (name, email, password) => {
     const options = {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            name: name,
            email: email,
            password: password
        })
    };
    try {
        const response = await fetch(`http://localhost:80/register`, options)
        const json = await response.json();
        console.log(json)
        return json
    } catch (err) {
        // TODO: put a toaster
        console.log('Error getting documents', err)
    }
}

let Register = {
    render: async () => {
        return /*html*/ `
            <section class="section">
                ...
            </section>
        `
    }

    , after_render: async () => {
        // TODO: add event listner for email checker on type
        document.getElementById("register_submit_btn").addEventListener("click",  () => {
            let name = document.getElementById("name_input");
            let email = document.getElementById("email_input");
            let pass = document.getElementById("pass_input");
            let repeatPass = document.getElementById("repeat_pass_input");
            if (pass.value != repeatPass.value) {
                alert (`passwords don't match`)
            } else if (name.value =='' | email.value =='' | pass.value == '' | repeatPass == '') {
                alert (`fields can't be empty`)
            }
            else {
                // XXX: HERE IS THE ERRORRRRRR
                let resp = await postUser(name, email, password);
                // TODO: call api register
                // TODO: show details if any
                // TODO: add token to Auth header
                // TODO: redirect to /
                alert(`email ${email.value} registered`)
            }
        })
    }
}

export default Register;```
strange notch
#

I have a question about no such table error or even better known as (main.auth_user_old)...
How should I fix it?

mental prawn
#

guys if for example i want to build a website, what languages do i need to learn?

inland stirrup
#

in a venv git add . is not working what should i do ?

native tide
#

The html is used for the contend the css is used for styling and javascript is used for back end or front end

native tide
#

Just downgrade to 2.1.5 version and it should work

#

I hope I helped you

#

Good luck!

marble gate
#

I keep getting a json decode error here when using oauth with authlib can someone tell me what the issue is.

@app.route('/glogin')
def login():
    google = oauth.create_client('google')
    redirect_uri = url_for('authorize',_external=True)
    return google.authorize_redirect(redirect_uri)
    

@app.route('/authorize')
def authorize():
    google = oauth.create_client('google')
    token = google.authorize_access_token() #JSON DECODER ERROR
    resp = google.get('userinfo')
    user_info = resp.json()
    session['email'] = user_info['email']
    session.permanent = True
    return redirect(url_for('index'))
   
cloud fjord
#

anyone knows best way to show the picture png as canvas streaming for live streaming?
which python module is good to work with png streaming?

#

picture should update automatically as latest file

open owl
open owl
inland stirrup
hybrid bobcat
#

yo so assume i have this folder structure with these files

folder-
     main.py
     foo.py
     foo.json
``` I can read the `foo.json` file inside of `foo.py` , and then import the variable that holds the parsed json value in `main.py` as `from foo import jsonval` .
But now if I move `main.py` outside of the `folder` directory, 

main.py
folder-
foo.py
foo.json
``` I change nothing in foo.py and foo.json except I change the import statement in main.py to from foo.foo import jsonval now, the read file line inside foo.py which reads foo.json throws an no such file or directory "foo.json" which don't really make sense to me, does anyone know why?

open owl
inland stirrup
open owl
inland stirrup
#

I did.... It got stuck there and that went on for 15 mins....I tried vs codes git and GitHub. Extension it says that index.dl is already existing so it can't create one and then a bunch of errors in the output console

open owl
inland stirrup
#

so i tried this and tried manually adding everything

#

and found my venv folder is not getting added

#

everything else is good

inland stirrup
native tide
#

I want to style my home.html template

#
{%extends '_base.html'%}
{%block title%}Home{%endblock title%}

{% block content %}
<h1>Homepage</h1>
{% if user.is_authenticated %}
    <p>Hi {{user.email}}</p>
    <a href="{% url 'logout' %}">Log Out</a>
{%else%}
    <p>You are not logged in</p>
    <a href="{% url 'login' %}">Login</a>
    <a href="{% url 'signup' %}">SignUp</a>
{%endif%}
{% endblock content%}
#

that inherits from _base.html

#
<!DOCTYPE html>
{% load static %}
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href='{% static "css\base.css" %}'>
    <title>{% block title %}Bookstore{% endblock title %}</title>
</head>
<body>
    <div class="container">
        {% block content %}
        {% endblock content %}
    </div>
</body>
</html>```
#

with the base.css file

#
body{
    background-color: rgb(39, 39, 39);
    color: white;
}

h1{
    color: red;
}```
#

But it doesn't work

#

The styling doesn't apply

#
STATIC_URL = '/static/'
STATIC_FILES_DIRS = [os.path.join(BASE_DIR, 'static'), ]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_FINDER = [
    "django.contrib.staticfiles.finders.FileSystemFinder",
    "django.contrib.staticfiles.finders.AppDirectoriesFinder",
]```
inland stirrup
#

i hope it doesn't work buddy don't jump the line just because u want help

native tide
#

🤨

inland stirrup
#

#rules don't jump in with your question if one is already going being discussed

gusty wagon
#

Anyone experience in google maps polygon circles in python backend and js frontend?

native tide
#

@native tide why is your STATIC_FILES_DIRS a list? Is that normal?

#

@inland stirrup I don't think that's a rule.

#

Also @native tide why is there a backslash here "css\base.css" is that normal too?

vestal hound
#

#rules don't jump in with your question if one is already going being discussed
@inland stirrup this is a topical channel...

inland stirrup
vestal hound
#

Are u saying yes to my post or what??
My question was almost resolved and then came that huge question tell me what do I do spam the server?
@inland stirrup if someone was already helping you, I don’t think they’re going to forget about that...

inland stirrup
#

Scroll up

vestal hound
#

if you want a channel that is exclusively for your usage, open a help channel.

inland stirrup
#

Lets leave it here

vestal hound
#

Scroll up
@inland stirrup I read everything already

inland stirrup
haughty turtle
#
Blog.objects.filter(entry__headline__contains='Lennon', entry__pub_date__year=2008)``` I want to loop through a JSON sent through a request, for each item in the JSON I want to add to my filter, how would I go about doing this?
#

Coders block is not letting me figure this out.

#

Having an if statement included to check that it is not null

haughty turtle
#

When I load it this is what its going to be

vestal hound
#

so you want e.g.

#

role=this.state.role, field=this.state.field etc.?

#

@haughty turtle

haughty turtle
#

In my models I have availabeTag = models.JSONField()

haughty turtle
vestal hound
haughty turtle
#

yeaup

vestal hound
#

Blog?

haughty turtle
#

Course

#

But I can change the name at any point in time.

vestal hound
#

...where is Course

#

okay can you show ALL the relevant models

vestal hound
#

and that looks like something from the Django tutorial

haughty turtle
#

course is the Model in which contains availableTag which is a JSONField

haughty turtle
vestal hound
#

then

#

well

#

I would say

#

when you're asking for help

#

ask something that is as close to what you want as possible

#

because at first you didn't mention the JSON field and your model is named something different

#

anyway, you can access the values of a JSON field using double underscore notation

#

exactly as if they were chained lookups of a model

#

e.g. available_tag__role=this.state.role

#

so what you need to do is remap the keys of the query JSON

#

and then use ** to spread it into keyword arguments

haughty turtle
#

I mean I would be able to edit it, just need a working example py ContactInfo.objects.filter( data__name='John', data__pets__has_key='dogs', data__cities__contains='London', ) from the django docs is similar to the other filter method I sent

vestal hound
#

it's harder for people to understand what you want

#

if you don't explain yourself clearly?

haughty turtle
vestal hound
#

like your original question suggested 1. you have a Blog model and 2. you were filtering on the model's fields, as opposed to the contents of one of its JSON fields

haughty turtle
#

{data__role:this.state.role, data__field:this.state.field, data__stack:this.state.stack, data__language:this.state.language}

#

but how would it convertdata__role:this.state.role to data__role=this.state.role

haughty turtle
vestal hound
#

like I said

vestal hound
haughty turtle
#

I have been reading this

#

I know it unpacks it, but I do not see how ** convert key:value to key=value

#

@vestal hound

topaz finch
#

Default python thing

native tide
#

Hi guys i have a problem in flask i tried to get subdomain effect like subdomain.domain.com do you know how to do it

forest talon
#

That is not a problem with flask, that is a server responsability

#

You can setup that in NGINX

open owl
copper lagoon
eternal blade
#

I am unable to add my django app to installed apps. I get this exeption: '''ModuleNotFoundError: No module named 'user_chat' '''.

native tide
#

@eternal blade user_chat and member_login app should be in same directory as the manage.py

eternal blade
#

ok

eternal blade
#

@native tide thanks it is working now

crude solar
#

Hello i need help with hosting my website

#

uwsgi gives me error that i can't understand

#

this is error

twilit needle
#

can someone pls help me here?

#

thanks a lot!

onyx flume
#

hey

#

i already have something like 70tables that only main admin can access to

#

but i have to devide them somehow because thats too ugly if i show up 70models under one app name

gaunt marlin
onyx flume
#

ty

barren swift
#

Can someone tell what's wrong with this jQuery code?

#
var arr = [5, 4, 3, 2, 1, 0];
    $(".countdown").each(function (index) {
      console.log(index);
      $(this).html(arr[index]);
    });

// Logs `0`
// h1 with a value of 5.  No rewritting

/* HTML
<h1 class="countdown"></h1>
*/
#

I just want a basic countdown, counting from 5 to 0.

visual fulcrum
#

I would help u but jquery is not my thing...

gaunt marlin
barren swift
#

I think forEach() is not included in jQuery but I figured it out anyways. I used setInterval() and conditional statements.

gaunt marlin
#

that sound like much more hard work then using sleep()

barren swift
#

I didn't know about sleep() lol.

gaunt marlin
#

well it's basic stuff in JS 😕

barren swift
#
var arr = [5, 4, 3, 2, 1];
    var i = 0;

    timer = setInterval(function () {
      if (i < arr.length) {
        $(".countdown").html(arr[i]);
        i++;
      } else {
        clearInterval(timer);
        $(".countdown").remove();
        $('<img src="https://i.gifer.com/7b7F.gif" id="rickroll-img">').appendTo("body");
      }
    }, 750);
gaunt marlin
#

lol you can just set default value of i =5 or something, loop each and i-- . Don't even need to use array

barren swift
#

Yeah I know

#

thanks anyway

quick bay
#

Hey, I am new to web development and Django and am trying to make a login/register system. I do not want to use Django's built in system, so that I can learn and also understand how to do the same for other apps I create in the future. I have a template created but am unable to find a way to save the data a user enters. It would be great if someone could help me out with saving this data. (I am using bootstrap)

Template(register.html):
<nav class="mx-auto card w-25" style=text-align:center;border:none;padding-top:12%>
<form action="." method="POST">{% csrf_token %}
<h3 style="padding-bottom: 10px">Register</h3>
<div class="form-group">
<input type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Username" required>
</div>
<div class="form-group">
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password" required>
</div>
<div class="form-group">
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Repeat Password" required>
</div>
<button type="submit" class="btn btn-primary btn-lg btn-block">Register</button>
</form>
<p style="text-align: left">Already registered? <a href="{% url 'user_system:login' %}">Login</a></p>
</nav>

views.py:
return render(request, 'user_system/register.html')

models.py:
class userss(models.Model):
username = models.TextField()
password = models.TextField()

gaunt marlin
quick bay
#

I will read through once again, but last time I did I didnt find anything useful

gaunt marlin
open owl
#

i bet you should learn how to handle forms first.....youtube, google, read some docs

quick bay
#

Alright thanks

gaunt marlin
#

@quick bay you probably missed this part in that docs where they described how to get data from your form

from django.http import HttpResponseRedirect
from django.shortcuts import render

from .forms import NameForm

def get_name(request):
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = NameForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            # process the data in form.cleaned_data as required
            # ...
            # redirect to a new URL:
            return HttpResponseRedirect('/thanks/')

    # if a GET (or any other method) we'll create a blank form
    else:
        form = NameForm()

    return render(request, 'name.html', {'form': form})
quick bay
#

Thanks a lot @gaunt marlin. I'll read through and try making some changes

gaunt marlin
#

@quick bay in your html the form need to have action url to your views url -> this part <form action="." after that you can get the data from request.POST['your_input_name'] in the views.py

native tide
#

someone know how to make a web server

#

a secured one?

#

dm me

#

i need it rn

vernal furnace
#

man why this is not working

def todo_add(request):
    added_date = timezone.now()
    content = request.POST["content"]
    print(added_date)
    print(content)
    return render(request, 'todo.html')
#
<form action="todo/" method="post" class="form-inline">
                <input type="text" name="content" class="form-control mb-2 mr-sm-2" placeholder="Jane Doe">
                <button type="submit" class="btn btn-primary mb-2">Submit</button>
            </form>
#

that was todo.html

#

It says theres problem in views.py

content = request.POST["content"]
#
MultiValueDictKeyError
dense slate
#

what's your forms.py look like @vernal furnace

#

and what's the whole traceback

vernal furnace
dense slate
#

You need a forms.py to validate your form.

vernal furnace
#

ohh man the tutor made a models.Model

#

lemme make a form

dense slate
#

You'll also need your view to handle it correctly. That doc should have the info you need.

vernal furnace
#

the problem is not here

#

When I click submit

#

I want it to reload the page

#

the tutor made it reload the page in a stupid way

#

it doesn't work properly to me

dense slate
#

reload the page with new information?

vernal furnace
#

no the same page

dense slate
#

So just page refresh when you press a button?

vernal furnace
#

yea(for now)

#

I just want to test if input is receiving data or not

dense slate
#

You could just link the button to that page.

#

so <a href="{% url 'your_url' %}"><button>Press Here</button></a>

#

or just do:

def todo_add(request):
    return render(request, 'todo.html')
#

and link the button to the function

vernal furnace
#

wait

#

@dense slate that's how views.py looks rn

from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
from .forms import todo
from django.utils import timezone

@csrf_exempt
def todo_add(request):
    added_date = timezone.now()
    content = request.POST.get("content", False)
    print(added_date)
    print(content)
    return render(request, 'todo.html')
#

and that's forms.py

from django import forms

class todo(forms.Form):
    added_date = forms.DateTimeField
    text = forms.CharField(max_length=255)
#
{% extends 'base.html' %}

{% block content %}
    <div class="row mt-4">
        <div class="col">
            <h2>Add Item</h2>
            <form action="add_todo/" method="post" class="form-inline">
                <input type="text" name="content" class="form-control mb-2 mr-sm-2" placeholder="Jane Doe">
                <button type="submit" class="btn btn-primary mb-2">Submit</button>
            </form>
        </div>
    </div>
{% end block %}
#

that was todo.html

dense slate
#

You're missing things you need from forms.py and your view. Go look at the link I sent you.

vernal furnace
#

ok

native tide
#

Please I need help I maked a multiple choice quiz without a GUI but I need to make one that has a GUI?

#

if im looking into start python web developement, what other languages do i need to know except python

#

and html

dense slate
#

none, but css and javascript will be helpful sometimes.

vernal furnace
#

so demi I made some changes

#

but its still not working

native tide
#

hm ok, also do you know any docs and yt's that i can watch to learn python website dev

vernal furnace
#

Do u want to see?

dense slate
#

Djangogirls tutorial is really good. One of the first ones I did.

native tide
#

Should i do Django or Flask

dense slate
#

Your choice. Django has more stuff built-in.

#

Flask is just leaner. I don't know much about Flask.

native tide
#

k

#

would you recommend Django i guess

dense slate
#

I really enjoy using it, yea.

native tide
#

ok.

vernal furnace
#

You can easily find job with django too

native tide
#

oo ok

vernal furnace
#

oh god im so lost

native tide
#

idk

#

do i need xamp

vernal furnace
#
def todo_add(request):
    if request.method == 'POST':
        form = todo(request.POST)

        if form.is_valid():
            added_date = timezone.now()
            content = request.POST.get("add_todos", False)
            print(added_date)
            print(content)
            return render(request, 'todo.html')
    else:
        form = todo()
        return render(request, 'todo.html', {'form': form})
#

my code is a mess, im lost between the tutorial and the doc lol

dense slate
#

Your form is probably not valid and so you're not getting to any return statement.

#

DId you fix your forms.py? You were missing things there.

#

like meta

vernal furnace
#
from django import forms

class todo(forms.Form):
    added_date = forms.DateTimeField
    text = forms.CharField(label="add_todos", max_length=255)
#

nope

#

I saw meta once but I don't know what it is

dense slate
#

I don't think it's necessary actually.

vernal furnace
#

do u know what is the problem?

#

I think its between the url and todo.html

dense slate
#

Put a different print('something') after each if and see what it prints.

vernal furnace
#

it didn't print anything

#
def todo_fun(request):
    print("hello")
    return render(request, 'todo.html')

@csrf_exempt
def todo_add(request):
    if request.method == 'POST':
        form = todo(request.POST)
        print("if1")

        if form.is_valid():
            print("if2")
            added_date = timezone.now()
            content = request.POST.get("add_todos", False)
            print(added_date)
            print(content)
            return render(request, 'todo.html')
    else:
        print("else2")
        form = todo()
        return render(request, 'todo.html', {'form': form})```
#

the django debugger says

ValueError at /todo/add_todos/
The view todo.views.todo_add didn't return an HttpResponse object. It returned None instead.
Request Method:    POST
Request URL:    http://127.0.0.1:8000/todo/add_todos/
Django Version:    3.1.4
Exception Type:    ValueError
Exception Value:    
The view todo.views.todo_add didn't return an HttpResponse object. It returned None instead.
Exception Location:    D:\python\lib\site-packages\django\core\handlers\base.py, line 307, in check_response
Python Executable:    D:\python\python.exe
Python Version:    3.8.6
Python Path:    
['D:\\Eshop\\pyshop',
 'D:\\python\\python38.zip',
 'D:\\python\\DLLs',
 'D:\\python\\lib',
 'D:\\python',
 'C:\\Users\\Fw admin\\AppData\\Roaming\\Python\\Python38\\site-packages',
 'D:\\python\\lib\\site-packages',
 'D:\\python\\lib\\site-packages\\win32',
 'D:\\python\\lib\\site-packages\\win32\\lib',
#

value error at /todo/add_todos :/

#

I saw the console

#

it didnt print anything

dense slate
#

Oh, your form also is not referencing a correct URL.

icy basalt
#

Is javascript necessary for web development?

dense slate
#

it should be {% 'your_url' %} in the action

vernal furnace
#

Ayyy it gave me if1

dense slate
#

@icy basalt No, but you won't get much farther than basic html without it.

icy basalt
#

What do I need to learn for web development?

dense slate
#

@vernal furnace Yea do you are getting the POST through but it's not valid. What's the error now

icy basalt
#

Html5, css, and what else?

vernal furnace
#

still the same error

#

how to validate it

#

I don't want to create another html tho

dense slate
#

@vernal furnace Did you import your form.py class? Don't they need to be capitalized?

vernal furnace
#

@icy basalt Django Or Flask if u are interested in python, and React.js if u are interested in Javascript

#
from .forms import todo
dense slate
#

@icy basalt Yea, React, Angular, or Vue are the main front end choices.

vernal furnace
#

isnt that how u import it? @dense slate

dense slate
#

Todo should be capitalized in the forms.py and when you import

vernal furnace
#

yep

#

still the same error

#

do u want me to show the urls.py and todo.html?

dense slate
#

Put this outside your second if, and before the else:
return render(request, 'todo.html')

#

that will at least return it

#

but your form is not valid for some reason

#

You can use print() to help yourself debug things.

#

oh, you're trying to collect date in your forms.py, but you don't have a date field in your form.

vernal furnace
#

OHHHHHHHHHHHHHHHH

#

the paras are missing

dense slate
#

That's why it's not validating.

#

You also have text= in your forms.py, but your form has a field called "content"

#

You need to match those. This is why some tutorials might help you get the basics here.

vernal furnace
#

lol still the same error

#
ValueError at /todo/add_todos/
The view todo.views.todo_add didn't return an HttpResponse object. It returned None instead.
#
def todo_add(request):
    if request.method == 'POST':
        form = Todo(request.POST)
        print("if1")

        if form.is_valid():
            print("if2")
            added_date = timezone.now()
            text = request.POST.get("add_todos", False)
            print(added_date)
            print(text)
            return  render(request, 'todo.html')
    else:
        print("else2")
        form = Todo()
        return render(request, 'todo.html', {'form': form})
#

something is wrong

#

Its mainly because im confused

#

the tutor was so bad man he confused everything I learned

dense slate
#

in your second if statement, unindent the return once

#

are you getting it to print "if2"?

vernal furnace
#

nope it printed if1

dense slate
#

so it's still not valid, change the first print to print(form)

#

see where your error is

vernal furnace
#

no no its valid now

#

I mean it returned me

dense slate
#

if you're not getting "if2" it's not valid

vernal furnace
#

It returned me to the add_todo/ path

dense slate
#

unindenting the return just removed it from the if and now doesn't require it to be valid

vernal furnace
#

oh yea

#

ok now it gave me something new

#
[22/Dec/2020 16:01:46] "GET /todo/ HTTP/1.1" 200 2722
<tr><th><label for="id_added_date">Added date:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="added_date" required id="id_added_date"></td></tr>
<tr><th><label for="id_text">add_todos:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="text" maxlength="255" required id="id_text"></td></tr>
[22/Dec/2020 16:01:48] "POST /todo/add_todos/ HTTP/1.1" 200 2722
#
{% extends 'base.html' %}

{% block content %}
    <div class="row mt-4">
        <div class="col">
            <h2>Add Item</h2>
            <form action="add_todos/" method="post" class="form-inline">
                <label for="add_todos/">Your name: </label>
                <input id="add_todos" type="text" name="add_todos" value="{{ text }}" class="form-control mb-2 mr-sm-2" placeholder="Jane Doe">
                <button type="submit" value="OK" class="btn btn-primary mb-2">Submit</button>
            </form>
        </div>
    </div>

    <div class="row">
        <div class="col">
            <ul class="list-group">
                <li class="list-group-item">Cras justo odio</li>
                <li class="list-group-item">Dapibus ac facilisis in</li>
                <li class="list-group-item">Morbi leo risus</li>
                <li class="list-group-item">Porta ac consectetur ac</li>
                <li class="list-group-item">Vestibulum at eros</li>
              </ul>
        </div>
    </div>
{% endblock %}
#

that's how my todo.html looks

#

I'm 100% sure the problem is here

near bison
#

how to sent csrf with a fetch() POST request ?

#

Django

crude solar
#

ValueError: 'myproject.sock' is not a socket
how do i solve this

#

i am using gunicorn

dense slate
#

You're still trying to get date. Did you remove that?

vernal furnace
#

Ok so I removed added date completely

#

the page is not validating

#
The view todo.views.todo_add didn't return an HttpResponse object. It returned None instead.
#

There was a bug in my form a week ago, It was one line of code and I had to struggle 3 days to fix it

#

hope this one is not the same lol

inland stirrup
dull tartan
#

has anyone of u made a spam classifier

#

@dense slate

plucky tapir
#

Just wanted to say thanks guys I asked questions frequently throughout the semester. I had no web development experience and had a huge project, this place kept me from flying off the loose end

native tide
#

@vernal furnace What is the issue you're having?

fallen spoke
#

what is the difference between HS256 and RS256 for JWT? Is one more secure than the other? should I use one over the other? also what do the numbers signify? there are versions with 512 instead of 256.

native tide
#

any reason you chose JWTs over cookies?

midnight needle
#

does django use processes or threads for handling "threads"?

copper lagoon
iron beacon
#

Hey everyone

#

I'm wondering what is the best practices to unit test file fields in a Django Application

#

I'm building a project that uses Azure Storage, but I wish there was a way to use the default system storage when testing.

#

anyone knows how can I accomplish this?

vernal furnace
#

@native tide Hope u are here, my problem is the form is not validating

native tide
#

Yeah I'm here (kinda), what's the error message?

vernal furnace
#
ValueError at /todo/add_todos/
The view todo.views.todo_add didn't return an HttpResponse object. It returned None instead.
native tide
#

And your view?

vernal furnace
#
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from .forms import Todo
from django.utils import timezone

def todo_fun(request):
    print("hello")
    return render(request, 'todo.html')

@csrf_exempt
def todo_add(request):
    if request.method == 'POST':
        form = Todo(request.POST)
        print(form)

        if form.is_valid():
            print("if2")
            text = request.POST.get("add_todos", False)
            print(text)
            return  render(request, 'todo.html')
    else:
        print("else2")
        form = Todo()
        return render(request, 'todo.html', {'form': form})
native tide
#

Did you remember to include the csrf token in your form

vernal furnace
#

no

native tide
#

Oh its csrf exempt

vernal furnace
#

so should I?

#
{% extends 'base.html' %}

{% block content %}
    <div class="row mt-4">
        <div class="col">
            <h2>Add Item</h2>
            <form action="add_todos/" method="post" class="form-inline">
                <label for="add_todos">Your name: </label>
                <input id="add_todos" type="text" name="add_todos" value="{{ text }}" class="form-control mb-2 mr-sm-2" placeholder="Jane Doe">
                <button type="submit" value="OK" class="btn btn-primary mb-2">Submit</button>
            </form>
        </div>
    </div>
{% endblock %}
#

that's how todo.html looks

native tide
#

you should (generally speaking), but it won't change the error you're getting.

Could you try this?

def todo_add(request):
        if request.method == "POST":
            form = Todo(request.POST) # this "inserts" the POST data into this form instance, which then can be used to check whether it's valid or not
            if form.is_valid():
              # do what you want with the form's data

            else:
              errors = form.errors
              print(errors)
              # show forms errors

        else:
          form = Todo()
        return render(request, 'todo.html', {'form': form})

# make sure you're returning something within the if statements too.
#

btw I don't work with Django forms but can't you render it into your template without having to write all the HTML yourself?

vernal furnace
#

wait its giving me syntax error at the else:

native tide
#

my indentations are wrong

vernal furnace
#

nvm fixed it

dense slate
#

@vernal furnace You still have that return statement indentation that I told you to remove before.

#

It's not validating, and you are not getting to the "else" part of the statement.

#

Therefore it doesn't hit any return statement.

vernal furnace
#

I removed it but I thought it was for test purposes

dense slate
#

No, unindenting it is the right move, but you have a validation problem to fix.

#

Print your form and look at which item it is saying "blah blah is required"

#

That is what is invalidating the form.

native tide
#
{% extends 'base.html' %}

{% block content %}
    <div class="row mt-4">
        <div class="col">
            <h2>Add Item</h2>
            <form action="add_todos/" method="post" class="form-inline">
                <label for="add_todos">Your name: </label>
                <input id="add_todos" type="text" name="add_todos" value="{{ text }}" class="form-control mb-2 mr-sm-2" placeholder="Jane Doe">
                <button type="submit" value="OK" class="btn btn-primary mb-2">Submit</button>
            </form>
        </div>
    </div>
{% endblock %}

Is this writing your own form? Shouldn't the form instance be passed through the context? Otherwise it will never validate

dense slate
#

Yea, why is "action" still not using your URL like we talked about?

vernal furnace
#

Its?

dense slate
#

although

#

Might not be necessary. Maybe you can route that way.

#

It is? Ok, because it's not showing it above. Unless that's the old code.

vernal furnace
#

I just want to get it working now, its another problem (action="add_todos/")

native tide
#

But can you correct me on this... how is that HTML bound at all to your form instance

#

How would you view know if the form is being submitted if it's not being rendered in your template

#
<form action="/your-name/" method="post">
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="Submit">
</form>
dense slate
#

Yea, Nut is right. I am used to using widget-tweaks so I thought he was doing it manually.

#

You can just use {{form}} to make it easier.

native tide
#

Because he passed form in the context and then did not use it in the template, so it will always be invalid.

If they want to stick with their custom form I think they need an API to handle the validation

#

which is more work than required 🙂

dense slate
#

That might be my fault. I don't think he had it setup that way originally but I sent him to the forms docs.

vernal furnace
#

Wait guys

dense slate
#

But that still is the way it should be done with forms.

vernal furnace
#

why do I have to validate my form?

dense slate
#

I don't think you have to, I am so used to doing that with every form that I forgot you can probably skip that step.

#

Sorry!

native tide
#

Well, in this case you are trying to validate your Todo form, and that may have some validators such as required=True, so you have to ensure that your inputs are valid or the form will not submit

vernal furnace
#

So should I skip the problem or fix it?

#
<li>This field is required.</li>
#

it says this fieldd is required @dense slate

#
<li class="list-group-item">{{ text }}</li>
native tide
#

Well you can't "skip" the problem, that is the problem

#

@vernal furnace do you understand why your form is not validating?

vernal furnace
#

no

#

that's why I can't fix the problem

native tide
#

Ok so tell me if you don't understand this, I'll try to explain:

You're trying to validate your form when you say form.is_valid().
What is the form you might ask?

form = Todo()
It's an instance of your Todo() form.

So for the view to be able to validate the form, it must be rendered. But you are not rendering your form, you are rendering something else with the HTML you sent. The form in your HTML does not correspond to the Todo() instance so it will never validate.

vernal furnace
#

How to make it respond?

native tide
#

Well you have to render the form. So remove the HTML you have

#

You understand that right?

vernal furnace
#

No lol

#

I mean how do u want me to render the form If I remove the html

native tide
#

Talk me through which parts you aren't getting

vernal furnace
#

so do u want me to remove "todo.html" from return render?

native tide
#

No.

#

The form that you wrote in the HTML is not at all linked to the Todo() instance

#

When you say form = Todo() and then check its validity with form.is_valid() that form is the Todo() instance. You're trying to submit a different form and the view doesn't know what it is.

#

Here's a good time to read through the docs and watch a YT video on django forms

#

But above in the text I've shown how to fix it

#

You wrote the Todo form right? So then all you have to do is render it.

vernal furnace
#

wait I think its working

#

when I click submit

native tide
#

huh 🤔

#

so what did you change

vernal furnace
#

when I click submit it sends me to add_todo/

#

its doesn't give me value error

#

idk while u were talking with demi I did some stuff

#
def todo_add(request):
    if request.method == 'POST':
        form = Todo(request.POST)
        print(form)

        if form.is_valid():
            print("if2")
            text = request.POST.get("add_todos", False)
            context = {
                "text": text
            }
            print(text)
            return  render(request, 'todo.html', context)
    else:
        print("else2")
        form = Todo()
    return render(request, 'todo.html')
#

oh

#

I have to remove return render right?

native tide
#

so is your form validating now?

vernal furnace
#

look

#

if I indent the last render under else

#

it will give me value error

#

if I keep it outside else it will work fine

#

I mean idk how fine it is, since it doesn't return any value to me lol

fresh sand
#

how do i pass a bool in a post req

native tide
#

yeah it gives you a value error because your form is not validating

fresh sand
#
    premium = request.form.get("premium", type=bool)
#

this doesnt work

native tide
#

you submit your "form - which is not linked to your Todo instance", it redirects to your add_todos/ with a POST request. But, your form is not valid and there is no else statement to return anything.

fresh sand
#

and if i remove type=bool it makes it a str

vernal furnace
#

how to link it

#

you told me to render it

fresh sand
#

any flask person here?

native tide
#

You've already linked it, form = Todo(), I've explained that, now you have to render it, which I have explained too above

#

@fresh sand what doesn't work about it, is premium null?

fresh sand
#

if i make it type=bool yes

#

it makes it None

native tide
#

Can you print the request data that you're sending?

fresh sand
#
def updateCreds(
    uid,
    avatarUrl,
    email,
    userName,
    followers,
    following,
    moderator,
    premium,
    notifications,
    profession,
    token,
    verified,
    notification,
    posts
):
    uid = request.form.get("uid")
    avatarurl = request.form.get("avatarurl")
    email = request.form.get("email")
    premium = request.form.get("premium", type=bool)
    followers = request.form.getlist("followers")
    following = request.form.getlist("following")
    moderator = request.form.get("moderator", type=bool)
    notifications = request.form.get("notifications", type=bool)
    profession = request.form.get("profession")
    token = request.form.get("token")
    verified = request.form.get("verified", type=bool)
    notification = request.form.getlist("notification")
    posts = request.form.getlist("posts")

    listAll = {
        'avatarurl': avatarurl,
        'email': email,
        "followers": followers,
        "following": following,
        "moderator": moderator,
        "notification": notification,
        "notifications": notifications,
        "posts": posts,
        "premium": premium,
        "profession": profession,
        "token": token,
        "userName": userName,
        "verified": verified,
        'uid': uid,
    }

    try:
        print(notification)
        for key, value in listAll.items():
            if value is not None and key != "uid":
                users.update_one({"uid": uid}, {"$set": {key: value}})
        # print(users.find({"uid": uid}))
        # return "hwello"
        return pjson({"data": list(users.find({"uid": uid}))})
        if uid is None:
            return {"error": "must provide uid"}
    except Exception as e:
        return jsonify(
            {
                "status": "error", "error": e
            }
        )

this is the complete function

copper lagoon
#

hey, with flask, using <var> and getitng var in def routevar(var): breaks the page! anyone got any ideas?

native tide
#

do all of the other variables w/ type=bool work?

vernal furnace
#

{{ form }} you mean rendering it like this?

native tide
#

yes

fresh sand
#

@native tide no

native tide
#

!code

lavish prismBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

fresh sand
#

none of em works

#

but I want it to be bool

vernal furnace
#

but where would I render it, I have some code there already

native tide
#

Ok, so I'd suggest printing your request to see what datatype they are. I think they are strings in this case within the JSON

vernal furnace
#

like just type {{form}} in the middle of todo.html lol

native tide
#

@vernal furnace what code is there already?

vernal furnace
#
{% extends 'base.html' %}

{% block content %}
    <div class="row mt-4">
        <div class="col">
            <h2>Add Item</h2>
            <form action="add_todos/" method="post" class="form-inline">
                <label for="add_todos">Your name: </label>
                <input id="add_todos" type="text" name="add_todos" value="{{ text }}" class="form-control mb-2 mr-sm-2" placeholder="Jane Doe">
                <button type="submit" value="OK" class="btn btn-primary mb-2">Submit</button>
            </form>
        </div>
    </div>

    <div class="row">
        <div class="col">
            <ul class="list-group">
                <li class="list-group-item">{{ text }}</li>
              </ul>
        </div>
    </div>
{% endblock %}
native tide
#

Why do you need that form, what purpose does it serve

fresh sand
#

yes if i remove type=bool and make it

    premium = request.form.get("premium")

it makes it string

#

which i dont want

native tide
#

Yeah, so your form is sending data as a string. Are you using WTforms?

vernal furnace
#

Its the whole page html @native tide

native tide
#

But... why do you need that form that you wrote in HTML?

#

I've explained why in this case it serves 0 purpose

vernal furnace
#

oh its because when I type it receives data

copper lagoon
#

hey, with flask, using <var> and getitng var in def routevar(var): breaks the page! anyone got any ideas?

native tide
#

But... that's the wrong form. You have to render {{form}} and not that HTML form, it serves no purpose. This is what I'm trying to explain, you understand right?

vernal furnace
#

so ill create a whole new html file?

native tide
#

@copper lagoon so you passed a var, did you change the URL to reflect that?

copper lagoon
#

ye

#

the page works, but the interactive stuff doesnt

#

lemme get pics

native tide
#

@vernal furnace Why would you create a new html file

vernal furnace
#

then where do I pass {{form}} ;-;

native tide
#

You need to render {{form}} instead of the form you wrote in html

#
<form action="some action" method="post">
<!-- csrf token usually goes here -->
  {{form}}
</form>
copper lagoon
#

clicking nothing happens @app.route("/<log>/<pog>/test") def _45589675(log, pog): return render_template("profile.html") but and same issue happens when i have more than 1 argument

#

this works

#

if i have like /pog/log/test

#

same output

vernal furnace
#

I don't get you

#

Do you want me to create a form under the form in my html file

#

Like

native tide
#

Why are you trying to create 2 forms

#

One of your forms is invalid

#

Get rid of it

#

And replace it with the valid one, {{form}}

vernal furnace
#

I only have 1 form

native tide
#

Ok can you show us the code for your Todo form?

vernal furnace
#
from django import forms

class Todo(forms.Form):
    text = forms.CharField(label="add_todos", max_length=255)
lavish prismBOT
native tide
#

Ok, there's one form. You have another which you wrote in HTML (which is the invalid one), so you have 2

#

Now get rid of the invalid one, and replace it with {{form}}

vernal furnace
#

Bruhhh thats html file

native tide
#

@copper lagoon Tbh I don't know why that doesn't work, is profile.html dependent on log or pog?

copper lagoon
#

this is just an example

#

but yes imagine it would be

vernal furnace
#

If i remove it the text will go to nowhere and it will not trigger the todo_add function

native tide
#

and you passed log and pog into the template as template variables right?

copper lagoon
#
def _45589675(log, pog):
    return render_template("profile.html")```
#

yes

native tide
#

you didn't though

copper lagoon
#

oh

#

ye i didnt pass

#

does it matter?

#

bc i would

#

this is just a test route

native tide
#

well, if the template is trying to access log or pog and you didn't pass them, it can't access them so it would be an issue

copper lagoon
#

ik

#

that isnt the issue

native tide
#

apart from that I actually don't know what could be the issue

#

might need to see the real thing to grasp what's going on

#

because from the example that's the only thing I can see.

#

@vernal furnace so can you explain what you think you need to do at this moment in time?

vernal furnace
#

I don't know, I literally don't understand anything you are saying

#

You are saying I have 2 forms

native tide
#

Yep.

vernal furnace
#

Which one ia the second one?

#

Is

native tide
#

Well, which do you think is your first one?

vernal furnace
#

My first one is todo

#

form = todo()

native tide
#

Yep, which is this:

from django import forms

class Todo(forms.Form):
    text = forms.CharField(label="add_todos", max_length=255)
#

Then look in your HTML file

#

You have another form

vernal furnace
#

<form>?

#

Isnt this an html tag?

native tide
#

Paste it

#

Yeah that's a HTML tag, that represents another form.

#

And that form which you have in the HTML is not linked to your form=Todo()

vernal furnace
#
<div class="row mt-4">
        <div class="col">
            <h2>Add Item</h2>
            <form action="add_todos/" method="post" class="form-inline">
                <label for="add_todos">Your name: </label>
                <input id="add_todos" type="text" name="add_todos" value="{{ form }}" class="form-control mb-2 mr-sm-2" placeholder="Jane Doe">
                <button type="submit" value="OK" class="btn btn-primary mb-2">Submit</button>
            </form>
        </div>
    </div>  
native tide
#

Yep there's your other form

#

So get rid of everything between the <form> tags

#

and replace everything between those tags with {{form}}

#

and make sure you pass {"form": form} in your context

vernal furnace
#

But how will I type input?

#

Its for styling

native tide
#

You need to give these a read and watch a yt video if you don't get it

#

Get the right form rendered first, then worry about styling

#

the form you wrote in the HTML will never validate when you say form.is_valid because what you wrote in the HTML is not form!!! it is not a Todo instance!

vernal furnace
#

so that's how it should look?

<form action="add_todos/" method="post" class="form-inline">
                {{ form }}
            </form>
native tide
#

and add a submit button

vernal furnace
#
<form action="add_todos/" method="post" class="form-inline">
                {{ form }}
                <button type="submit" value="OK" class="btn btn-primary mb-2">Submit</button>
            </form>```
native tide
#

sure

vernal furnace
#

Idk where to type

#
def todo_add(request):
    if request.method == 'POST':
        form = Todo(request.POST or None)
        print(form)

        if form.is_valid():
            print("if2")
            text = request.POST.get("add_todos", False)
            context = {
                "text": text
            }
            print(text)
            return render(request, 'todo.html', context)
    else:
        print("else2")
        form = Todo()
        context = {
                "form": form
            }
        return render(request, 'todo.html', context)
#

so wait

#

Hope you didn't ragequit ;-;

#

Thank you tbh, you stayed with me 2 hours ❤️

tacit barn
#

What would be a good data structure with python to capture the directed graph as generated by a moderately sized (less than 10,000 notes) directy graph (let's say up to around 5 edged between any two graphs) wiki database (think of the graph generated by the Wikipedia pages on a certain subject and all its interlinks)?

#

And so some searching and graph manipulation with it

copper lagoon
#

@native tide ```py
@app.route("/profile/view/<id>/")
@requires_authorization
def seeprofile(id):
user = discord.fetch_user()
name = f"{user.name}#{user.discriminator}"
avatar = user.avatar_url

return render_template("showprofile.html", user=name, avatar=avatar, id=id)```
#

this is one of the ones that dont work

#

as u can see, nothing is different here / its meaningless

#

like the buttons dont work

#

and i suspect its due to the route

vestal hound
#

look into networkx

copper lagoon
#

does the amount of "args" in a flask route make a difference?
im having an issue where having more than 1 argument breaks the page, and same with having any variables

native tide
#

@copper lagoon I've never had an issue with multiple variables in the route. One thing that you could try (but probably won't make a difference) is setting the type of the variable.

e.g. ```py
@app.route("/profile/view<int: id>/<path: username>/")

copper lagoon
#

like i cant even have more than 1 arg in the page

native tide
#

so you can't pass more than 1 variable to your template?

copper lagoon
#

not even

#

i cant have more than one /test/

#

like /test/test/

#

breaks it

native tide
#

oh, so even if it's static like /path/example/ it won't work?

copper lagoon
#

mhm

native tide
#

that's really weird

#

but you are visiting the route right? in your logs you get 200 response status' when you visit the page?

copper lagoon
#

yes

#

lmk if u want pictures

#

and the route is just /poggers/

#

it works

#

but when the route is /poggers/something/

#

it doesnt

#

and a var is the same as "something" in this way

#

so it just stops

#

/ doesnt work

native tide
#

so just / as the route doesn't work either?

copper lagoon
#

gimme a min

#

just / works fine

tacit barn
#

Okay yeah I've playfully used networkx before, although I don't know if it can conveniently search things

native tide
#

@copper lagoon Nothing about the route seems to scream "I'm broken", could this be something to do with auth?

copper lagoon
#

ive been testing it with this

#
def testtestlog():
    return render_template("control_panel.html")```
#

and no route needed

#

no auth*

#

look u seem to be really helpful

#

would you want me to send u the website?

#

so u can actually see what i mean?

#

tho i gtg eat rn

#

ill be back in a bit, want me to ping u?

native tide
#

You could, but I actually have 0 idea why there's such a problem, I've never ran into it before and I couldn't find anything online about it

#

sure

#

maybe show the html file to check if there's anything out of the ordinary

copper lagoon
#

well i mean u can just check the inspect element

#

i can tho

#

like this

#
                          <span class="alert-text"><b>Vanity URL Updated!</b></span>
                          <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                              <span aria-hidden="true">&times;</span>
                          </button>
                      </div>```
#

this is the alrt

#

lemme get u the css

#
.alert
{
    position: relative;

    margin-bottom: 1rem;
    padding: 1rem 1.5rem;

    border: 1px solid transparent;
    border-radius: .375rem;
}```
#
.alert-success
{
    color: #fff;
    border-color: #2dce89;
    background-color: #2dce89;
    color: #FDFEFC;
}```
#
{
    padding-right: 4.5rem;
}```
#

.alert-dismissible

#
{
    position: absolute;
    top: 0;
    right: 0;

    padding: 1rem 1.5rem;

    color: inherit;
}```
#
{
    transition: opacity .15s linear;
}```
#

.fade

#

i honestly think it COULD be the html

#

but i doubt it

#

cuz why would it work with 1 /thing/

#

but not 2

#

@native tide

dry bridge
#

anyone know how to use django

native tide
#

@copper lagoon do you have any jinja2 logic in your html file

#

@dry bridge of course

dry bridge
#

@native tide awesome, can you help me out with a problem im having

dry bridge
#

every time I try to add image to my html template the image comes up broken

#

and the css isn't working either. The background image isn't working either

native tide
#

ok have you specified STATICFILES_DIRS in your settings.py

copper lagoon
#

me?

dry bridge
#

@native tide i have in my installed_app section 'django.contrib.staticfiles',

#

and at the bottom

#
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'reviews/static')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'imagesite/media')
copper lagoon
#

look imma send u it

native tide
#

@dry bridge ok and when you attempt to provide the src for the image, do you do the following:

{% load static %}
<img src="{% static <your_path> %} > </>
dry bridge
#

yes

#
<img src="{% static 'logo.jpeg' %}" >```
native tide
#

alright, could you show us your filestructure?

#

imma head off for now its midnight so yea

dry bridge
#

what time zone are you in @native tide

native tide
#

GMT, I'll have a look at this tomorrow, see ya for now 🙂

dry bridge
#

😦 its due at midnight.. ET

#

thanks tho!

winter mason
#

idrk where to put this, this is probably the channel most closely related, how would you guys go about scraping a html <math> tag, and convert it to something wolfram alpha can understand?

marsh haven
#

Hi! is there a recommended directory structure for big projects using django, or everything (classes, business layer, access to a database) is supposed to be stored in views.py and model.py ?

dawn zinc
gaunt marlin
# marsh haven Hi! is there a recommended directory structure for big projects using django, or...
keen mason
#

can any of yall help me with selenium

hybrid bobcat
#

what might be the possible cause for this flask (werkzeug more specifically) error?
CSRF Warning! State not equal in request and response.
I am using the google api, and then after getting the consent from the user, I gonna get the authentication server response on the callback page after the consent screen then this happens

#

I'm running in development btw

gaunt marlin
#

@hybrid bobcat are you sure you using django with domain localhost name match with your google app redirect url?

hybrid bobcat
#

Sorry for the late response btw

hybrid bobcat
twilit needle
#

hello

#

I would like to use the django permissions system

#
class LocalRole(models.Model):
    """
    Represents a Local-Role object.
    An one-to-one related model with Global role.
    Roles have their own:
        - Hex Color Code [Integer Representation]
        - Name [&]
        - Permissions.

    Role permissions for individual datasheets override global parent permissions.
    """
    objects = RolesManager()
    id = models.BigAutoField(primary_key=True, db_index=True, editable=False, auto_created=True)
    global_role = models.OneToOneField('api_backend.GlobalRole', on_delete=models.CASCADE)
    parent = models.ForeignKey('api_backend.DataSheet', on_delete=models.CASCADE, db_index=True)
    created_at = models.DateTimeField(auto_now=True, editable=False, db_index=True)

    REQUIRED_FIELDS = [global_role, parent]

so I have this model

#

this model named role should have permissions

#

and these roles should be given to user

#
class GlobalRole(models.Model):
    """
    Represents a Global-Role object.
    Roles have their own:
        - Hex Color Code [Integer Representation]
        - Name [&]
        - Permissions.
    """
    objects = RolesManager()
    id = models.BigAutoField(primary_key=True, db_index=True, editable=False, auto_created=True)
    name = models.CharField(max_length=512, db_index=True)
    hex_color_code = models.IntegerField(db_index=True)
    position = models.IntegerField(db_index=True)
    parent = models.ForeignKey('api_backend.DataSheetsCluster', on_delete=models.CASCADE, db_index=True, editable=False)
    created_at = models.DateTimeField(auto_now=True, editable=False, db_index=True)

    REQUIRED_FIELDS = [name, parent, position]
#

how can I implement this?

#

can somebody please help?

#

thanks a lot! please ping me when help

twilit needle
wanton ridge
#

this is my code for my first diashow, i want to create more than one diashow how do i do it

granite loom
#
            <button>
                <a href="home.html"><img src="../images/logo/the_rationals.png" width=50></a>
            </button>
            <h1><strong>The Rationals</strong></h1>

this is my code, and
this is the result, is there a way to make it so that The Rationals would appear beside the picture

winter mason
coral raven
#

@granite loom make the image an h1 inline elements

granite loom
coral raven
#

add the image before h1 in html

granite loom
#

ah ok, thankyou

#

I apprecieate it

twilit needle
#

So I've got two models structed like:

class DataSheetsCluster(models.Model):
    """
    Represents a group of datasheets made by the owner.
    Has it's own icon, name and description.
    A parent can only have one owner at a time.
    """

    class Meta:
        permissions = [
            ('GLOBAL_READ_DATA', 'can read cluster data'),
            ('GLOBAL_WRITE_DATA', 'can write to cluster'),
            ('GLOBAL_MANAGE_CLUSTER', 'can manage cluster'),
            ('GLOBAL_MANAGE_FIELD_DATA', "can manage cluster's field data"),
            ('GLOBAL_MANAGE_DATASHEETS', "can manage cluster's datasheets"),
            ('GLOBAL_MANAGE_ROLES', "can manage cluster's roles"),
            ('GLOBAL_MANAGE_FIELDS', "can manage cluster's fields")
        ]
    ...
    roles = models.ManyToManyField('api_backend.Role')
    ...
class DataSheet(models.Model):
    """
    Represents a single dataSheet.
    dataSheets have their own model at the core. Model data is added to
    the dataSheets in the form of separate records.
    """

    class Meta:
        permissions = [
            ('LOCAL_READ_DATA', 'can read datasheet data'),
            ('LOCAL_WRITE_DATA', 'can write to datasheet'),
            ('LOCAL_MANAGE_FIELD_DATA', "can manage datasheet's field data"),
            ('LOCAL_MANAGE_ROLES', "can manage datasheet's roles"),
            ('LOCAL_MANAGE_FIELDS', "can manage datasheet's fields")
        ]

    ...
    roles = models.ManyToManyField('api_backend.Role')
    ...

I want to make sure that the DataSheet model's roles field reference the DataSheetsClusters model's roles field, like a foreign key. How can I achieve this? Can someone please help me?
Thanks a lot!

solar summit
#

hey I am trying to get a user's info with flask , well I read the discord's oauth2 docs & some stackoverflow and I somehow managed to get the access token from discord. Now I want to know how to fetch the user's data now with that access token. I couldn't find anything about how to fetch user object with the access token so I am completely struck here and Idk how to proceed .
Here's the code

from flask import Flask, render_template, request, session, redirect
from config import *
import requests
app = Flask(__name__)
API_ENDPOINT = 'https://discord.com/api/v6'
app.config["SECRET_KEY"] = "ac1bf18a8db34e15c2dba713802b347e89625413c4a31e53"


@app.route('/')
def homepage():
    return render_template('index.html', url=oauth_url)


@app.route('/callback')
def callback():
    code = request.args.get('code')
    data = {
        'client_id': client_id,
        'client_secret': client_secret,
        'grant_type': 'authorization_code',
        'code': code,
        'redirect_uri': redirect_uri,
        'scope': 'identify'
    }
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded'
    }
    r = requests.post('https://discord.com/api/v6/oauth2/token',
                      data=data, headers=headers)
    r.raise_for_status()
    session["token"] = r.json()["access_token"]
    return redirect("/dashboard")


@app.route("/dashboard")
def dashboard():
    return render_template('dashboard.html', )


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

if its off-topic here , please direct me where should I ask about this

ripe jasper
granite loom
#

Hey so

@import url('https://fonts.googleapis.com/css2?family=Lato:ital,wght@1,300;1,400&display=swap');

* {
    box-sizing: border-box;
    padding: 0;
    margin: 0
} 

body {
    font-family: 'Lato', 'sans-serif'
}

this is my css, but the font isn't changing why is that?

haughty turtle
haughty turtle
gaunt marlin
haughty turtle
haughty turtle
solar summit
haughty turtle
#

Ah ok

granite loom
marsh haven
compact lion
#

Does anyone have experience setting up an environment with flask and react, where react is precompiled to a static folder? I'm having issues setting up the react part

granite loom
#

hey how to remove the white spaces?
This was cause because of css, but i have a class for that logo only, but idk how to remove those white spaces

long ibex
#

Hi, how would I be able to wrap my check if user has access to document in a decorator ?

@documents_bp.route("/documents/<doc_id>", methods=["GET"])
@jwt_required
def get_one_document(doc_id: int):
    try:
        document = Document.get_by_id(doc_id)
    except Document.DoesNotExist:
        raise NotFoundError("Document not found.")
    if not document.owner.email == current_user.email:

        contributor_emails = [
            user.email
            for user in (User.select().join(DocumentContributors).join(Document).where(Document.id == document.id))
        ]
        if current_user.email not in contributor_emails:
            raise UnauthorizedError("User doesn't have access to this project.")
native tide
#

@compact lion did you use create-react-app?

compact lion
#

yeah, but I'm trying to turn each .jsx file in this folder into its own .html file @native tide

native tide
#

why would you want to do that? you're having an MPA with react?

compact lion
#

Well, we'd like to just have all files serverside-rendered, and running both flask and react servers would create another connection where things could break

native tide
#

Ok, but I don't think turning each .jsx file into their own .html file is how it works. Can't you just have a <script> tag in your server-side templates to have some React components in your templates?

#

You can just npm run build and then CRA will webpack your static files and then your backend can serve your index.html

#

Then the rest is handled by your frontend, like an SPA

#

Also with an SPA you aren't hosting your backend and your frontend separately, you just use your backend as an API. It's not really an extra connection which might break unexpectedly.

native tide
#

Hello, how to find with selenium the element, who's xPath changes everytime.

<button type="submit" class="wbutton btn btn-dark rounded-0 font-weight-bold p-2"><i class="fa fa-video-camera text-danger fa-lg"></i> 808</button>
fallen spoke
#

Please someone explain what is happening here:
print(user.active)
user.active = True
print(user.active)
first print is false, second print is true, but the database still shows false..... what am I doing wrong?

modest scaffold
#

your not saving it to the database

modest scaffold
fallen spoke
#

I am using django, Thank you so much, works now

modest scaffold
#

np

#

I need some help with django: I'm getting this error "NOT NULL constraint failed: homeworkApp_homework.object_id". I have a homework model that has a generic relation with a student model. I created a homework form from the model and am now trying to save it. I have this piece of code in the views ```python
form = homeworkForm(request.POST)
if form.is_valid():
#This tells the homework which student to relate itself with
form.cleaned_data['content_object'] = request.user.student
form.save()

native tide
#

do you have a student column for your User model?

modest scaffold
#

i have modified the abstract user

native tide
#

ok, and did you set that model as your DEFAULT_USER_MODEL?

modest scaffold
#

yee

#

oh wait no

#

i set it as my auth_user_model

native tide
#

for web dev do i have a choice in between java script and python

peak bronze
#

you do

#

at least for the backend

#

for the frontend, you dont have much of a choice

#

most people usually end up using javascript

native tide
#

okay, thanks

swift sky
#

is it possible to do single checkbox using wtforms?

#

i made a widget for multi check box already

modest scaffold
#

is this for django

modest scaffold
#

you know the way in django when you get a group of objects it returns it like this "<joe: joe1>" how does one remove the <> and joe bit

lofty matrix
#

You can access the field on the model and print that

native tide
#

@modest scaffold sorry I forgot to reply to your issue, did you get it fixed?

haughty turtle
#

@compact lion CRA is not what you want then, there are other packages to deploy react that will achieve what you want, just that it's not the norm not much documentation and I haven't tried it and others prob haven't either.

#

@native tide you ever got to use Session Storage in Django with React on the DB instead of using Cookies?

native tide
#

@haughty turtle Nope, you mean cookie-based sessions?

haughty turtle
native tide
#

Ah, no, I don't really fully understand it at the moment but I haven't looked into it that much. Rn I'm stuck on understanding the difference between session-based and token-based authentication. I think that session-based auth is just token + session information in a seperate cookie. Or something like that

#

I just used token auth for all of mine and it works fine

verbal snow
#
<select type="text" class="form-control" id="bot" name="bot" required>
  <option disabled value="Select a bot..." selected hidden>Select a bot...</option>
  {% for x in bots %}
  <option type="text" value="{{x.name}}">{{x.name}}</option>
  {% endfor %}
</select>
``` Is there a reason the select is not required?
#

Even with the required attribute

fallen peak
verbal snow
#

I don't know whats causing it

#

I remove the Select a bot... and its fine

#

No values fill up an option neither since theres no valid bots

native tide
#

@verbal snow Just a thought, I'm probably wrong, but would selected auto-select an option before the page loads, therefore making the select always required?

hollow scaffold
#

In django, does anyone know a trick to reboot a server?

i.e.

class MyModel(models.Model):
  ...
  def save():
    ...
    restart_server()

I've got a model who has fields in admin that show/hide depending on the status of another model. The fields in admin only update upon reboot. Maybe there is another trick?

modest scaffold
#

@modest scaffold sorry I forgot to reply to your issue, did you get it fixed?
No but it's fine

dawn heath
#

example I have the following models, and I want to parse 3 jsons with the following structure hhttps://dpaste.org/1zf2 ,and populate data over api or other without user interaction

vestal hound
#

you mean in production?

#

I don't think you can from within Django

native tide
#

i am trying to put this into html with flask, anyone know how ?for i in how_many: guess = input(f'input your '+ str(i) +' guest: ') for j in guess: your_answer.append(j) for l in range(0, len(your_answer)): your_answer[l] = int(your_answer[l]) @ me if you do please

twilit needle
#

can someone please help me? thanks!

native tide
#

does anyone know flask?

gaunt marlin
native tide
#

is there away to save input from html into a variable in pyhton flask

gaunt marlin
verbal snow
gaunt marlin
twilit needle
#

hello

#

can anyone help me like live?

#

wait I claim help channel

twilit needle
#

Hello!
So I am creating a roles and permissions system in django. I think that I need some help here,
So the basic concept is that:

  • there are objects known as clusters

  • clusters can have their own roles

  • members of the cluster are assigned roles.

  • roles also have a positional value,
    smallest positional value indicates highest role.

  • based on this certain permissions are determined for the user [member]
    I have implemented this a bit roughly, and think that I can improve a lot, maybe am using the wrong logic here.

here's my backend code:
https://mystb.in/JamaicaInclFinal.python
here are my models:
https://mystb.in/EthicalAlertWhom.python

the roles system is very similar to discord roles system.
So I have an object called cluster - referred to discord server
and an object called datasheet - referred to as discord channel

Datasheets have their own role overwrites too [role overwrite object given in above link], which can overwrite the permissions the roles have at cluster-level.
The main thing here is that for the positional value, each role can have only one unique positional value in its parent cluster.
so for every update to role positions, I am rotating the whole role positions for every role in the cluster [given in code link]
Is this the best way to go about this? can someone pls help me?
its going to take sometime to read my code, if you are willing to spare that time and help then thanks a lot!!

brittle basin
#

anyone who knows sql

#

in pyhton

#

python*

gaunt marlin
twilit needle
#

can someone pls help me

gaunt marlin
#

@twilit needle someone will help you if they know the answer

twilit needle
#

okay

native tide
#

how to get started on flask

gaunt marlin
native tide
#

k

grizzled meteor
#

for flask and sqlalchemy, is there a standard way to serialize sqlalchemy object to return a dictionary?

#

basically i performed a query, and want to get the output as a dictionary to send back as JSON

#
 @api.route('/send_dummy_data', methods=['GET', 'POST'])
def send_dummy_data():
    data = request.json
    print(data)
    # data_query = db.session.query(CableResistance).filter_by(size='12').first()
    data_query = CableResistance.query.filter_by(size='12').first()
    pdb.set_trace()
    return jsonify(data_query)``` something like this
#

where CableResistance is a sqlalchemy database model

gaunt marlin
#

basically you write a schema for the serialization

grizzled meteor
#

@gaunt marlin i am suprised sqlalchemy doesn't have a baked in solution already

gaunt marlin
grizzled meteor
#

i got an error when I tried to just use jsonify directly on the object

#

unless i was supposed to use it on a class attribute or i am just missing something

gaunt marlin
#

what is the error?

#

@grizzled meteor i think because you using filter it will return a list and that can't be jsonfy, you have to access index 0 of that list first

grizzled meteor
#

i did not realize the filter returns a list

#

and i also did not realize i cannot jsonify a list

#

good to know

#

TypeError: Object of type CableResistance is not JSON serializable

#

this was the error so that kind of lines up what you're saying

#

is 0 of that list; the first column in the "row"?

gaunt marlin
#

can you print out the query result?

grizzled meteor
#

"<CableResistance 7>"

#

basically '7' is the ID

gaunt marlin
#

so it's not a list but a class

grizzled meteor
#

yeah

from flask_sqlalchemy import SQLAlchemy
from .database import db

class CableResistance(db.Model):

   __tablename__ = "CableResistance"
   id = db.Column(db.Integer(), primary_key=True)
   size = db.Column(db.String(8))
   conductor_material = db.Column(db.String(2))
   conduit_material = db.Column(db.String(5))
   reactance = db.Column(db.Float(precision='5,3'))
   resistance = db.Column(db.Float(precision='5,3'))
gaunt marlin
#

jsonify is only use when you set the attribute for example jsonify(name="abc", description="a") because it's a wrapper of python json.dumps()

grizzled meteor
#

ah, i see

gaunt marlin
#

@grizzled meteor try this instead

from flask.json import dumps
....
#other codes
...
return dumps(data_query)
#
flask.json.dumps(obj, app=None, **kwargs)
Serialize obj to a JSON-formatted string.
grizzled meteor
#

same error, was expecting that though

gaunt marlin
#

the top answer even suggest it 🙂

grizzled meteor
#

i'll look into it

#

didn't think i'd have to look into it this much though

gaunt marlin
#

for single instance of class one of the answer

def serialize(self):
        return {c: getattr(self, c) for c in inspect(self).attrs.keys()}

for the class itself, for list query you have to write different implementation :/

grizzled meteor
#

i might just be lazy

#

and use that

#

method

#

lol

gaunt marlin
#

actually marshmallow is really easy to use

#

the docs is not that long to read either

static pasture
#

Hello!!! I want to start learning about interactive web, particularly with python. Any advice to begin? Or maybe sources like a YouTube channel or learning web?

tribal badger
#

Anyone here good with Shopify dev?

austere vessel
#

anyone know a website that provide free icon to use for website?

#

I have found some but they afraid to use them cause of copyright

kindred osprey
native tide
small linden
#

@native tide Have you pip installed it?

native tide
#

oh

small linden
#

Yeah I thought it was standard at first too 🤣
with how common is it. You would think.

native tide
#

thx

small linden
#

Ikr I am glad I am not the only numpty 🤣

granite loom
#

Hey guys so if I have a navbar for my project, and it is made with css and html only.
Is there a way to apply that navbar to every single page, without copy pasting it?

noble smelt
#

Django?

#

Wirte a layout.html , then extend it in your other templates

granite loom
dense slate
#

You can use includes to reduce how much you have to edit, but I don't think html supports a way to extend html files the way you want.

#

That's why Django, for example, has templating that allows for extending a base html file.

granite loom
#

i see

#

well i guess ima have to copy it then

austere vessel
#

shouldnt the equal sign after navSlide be purple?

#

if its not does it mean its not properly defined?

#

i'm using vscode insider

swift sky
#

can i use morethan 1 form in a view

willow iron
#

yo, has anyone else also faced a problem with their postgres db when trying to migrate the migrations on a custom user model for a new project?

#

I just keep getting this and apparently, no relations get created in the first place

willow iron
# willow iron

this is the error I get when trying to create a superuser

#

p.s this is django

final meteor
#

How can i execute a python script on click of a button in flask ?
basically i want a page where it shows all the python scripts
a user can select the script he wants to run
and the result of the script execution should show up on another page

While i can get he other pieces, but how should i tell flask to run another python script on button click

I see a lot of results telling to use AJAX but i can't understand it
can't i keep it pure python ?

#

the route function should call another function that processes the python script that user selected And returns a result which is further returned to the render template and the result is showed to user

verbal snow
#
@require_GET
@discord_.login_required
@utils.route(["user/me/", "user/me"])
def user_page_self(request):
``` So I have 3 decorators on a function, however, the route for some reason has to be on the bottom to get the function name, but that causes login_required to not even work. Im so confused. This is in Django.
echo mesa
#

Why are the difference in WTForms between
wtforms.form.Form.formdata
To
wtforms.form.Form.data

echo mesa
#

?

native tide
#

@final meteor sounds like you need to make your own API

#

Shows you the difference

quick bay
#

I am trying to make a form that has a dropdown menu in Django. However, the labels for the form are not what I want. How can I choose what comes in the labels? (I am using Bootstrap)

Forms.py:
class BookForm(ModelForm):
class Meta:
model = drones
fields = ['origin', 'destination']
widgets = {
'origin': forms.Select(
attrs={
'class': 'my-1 mr-2',
},
)
}

Models.py(Origin):
origin = models.ForeignKey('locations', models.PROTECT, null=True, related_name='destination_id')

Models.py(Locations model):
class locations(models.Model):
id = models.AutoField(primary_key=True)
location = models.TextField()

The labels I get are as follows:
locations object(1)
locations object(2)
...and so on

However, I would like the location's name. Their name is also stored in the location model.

native tide
#

So you want origin.location as your label?