#web-development

2 messages ยท Page 87 of 1

errant spear
#

so dict_to_be_passed was an example variable name

swift sky
#

so

quick cargo
#

you use . notation for keys btw

#

dict.key not dict['key']

#

also send your code

errant spear
swift sky
#

would it be

errant spear
#

according to the docs both do that same thing

swift sky
#

dict.key['example of a key']

errant spear
#

dict.key = dict['key']

#

So the error you are getting is that dict_to_be_passed is not assigned

#

so can you show the render_template function you use to call this?

swift sky
#

one sec the file is quie large

#

!paste

errant spear
#

which route is giving the error

swift sky
#
    @app.route("/UpdateKnowledgeArticles")
    @login_required
    def knowledge_articles():
        return render_template("knowledge_articles.xhtml", dict=urls_311)```
quick cargo
#

you dont specify the dict

#

it expects dict_to_be_passed=something

errant spear
#

So in your template the value you would reference is dict not dict_to_be_passed

#

because in the render_template function you are passing the variable dict so that is the one you would be able to reference in the template

swift sky
#

oh i thought dict was a specific kward

#

but ok thx

errant spear
#

It is and you shouldn't use it

#
return render_template("knowledge_articles.xhtml", my_dict=urls_311)
#
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Knowledge Articles</title>
  </head>
  <body>
    {% extends "staff_parent_template.xhtml" %}
    {% block content %}
    <h1> Welcome to the Knowledge Articles page </h1>
    <p> these are the new articles for today </p>
    <h3>DICTIONARY: {{ my_dict }} </h3>
    <h3>DICTIONARY FIELD: {{ my_dict['field_name'] }}</h3>

    {% endblock %}
  </body>
</html>
#

Make sense?

swift sky
#

alright so

#

so it's a list not a dict

errant spear
#

That means that you are passing a list instead of a dictionary

swift sky
#

yeah

errant spear
#

so it would be something in your processing of urls_311

swift sky
#

yeah indeed urls is a list

#

urls_311 = []

#

but the functino

#
def parseXML(xml_string):
    # parse xml
    prefix = "{http://www.sitemaps.org/schemas/sitemap/0.9}"
    dt = datetime.now(timezone.utc)
    root = ET.fromstring(xml_string)
    for url in root.iter(f"{prefix}url"):
        for loc, time in zip(url.iter(f"{prefix}loc"), url.iter(f"{prefix}lastmod")):
            obj_time = dateparser.parse(time.text)
            if obj_time >= (dt - timedelta(days=3)):
                # print(loc.text, "---", time.text)
                urls_311.append({"url": loc.text, "last update": obj_time})
    #print(urls_311)
    return urls_311```
#

so it's a list of dicts O.o

#
urls_311.append({"url": loc.text, "last update": obj_time})
    #print(urls_311)
    return urls_311```
#

or tuple or something?

errant spear
#

So append is a list function

#

So yes you are creating a list of dictionaries

strong oriole
#

what is .xhtml format?

swift sky
#

idk, it's like the default recommendation in my ide

#

what should I google

errant spear
#

Give me one second

swift sky
#

k

errant spear
#

I need to create an example

dense bear
#

hey everyone! anybody available to help with a flask-sqlalchemy problem?

errant spear
#

So @swift sky I don't know if you're using the dict correctly

swift sky
#

oh

errant spear
#

Dictionaries are data structures that store a key value pair

swift sky
#

yes

errant spear
#

keys should be unique

swift sky
#

oh

errant spear
#

Luckily you already have a unique key

swift sky
#

why woulnt they be unique

errant spear
#
urls_311[loc.text] = {
  "last update": obj_time
}
swift sky
#

yeah each url is unique

errant spear
#

That statement makes it so that each url is created into a dictionary entry

#

the value for the entry is another dictionary that holds attributes about the url

swift sky
#

well

errant spear
#

'url0': {'last_update': 'some_time'}

swift sky
#

yeah i understand

errant spear
#

so you would get entries that look like that

swift sky
#

i guess that works

#

i mean

#

but why are you breaking it up like that

errant spear
#

what do you mean?

swift sky
#

the value for the entry is another dictionary that holds attributes about the url
@errant spear this

#

like wouldn't you want to just do url & time

errant spear
#

You could absolutely do that

#

that would 100% work the key is the url and the value is obj_time

#

I just thought you wanted it split up because that is the way you had it before

swift sky
#

hmm

errant spear
#

If I were you I would do it as urls_311[url] = obj_time

swift sky
#

If I were you I would do it as urls_311[url] = obj_time
@errant spear where are you doing this

errant spear
#
def parseXML(xml_string):
    # parse xml
    prefix = "{http://www.sitemaps.org/schemas/sitemap/0.9}"
    dt = datetime.now(timezone.utc)
    root = ET.fromstring(xml_string)
    for url in root.iter(f"{prefix}url"):
        for loc, time in zip(url.iter(f"{prefix}loc"), url.iter(f"{prefix}lastmod")):
            obj_time = dateparser.parse(time.text)
            if obj_time >= (dt - timedelta(days=3)):
                # print(loc.text, "---", time.text)
                # THIS IS THE LINE BEING CHANGED
                urls_311[loc.text] = obj_time
    #print(urls_311)
    return urls_311
#

Like that

swift sky
#

what should I do with urls_311 = [] at the top of the page

errant spear
#

urls_311 = {} creates an empty dict

swift sky
#

oh

#

ha

#

but now it will be a dictionary of dictionaries no?

errant spear
#

No

#

It will be a dictionary with many key-value pairs with the keys being urls and the values being last updated times

swift sky
#

hmm

#

so i tried it

#

jinja2.exceptions.UndefinedError: 'dict object' has no attribute 'key'

#

hmm one sec

#

this is prob why

#

<h3>DICTIONARY FIELD: {{ dict_to_be_passed.key['url'] }}</h3>

errant spear
#

yes

swift sky
#

would it now be loc

#

it would not be loc

errant spear
#

Not quite

#

it would be the url

#

and the way to access it in jinja2 is

#
{% for url in my_dict %}
{{ url }} 
{{ my_dict[url] }} 
{% endfor %}
#

make sense?

swift sky
#

I have a lot of questions

errant spear
#

Ok shoot

swift sky
#

uhhhh

#

when you use my_dict

#

i guess that would be equivalent to dict_to_be_passed

#
    <h3>DICTIONARY FIELD: {{ dict_to_be_passed.key['loc'] }}</h3>```
errant spear
#

yes

swift sky
#

also, do i need both h3 headers

errant spear
#

or whatever is on the left side of the equals in render_template

#

No you can do it in one

#

Unless you want a line separation between them

swift sky
#

naw

#

i changed it to this

#
        DICTIONARY FIELD: {{ dict_to_be_passed.key['loc'] }}</h3>```
#

and so now I will try to make it like so

#

wait

#

so i don't need this anymore?DICTIONARY FIELD: {{ dict_to_be_passed.key['loc'] }}</h3>

#

cuz im looping through the dict

errant spear
#

{{ dict_to_be_passed.key['loc'] }} would throw an error

#

first because the syntax is wrong

#

the syntax is either

#

{{ dict_to_be_passed.loc }} or
{{ dict_to_be_passed['loc'] }}

#

secondly it would throw an error because that would search the dictionary for a place where key = 'loc'

#

the keys are the urls

#

so and the values are the locs

#

so to get the loc for each url you would need {{ dict_to_be_passed[url] }}

#

because that would access the value at that key

#

does that make sense?

swift sky
#

yes

#

this is what i have now

#

but it looks like I could get rid of the last line

#
    <h3>DICTIONARY: {{ dict_to_be_passed }}

        {% for url in dict_to_be_passed %}
        {{ url }}
        {{ dict_to_be_passed[url] }}
        {% endfor %}

      DICTIONARY FIELD: {{ dict_to_be_passed['loc'] }}</h3>```
errant spear
#

DICTIONARY FIELD: {{ dict_to_be_passed['loc'] }}</h3> this line will still throw an error

swift sky
#

my bad

#

i just didnt update it

#

i dont need that line though

#

since you are looping throught he dict already?

errant spear
#

right

swift sky
#

so im going to delete it then

errant spear
#

{{ dict_to_be_passed }} will print the whole dict

{% for url in dict_to_be_passed %}
{{ url }}
{{ dict_to_be_passed[url] }}
{% endfor %}
``` will loop and print the url and location for all the entries
swift sky
#

what's the difference

errant spear
#

No formatting with {{dict_to_be_passed}}

#

I think

#

Not 100% sure

swift sky
#

lets see

#

well

#

closer

#

i can at least visit the url

#

however

errant spear
#

however....

swift sky
errant spear
#

hmmm and what does your render_template statement look like?

swift sky
#
    @login_required
    def knowledge_articles():
        return render_template("knowledge_articles.xhtml", dict_to_be_passed=urls_311)```
#

it may be how my parser script is running

errant spear
#

That's my guess

swift sky
#

meaning, the ordedr of things being run, and the imports

#

since its returning an empty dict

errant spear
#

correct

#

that is the way it seems

swift sky
#

thank you for your help

past cipher
#

Instead of wrapping try:except around all my code, is there another way to log errors that may occur? I have over 12 files, and at least 3000 lines of code

#

Flask btw

hallow jacinth
#

anyone have an idea why elasticsearch isn't finding the indecies on heroku?

#

It works locally, and that is what is confusing me haha

strong oriole
#

how do i conntect css to html , im using flask

#

and i have
base.html

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="mystyle.css">
        <title>{% block title%}{% endblock %}</title>
    </head>
    <body>
        {% block content %}
        {% endblock %}
    </body>
</html>
body {
    background-color: cadetblue;
    text-align: center;
}

both in same fodler

hallow jacinth
#

you have to create a static directory in the same level as your templates directory

#

then after you put your css in the static directory

#

then depending on how you set up your html files, you use the code
<link rel="stylesheet" href="{{ url_for('static', filename='mystyle.css') }}">

#

you can also use the static directory for imgs and stuff that you use to style your site with

strong oriole
#

i have base.html and just extend it in other tempaltes , do i just put it in base.html?

hallow jacinth
#

yes you can just put it in your base

strong oriole
#
<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="{{ url_for('static', filename='mystyle.css') }}">
        <title>{% block title%}{% endblock %}</title>
    </head>
    <body>
        {% block content %}
        {% endblock %}
    </body>
</html>
hallow jacinth
#

it will apply to all files using the base

#

you haven't created a static directory

strong oriole
#

what does it mean?

hallow jacinth
#

it should be like this

\app
    \static
        .css
    \templates
        .html
strong oriole
#

or without css folder

quick cargo
#

doesnt matter really

hallow jacinth
#

^

quick cargo
#

just add it to your path to le file

strong oriole
hallow jacinth
#

that is because the file path you are giving is not where your .css is

quick cargo
#

cuz you didnt do the css/ bit

strong oriole
#

css/mystyle.css?

quick cargo
#

yus

strong oriole
#

yay

#

it works

#

thank u guys

hallow jacinth
#

anyone have elasticsearch in a heroku flask app working?

#

I keep getting a peculiar error

strong oriole
#

is it normal that flask doesnt debug when css updates?

hallow jacinth
#

you have to ctrl+r the page

#

or cmd+r for mac

strong oriole
#
body {
    background-color: rgb(57, 36, 173);
    text-align: center;
    font-size: medium;
}
form {
    background-color: chartreuse;
    font-size: large;
}
#

o.0

#

after refreshing

#

and suddently i dont get the get css notification in termianl

versed lotus
#

what browser is that?

strong oriole
#

opera gx

versed lotus
#

do the dev tools open, if you hit F12?

strong oriole
#

nothing happens with f12 , lemme run the page on chrome

versed lotus
#

might also work with ctrl+shift+i

strong oriole
#

wait wut, suddently on chrome css works

versed lotus
#

right, go to "Network" and see if the checkbox for "Disable Cache" is enabled.

strong oriole
#

its disabled

versed lotus
#

enable it, and keep it enabled.

#

whenever you have the dev-tools open, the browser now won't cache your css files etc.

#

and forces them to re-download

strong oriole
#

so i need to refresh with dev tools open?

versed lotus
#

preferably

strong oriole
#

yup , only works with dev tools open

versed lotus
#

I recommend getting used to dev-tools anyway. They're very helpful for debugging and adjusting CSS

#

usually browsers have a way to "reload without cache". In most browsers it's something like Ctrl+F5 or Shift+F5

strong oriole
#

its my first day working on web dev soo advices are very welcome

#

ctrl+f5 in opera will reload without cahge

versed lotus
#

yes, if you go to "Element" tab in dev tool, you can go through your html hierarchy, inspect each element, and see the CSS rules that apply and change them in the browser directly.

strong oriole
#

thats cool , but later they wont save even tho its my local host right?

versed lotus
#

no, those changes are only temporarily, until you reload the page

strong oriole
#

alright , thank u :3

static forum
#

Should this 2018 web development tutorial I found be fine to learn the basics or has there been any major updates within that time I should keep in mind so I don't learn outdated things

hallow jacinth
#

it should be fine, just becareful of outdated packages or version differences

#

YOOOOOOOOO

#

I finally fixed the stupid issue I have been having for the past week

#

lets go

bright spindle
#

in django, whats the difference between DEFAULT_FILE_STORAGE and STATICFILES_STORAGE?

deft flower
bright spindle
#

is there instances where you would actually need different ones

native root
#

STATICFILES is for developer-provided files such as Html, Css, and Js

bright spindle
#

also for some reason STATIC_URL has become completely useless, while AWS_S3_CUSTOM_DOMAIN seems to take over the work

native root
#

They usually come from your apps

bright spindle
#

but i dont know if its useless or if its nessesary somewhere

#

i put my static files on the cdn

native root
#

DEFAULT_FILES_STORAGE is where.. I think.. django stores uploaded files. User uploaded files, from Filefield and similar

bright spindle
#

to put less strain on the servers (or will it cause more strain, if it has to call the data, then inject the info and then return the data?)

native root
#

Then you should point your static url at the cdn

#

static url is usually used in templates like {{ STATIC_URL }}img/logo.png

bright spindle
#

yeah but whatever i put on static url

#

it still works

#

oh wait nvm

native root
#

There's also STATICFILES_STORAGE

bright spindle
#

i just do

native root
#

Hm. Looks like I've been using static_url wrong

#

Oh well

bright spindle
#

{% static 'foo/style.css' %}

native root
#

right, that's correct

bright spindle
#

but it seems STATIC_URL really doesnt do anything

native root
#

What that does is finds the appropriate link to the static file via STATICFILES_STORAGE

bright spindle
#

thanks for the help bast and sambyte! I also do wonder if im just making things slower by using a CDN for serving STATIC_FILES

#

i just noticed... the source said its a smart idea to do so, but what makes it faster to load, django still has to receive the data, inject the data and then return the site

native root
#

While it won't reduce connection latency directly, it will reduce sending load on your server

#

they still need to get the html from django, but it does mean that everything else comes from elsewhere, which is usually an improvement

bright spindle
#

the improvement is that it allows static files e.g. css and png to be served trough a cdn

#

that is a huge bonus

#

that makes me wonder... if the html actually gets served from cdn or from file storage, ill try that tomorrow nachoburg

meager coyote
#

hi im noob im trying to create a template in django but I think I have an error with routing? Thankful for your insights

#

File "C:\Python38\lib\importlib_init_.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
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:\dev\Projects\CookingBlog\CookingBlog\CookingBlog\urls.py", line 18, in <module>
from . import views
ImportError: cannot import name 'views' from 'CookingBlog' (C:\dev\Projects\CookingBlog\CookingBlog\CookingBlog_init
.py)

noble star
#

Ew Django

#

Iโ€™d rather use Oganj

meager coyote
#

wats oganaj

fallen peak
#

hi im noob im trying to create a template in django but I think I have an error with routing? Thankful for your insights
@meager coyote You are trying to import "views" from the current directory (CookingBlog), but theres no "views" file in that directory

meager coyote
#

ah yeah you are right

#

how would i go about importing it from the blog directory?

noble star
#

@meager coyote read Oganj backwards

fallen peak
#

how would i go about importing it from the blog directory?
@meager coyote from blog import views

fallen peak
#

@meager coyote read Oganj backwards
@noble star jnago?

noble star
#

It was supposed to be django, but my spelling is lacking

meager coyote
#

hi i solved it

#

thanks Deivid

#

and i prefer oganaj now

native tide
#

Is there a way with Flask to make it so a page is only accessible to people inside the network? I have Flask operating as a webhook listener but I would also like to have a page with buttons I can use to trigger the same events that the webhooks do

warm igloo
#

Safest bet would be to not have those buttons on the same app thatโ€™s facing the web even if you think you lock it down.

Make that button app to trigger your hooks be local only. Donโ€™t risk it.

native tide
#

It just occurred to me that since I'm not checking the authenticity of the webhook messages that's totally possible. Thanks!

merry geode
#

@versed python regarding this tutorial you had given me earlier: https://dev.to/ignisda/setting-up-user-authentication-with-nuxtjs-and-django-rest-framework-part-1-5gji
As I said, most tutorials stop at how to signup the user and don't tell how to actually use that information in other APIs. Your tutorial also misses on this part.
What I wanted to know was how to use this token to validate requests once the signup and login is complete. And this is what I needed to do for that:

# For function based views, add the following decorators
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def func_view(request):
    #then use the following to get the user id of the user who made the request
    user_id = request.user.id

And

# For class based view, use the APIView class
class ClassView(APIView):
    #then add the following permission class
    permission_classes = (IsAuthenticated,)

    def get(self, request):
        #then use the previous syntax to access the user information
        user_id = request.user.id

Unless I know this part, creating a login or signup doesn't serve much purpose as I still wouldn't know how to authenticate the requests.

versed python
#

@merry geode alright that's a fair point, and I missed it. It will add it to the tutorial as soon as I can. Thanks for the input!

deft flower
#

Hello all ๐Ÿ–๏ธ - I would like constructive feedback on the UX + code layout in my Django app - https://github.com/huangsam/chowist/ - feel free to provide it in the DMs or as a GitHub issue / feature request

lethal orbit
#

Hello all ๐Ÿ–๏ธ - I would like constructive feedback on the UX + code layout in my Django app
@deft flower looks nice, but a little bit dry. Would be good to add some images. Maybe Cards (as I see you are using bootstrap) to display the restaurants list (https://getbootstrap.com/docs/4.5/components/card/).

naive venture
#

Looking for a method/technology: I have an app that trains ML models and generates forms for users. All models are saved in a S3 bucket. After a user fills out a form and wants to predict something the app downloads the models from the bucket and uses it for the prediction. As the user can simply reuse the form I think that redownloading the model is unefficient. Is there a better way? Download the model to a temporary folder? Use cache?

dapper tusk
#

in django templates, how do you handle things like page title, which has to be in the title tag and 2 meta tags, allowing child templates to change the title in one place and having it use the title in 3 places

#

sending the title as a context var seems quite silly

lethal orbit
#

in django templates, how do you handle things like page title, which has to be in the title tag and 2 meta tags, allowing child templates to change the title in one place and having it use the title in 3 places
@dapper tusk {%with foo="bar" %}<title>{{ foo }}</title>{% endwith %} or something to that effect?
https://docs.djangoproject.com/en/3.1/ref/templates/builtins/#with

dapper tusk
#

how would I override a with in a child tag

#

can I do
with foo={%block bar%}"bar"{%endblock %}

lethal orbit
#

I think it'd be rather

{% block block_to_override %}
{% with title="foo" %}
<title>{{ title }}</title>
<meta...>{{ title }}
{% endwith %}
{% endblock %}
#

Don't think you can just pass a variable from a child template to a parent, if that is what you'd want to do...

#

But I mostly use Django for APIs and ORM lol

dapper tusk
#

Don't think you can just pass a variable from a child template to a parent, if that is what you'd want to do...
well, this is literally what I want to do, so I guess I will just send the title from the view

lethal orbit
#

Probably the most logical.

fallen peak
#

well, this is literally what I want to do, so I guess I will just send the title from the view
@dapper tusk you can also create a {% block title %}MySite - {%%} as a prefix and then in the child templates, you put {% block login %} Login {%%} or something, then you will controle from de template itself.

dapper tusk
#

elaborate please

fallen peak
#

just make sure to put before the {% block content %}{%%} as usually it represents the <body> of the page

#

but yea, you can do either way, depends on your approach

rough tulip
#

"python manage.py runserver" shows nothing is there any solution ?

versed python
#

are you on windows?

rough tulip
#

yes

versed python
#

The last time I was on Windows, and had the same problem. Could not find any solution.

#

I switched to Linux

rough tulip
#

Actually I got solution

versed python
#

really?

rough tulip
#

yes

versed python
#

what was it?

rough tulip
#

you have to remove "#!/usr/bin/env python" this line from manage.py

dapper tusk
#

@fallen peak the problem with that is I need the same title in multiple places

versed python
#

@rough tulip I see, i did not know windows even bothers reading shebangs

#

well that's something new for me, thanks

rough tulip
#

no problem @versed python

#

and us py instead python

#

use*

fallen peak
#

@fallen peak the problem with that is I need the same title in multiple places
@dapper tusk it's the same title to all pages?

dapper tusk
#

one title per page, but on multiple places in that single page

#
{% with rtitle=title|default:"redacted" rdescription=description|default:"redacted" %}
        <title> {{ rtitle }}</title>
        <meta property="og:type" content="website">
        <meta property="og:url" content="{{request.path}}">
        <meta property="og:title" content="{{rtitle}}">
        <meta property="og:description" content="{{rdescription}}">
        <meta name="title" content="{{rtitle}}">
        <meta name="description" content="{{rdescription}}">
    {%endwith%}
somber aurora
#

How to integrate TSX(TypeScript React) with Django?

dapper tusk
#

generally, you make an API in django and talk to that from react

somber aurora
#

How to do that?

#

@dapper tusk

versed python
#

you create separate backend and frontend projects @somber aurora

#

look into django rest framework

somber aurora
#

Oh Okay.

#

Thanks

lethal orbit
#

How to do that?
@somber aurora better yet, use ariadne. DRF is getting dated.

#

(And REST as a whole)

versed python
#

whaattt

#

don't tell me

#

I'm busting my ass over a drf backed

lethal orbit
#

Well, it still works

#

and there's definitely jobs that require it

#

But if I started a new project, I would definitely go GraphQL

versed python
#

god

#

im gonna cry

#

there's too much to learn

somber aurora
#

^

fallen peak
#
{% with rtitle=title|default:"redacted" rdescription=description|default:"redacted" %}
        <title> {{ rtitle }}</title>
        <meta property="og:type" content="website">
        <meta property="og:url" content="{{request.path}}">
        <meta property="og:title" content="{{rtitle}}">
        <meta property="og:description" content="{{rdescription}}">
        <meta name="title" content="{{rtitle}}">
        <meta name="description" content="{{rdescription}}">
    {%endwith%}

@dapper tusk Well, since theres a lot of dynamic meta tags, i think you'll be better of passing the variables as context on the return render_template() and grabbing them with the {{}} jinja syntax

dapper tusk
#

that is what this is doing

#

I just need defaults

cyan violet
#

How can website change data without redirecting and wont letting others edit them
like mee6

vague ibex
#

its probably a server-client relationship

cyan violet
#

uh?

vague ibex
#

its probably preset

#

the part you see is just a front end

#

there goes many processes in the background

#

one by one,

#

as one finishes, the front end changes

#

if im not wrong

versed python
#

@cyan violet look into Ajax, that's where you would want to start

vague ibex
#

Ajax is API-calls based, isnt it?

versed python
#

but dynamic websites are no childs play, and if you want to make a good looking one, you'd have to learn a frontend framework

#

@vague ibex yeah it's present in most browsers nowadays

vague ibex
#

be it front end framework or pure html css, both are usuable

versed python
#

all actually

vague ibex
#

it depends on ur knowledge tbh

#

imagine twitter being wordpress-based

#

linkedin*

cyan violet
#

Could i use ajax to send forms without refreshing

versed python
#

it went out of use and was replaced by modern frontend frameworks now

#

@cyan violet yeah

cyan violet
#

That could work

vague ibex
#

you can try websockets too

cyan violet
#

to check if user has perms i would need to get sessions tho

versed python
#

but you should probably switch to an actual frontend framework instead of Ajax

cyan violet
#

uh

vague ibex
#

Ajax works pretty fine with javascript

#

do you need a front-end framework?

#

ig DOM manipulation with javascript works pretty fine

#

if you dont want to waste your precious time learning react/vue

versed python
#

or you can look into intercoolerjs if you don't want to learn an entire framework

#

my experience with ajax has been not good, hence i am recommending alternatives.

#

it it works out for you, then cool

vague ibex
#

you can use websockets tho

#

no framework no hardwork

versed python
#

never used them so idk

vague ibex
#

once u learn using websockets, its way too easier and powerful

#

today's servers use websockets

#

for communicating

#

be it PHP, node or flask, websockets are super common

cyan violet
#

So i could send from javascript to flask

#

And other could not access it

versed python
#

@cyan violet yeah you can

#

@cyan violet everything can be hacked, assuming there is a good hacker behind the computer

#

but it's generally safe

cyan violet
#

i mean i dont want that my javascript would just send a request to a url with guild id that people could easily copy

versed python
#

i think you should implement it first, and worry about security later

#

one step at a time dude

cyan violet
#

i have it done

#

very badly

#

that it just redirects you to a url where it changes it

versed python
#

then ask in #cybersecurity if you want to have security side cleared up

#

that it just redirects you to a url where it changes it
@cyan violet ajax doesn't work that way, you must have done something wrong

cyan violet
#

i dont use ajax

#

i just do document.location.href

#

lmao

#

and add values like

#

/config/guild_id/nex_config

versed python
#

that's very inefficient and unmaintainable code imo

cyan violet
#

web sockets are better right

versed python
#

i have no idea

#

i dont know what they are

cyan violet
#

Well i think you can make chat apps with them too

versed python
#

most chat apps would use something more robust than ajax

#

something like an actual frontend framework

cyan violet
#

i mean web sockets

versed python
#

well maybe, idk

vague ibex
#

@cyan violet websockets are used for client-server communications.

cyan violet
#

uh

#

So i could use socketIO?

#

or something else

vague ibex
#

SocketIO is a multi-client chatting platform

#

You can use it in your projects tho.

#

What is the main thing are you trying to do?

cyan violet
#

Web dashboard

#

for a bot

vague ibex
#

a single bot at a time?

cyan violet
#

yeah

vague ibex
#

so, basically you're retrieving data from your own database or from any other external database through APIs?

cyan violet
#

mongodb

vague ibex
#

Its simple. Just connect the server with the database properly. Check if everything is okay and then further, make the functions to interact with the front end accordingly

#

Web dashboard
@cyan violet is it like a result for a searched input?

cyan violet
#

what

vague ibex
#

what kind of dashboard is it? when does it appear ?

cyan violet
#

Like mee6 simple

vague ibex
#

like this?

#

I cant really get what kind of dashboard you're referring to.

cyan violet
#

yes

#

you can change bot settings

#

from a dashboard

vague ibex
#

alright

cyan violet
#

socketio is made for chat rooms

#

since it has join_room

vague ibex
#

You can just use websockets then

cyan violet
#

Socketio seems easier tho

vague ibex
#

socketio is a chat room -like thing

#

you need a dashboard if im not wrong

#

so where's the chatroom coming from?

cyan violet
#

nowhere

vague ibex
#

'o.o

#

I can't really get what you're talking about.

#

You want a dashboard so from where is the chatroom coming]

cyan violet
#

i just need frontend to send Something WHere it checks userid from sessions and it can send a guild_id with it too

vague ibex
#

so use websockets

#

simple javascript or event listeners works too

#

whenever someone clicks, you can pass on the details to ur backend

#

the backend will process and do whatever is required and then send back the result

cyan violet
#

Does it keep session values

#

Or i could just redirect users that dont have access

vague ibex
#

you can research more on websockets

#

you can also cache the results for a particular user so that you dont need to do it again and again

cyan violet
#

Whats a good flask web socket

vague ibex
#

I'd refer this to you.

cyan violet
#

k

#

thanks

vague ibex
#

no worries ๐Ÿ˜„ ^_^

cyan violet
#

still reccomends socketio

#

Guess i'll just use it

vague ibex
#

yea gl

#

there are thousands of technologies available tbh

somber aurora
#

I've linked my Django Project to my react

#

How to render my more tsx pages in my views?

hybrid gale
#

is there someone here who uses Selenium for testing or automating with python?!

versed python
#

i did once, what do you need? @hybrid gale

hybrid gale
#

I wrote some code to automate googling stuff just for fun (as always ), and I want someone who writes python code better than me to look at it!!

brittle basin
#

Hello, I'm working on a flask app and deployed it to Heroku. The container is up but as you can see uwsgi fails. It seems it cannot bind port 80. Any idea how can I fix that?

acoustic oyster
#

sudo

#

haha

brittle basin
#

lol

#

But where sudo? To deploy it I do "heroku container:release web"

acoustic oyster
#

are you using docker?

#

you may be missing a chmod

dapper tusk
#

IIRC, heroku gives you a port you are supported to bind to in a PORT env var

quick cargo
#

yeah

acoustic oyster
#

yeah, I do not use heroku sadly, but that sounds right haha

quick cargo
#

like 5050 or something

brittle basin
#

are you using docker?
@acoustic oyster heroku-cli to be more accurate

acoustic oyster
#

you may not want a default, you probably want it to raise an exception if "PORT" is not defined

#

so I would set 5000 to none, or omit it

brittle basin
#

Ok but where do I specify that? In the dockerfile?

acoustic oyster
#

I mean just on that line, you want to os.environ.get("PORT"), if the port is somehow wrong, you do not want it to raise a "failed to bind" error from port 5000. It seems that heroku sets the "PORT" environment variable for you.

brittle basin
#

Ok

acoustic oyster
#

The biggest thing I could think for that error is improperly configured permissions

versed python
#

@hybrid gale i thought you were a beginner, turns out you are better than me lol.

acoustic oyster
versed python
brittle basin
#

I do not use heroku, but here is what I have in docker for a django/nginx container
@acoustic oyster
Ok I'll try, I'll check that more thank you

versed python
#

@acoustic oyster what does the -d flag to useradd do?

acoustic oyster
#

if only I knew, LOL

#

this is from another project, I actually did not write this. But thought it may help

#

it sets the dir where the user will be created

#

shhhh, haha

#

I need this

#

jk, patryk plz help, like you helped me

lethal orbit
#

@acoustic oyster what does the -d flag to useradd do?
@versed python sets the home directory to the passed value (/django)

#

Also, I never used Heroku, so I won't be much help

nimble epoch
#

I want to build an e-commerce website using flask

#

Can anyone tell me what flask extensions are great to do that?

native tide
#

bagisto ?

#

oh that's php

native tide
#

I have a question, is it far more costly to use ModalViewSets inside Django rest framework than simple function methods ?

lethal orbit
#

Can anyone tell me what flask extensions are great to do that?
@nimble epoch You can always look at saleor. It's BSD-licensed (based on Django, rather than flask). Probably better than writing your own from scratch.
https://github.com/mirumee/saleor

GitHub

A modular, high performance, headless e-commerce storefront built with Python, GraphQL, Django, and ReactJS. - mirumee/saleor

nimble epoch
#

@lethal orbit the problem is i want to write it from scratch

#

More comfortable with my own program

lethal orbit
#

Then you need to decide on the features, and look for packages that fill those needs.

  • DB. Either use a DB library or an ORM (SQLAlchemy).
  • User management. See what the standard is (I never did user management in Flask, so I can't help there)...
  • Etc.
#

Decided how you want to handle communications. API, or just templates?
If API, REST or GraphQL?

#

Flask-RESTful seems like a good bet for REST. Ariadne is great for GraphQL, but I only worked with it in Django, not Flask.

#

I do know they have support.

#

Expect to do a lot of research and spend a lot of hours lol

acoustic oyster
#

I have a question, is it far more costly to use ModalViewSets inside Django rest framework than simple function methods ?
@native tide In general, there is probably a performance hit using a built in ViewSet, but I would not consider it anywhere near impactful enough to make the decision as to which one to use

buoyant escarp
#

Hi guys sorry to interrupt, which channel would you recommend I go to for my project idea help/feedback?

native tide
#

@buoyant escarp Whats your idea?

buoyant escarp
#

well it's like using a qr code to send the user to leave feedback on a website/webapp for a product they just purchased

#

was wondering if it's possible using Django framework for it

#

I've used Flask but never Django

nimble epoch
#

@lethal orbit thanks a lot man i really needed that

#

And of course you mean user management like django admin??

#

Or itโ€™s authentication system?

lethal orbit
#

Authentication system.

#

was wondering if it's possible using Django framework for it
@buoyant escarp That should definitely be doable. I think Django is a great fit, tbh.

#

I use a Python back-end to generate bar-codes for a store with physical goods.

#

This channel is a good place. You can also always DM me if you have some questions. I will be busy tonight though ๐Ÿ™ƒ

buoyant escarp
#

Thanks man ๐Ÿ™‚

#

I'll be sure to check in some time later for your expertise

native tide
#

do you guys use elasticsearch with django ? Is it worth replacing django built in python search modules rather using elasticsearch?

marble carbon
#

built in Python search modules??

fast basin
#

How much hosting costs sites like tinypng has to pay if they have 100K daily visitors?

native tide
#

i mean standard traditional filtering

#

like djang-search-filter

muted grove
#

Yo! I have a string that I am getting from a REST API, but a lot of the text is being displayed as HTMl placeholder codes, like &#39 instead of just an ' character. Does anyone know of a python module that handles replacements of these values with their actual meaning?

vestal hound
#

Yo! I have a string that I am getting from a REST API, but a lot of the text is being displayed as HTMl placeholder codes, like &#39 instead of just an ' character. Does anyone know of a python module that handles replacements of these values with their actual meaning?
@muted grove urllib.unquote

muted grove
#

@vestal hound I appreciate the suggestion, but that does not handle the specific &#39; placeholder type

#

that only handles url placeholders like %20 and such

#

I need HTML placeholders, not URL placeholders

#

For reference, I found the solution, it is html.unescape(string)

zealous cloud
#

Does anyone know how to work with the offset parameter in flask? Im trying to get 400 search results to paginate in my jinja template, but unfortunately the propublica api https://projects.propublica.org/api-docs/congress-api/ doesn't include a limit parameter or a next page function. So basically I'm trying to loop through the offset, make the GET api call and then decrease the offset by 20. During each loop I'd have to save the results returned by the api call, but how do I store this data so I can pass it to my jinja template? This is how my code looks

@app.route('/search/member/<member_id>')
def get_member_info(member_id):
    """Retrieve individual government official data on link click"""

    offset = 400
    while offset >= 0:
        res = requests.get(
        f"{MEMBER_VOTE_POSITION_API}{member_id}/votes.json", headers={'X-API-Key': key}, params=offset)
        offset -= 20
        data = res.json()

Can someone please help me figure this out?

rotund token
#

hey guys! im bored atm and wanting to learn more html, css, and js etc. can someone give me a website idea n ill start it up and try to design it, please TAG me to get my attention thanks alot

versed python
rotund token
#

something like a website idea

acoustic oyster
#

@rotund token website for your pet, a portfolio, or make a discord bot and make a website for it

rotund token
#

hmmmm ok

wind escarp
#

@zealous cloud you need to pass the variable in this case member_id to the template, to do that you can use this code:
return render_template('template.html', member_id=member_id)
After this you can call the variable from inside your template by doing something like this {{ member_id }}

#

If you need to save results on each loop then better create a dictionary or list at the beginning of the function and append the result of each loop to that list or dictionary (depending on how you want go save things)

zealous cloud
#

@wind escarp Sorry I definitely should've posted the entire code block for the route. I've done this and got it to work, the api unfortunately only returns 20 results per call. Im trying to figure out a way to get 400 results via the offset method. I dont know how to save that data however, this is what Im struggling with. Here's my full code

@app.route('/search/member/<member_id>')
def get_member_info(member_id):
    """Retrieve individual government official data on link click"""

    res_object = {}
    offset = 400
    while offset >= 0:
        res = requests.get(
            f"{MEMBER_VOTE_POSITION_API}{member_id}/votes.json?limit=100&offset={offset}", headers={'X-API-Key': key})
        data = res.json()
        res_object.update(data)
        offset -= 20

    # return data

    members_data = data['results'][0]['votes']

    return render_template('search/officials_voting.html', members_data=members_data)
#

Yea thats what im working on at the moment, but how would I save this data and continue to update it? Dictionaries dont have an append method, so is there a way to continually add the results of an api call to a dictionary?

wind escarp
#

Are you sure you are adding data to res_object?

zealous cloud
#

No i just printed it. Im definitely not

wind escarp
#

That's where you should add that and then you can retrieve it
Although I can suggest using sqlalchemy

#

Flask-SQLAlchemy is easy to use

zealous cloud
#

This project is making use of flask-sqlalchemy. The issue with this feature is that this is government voting information that changes daily, so every time you visit the page to view voting records you should see the latest info, This is why im not saving this data, I would need to constantly update it.

#

Sorry maybe I didnt explain that correctly or maybe my understanding is incorrect. It's my first time using flask-sqlalchemy. It's been great so far, but maybe I dont understand it well enough

wind escarp
#

Now that's new for me, I haven't worked around that yet so I can't help, sorry.

I am sure there are other tools to do that, it's not impossible but I just don't know how.
Try asking on flask reddit channel

zealous cloud
#

Yea thank you for chiming in. I've posted a question there. So i inserted a print statement after the data = res.json() line inside my while loop and I am getting the desired information. The issue now would be somehow saving it into one big object that I can pass to my template and use jinja to paginate the data. Thank you again for helping. Most apis I've worked with have a num pages or num results option you can work with so you can request 100 results with one api call. This api for some reason only allows 20 results per call. Oh well, that's the fun part about working with apis. They all work differently.

stable kite
#

I want to create a custom django model field.I want it to take email from user and store it in database in bytes form.How to create such a model field?

versed python
#

@stable kite override the save method and convert that field to bytes

stable kite
#

@versed python I don't want to create model but custom model fields that are encrypted

stable kite
#

I saw that but i did'nt find answer to my question

versed python
#

what model are you trying to encrypt? Is it a custom user model or something else

stable kite
#

I want to create open source model fields that encrypt that encrypts the data

versed python
stable kite
#
from django.db import models
from .cryptography import Encrypter,Decrypter
class EncryptedCharField(models.BinaryField):
  def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
  def from_db_value(self, value, expression, connection):
    print('called from_db_value')
    if value is None:
      return value
    return (Decrypter(value)).decode()
  def to_python(self,value):
    print('called to_python')
    if value is None:
      return value
    else:
      return Encrypter(value)
  def get_prep_value(self, value):
    print('called get_prep_value ')
    if value is None:
      return value
    else:
      return Encrypter(value)
  def deconstruct(self):
    name, path, args, kwargs = super().deconstruct()
    print(name,path,args,kwargs)
    return name, path, args, kwargs
#

I am creating an open source project not creating this for my project

versed python
#

this looks right to me, whats the problem?

stable kite
#

I am working on this project because i did'nt find any project like this which encrypt data and and we can retrieve it again

#

This is for text

#

I want it to be for integer,email,etc

native tide
#

id = db.Column(db.Integer, db.Sequence('users_id_seq', start=100000000000000000000, increment=1), primary_key=True)
here the Sequence isn't working
it doesn't start with 100000000000000000000
but it startswith 1

#

I'm using SQLAlchemy ORM

#

with Flask, and Python

#

Python 3.8.5

worn rapids
#

for you uni students out there, found this pretty cool repository for a Rate My Professor scraper (scrapes RMP webpages and uses their hidden API).

It's two years old so I started working on it, cuz it's useful for another tool I'm working on. Lemme know if any of u are interested in helping!

https://github.com/nananananate/ratemyprof-api

#

don't integers have a limit?

native tide
#

Anyone?

stable kite
#

@versed python can you help me?

native tide
#

anyone there?

worn rapids
#

@native tide did it reach the int limit?

native tide
#

I don't know

versed python
#

@stable kite I don't think I can, I am not that experienced about what you want, sorry

stable kite
#

ok

native tide
#

Well, then Do I need to make it, bigint?

worn rapids
#

http://jakegoulding.com/blog/2011/02/06/sqlite-64-bit-integers/#:~:text=From the datatype reference in,2**63-1).

INTEGER. The value is a signed integer, stored in 1, 2, 3, 4, 6, or 8 bytes depending on the magnitude of the value.

That is, you can only store values from -2**63 to (2**63-1). What does SQLite do for a value outside of this range? As we saw earlier, it switches over into floating point. Again, quoting from the SQLite reference:
#

Might not be ur problem, so not sure anymore

native tide
#

I'll try bigint

#

Let me migrate now

#

forgot to migrate

#

now not working

#

@worn rapids I get like this

#
INFO  [alembic.ddl.postgresql] Detected sequence named 'users_id_seq' as owned by integer column 'users(id)', assuming SERIAL and omitting
#

I'm using PostgreSQL

#

done

#

removed everything

#

and retried again

#

but still the ID is same

#

it startswith 1

#
{
  "users": [
    {
      "email": "sairamkumar2022@gmail.com", 
      "id": 1, 
      "keys": [], 
      "name": "Sairam", 
      "password": "123456789", 
      "type": "developer"
    }, 
    {
      "email": "ponvannan2006@gmail.com", 
      "id": 2, 
      "keys": [], 
      "name": "Ponvannan", 
      "password": "28454", 
      "type": "developer"
    }
  ]
}

Ignore password. This is a testing database, which I have hosted locally

#

99% complete

#

Only the seq needs to be fixed

native tide
#

@worn rapids ?

maiden kraken
#

Hello, I am trying to style my webpage with flex and I am having so much trouble making simple 2 column page... It looks like this now:

#

How do i extend second row (highlighted) to the same width as first row?

lethal orbit
#

Are you using a CSS framework @maiden kraken ? Most of them allow you to set a number of columns for your rows:

<!-- bootstrap example -->
<div class="row"><div class=col-6>Row 1 column A</div><div class=col-6>Row 1 column B</div></div>
<div class="row"><div class=col-12>Row 2 column A</div></div>
maiden kraken
#

Hello Patryk, no, I am trying to learn Flex without any bootstrap or any other framework

lethal orbit
#

In that case, you probably want to assign some styles to your row class.

#

min-width and max-width, or fixed width

#

I think most frameworks use javascript to do some magic

maiden kraken
#

okay, this is kinda hard coded solution which I thought can be avoided. I thought there is some magic command which expands row to width of container

pastel osprey
#

In my flask application, I have something that spins up a new threading.Thread (cache eviction for rate limiting purposes). when i try to run flask db migrate, it never exits (obviously). Is there a way that i can prevent certain code from being run if flask is being invoked with flask db *, like an inbuilt environment variable or something?

frosty bluff
#

i have a query about django ?

#

can any one help?

lethal orbit
#

okay, this is kinda hard coded solution which I thought can be avoided. I thought there is some magic command which expands row to width of container
If you have a parent container, you should just be able to set width: 100%; no?

#

You don't have to apply it to the row class. You can add a new class. .row-100 or something.

maiden kraken
#

yeah, I will try, I am definiteley doing something wrong, this should be much easier

lethal orbit
maiden kraken
#

thanks a lot

lethal orbit
#

NP

frosty bluff
#

ok

lethal orbit
#

CSS is the worst part of web dev ๐Ÿ˜„

quick cargo
#

css is great

#

probably the most rewarding thing is seeing stuff come to life

frosty bluff
#

i want to sum of column and subtract with another column total and i know how to do this but i want this with filter like for example if seller = xyz then subtract the total anyone can look into it i will be thankful

cinder plank
#

i want to login to a website uiong requests

#

but it doesnt seem to work

#

where is the problem ?

lethal orbit
#

i want to sum of column and subtract with another column total and i know how to do this but i want this with filter like for example if seller = xyz then subtract the total anyone can look into it i will be thankful
@frosty bluff can you expand? What do your models look like? What columns are you filtering? Do you want to filter on one column, or both?

maiden kraken
#

@cinder plank I think you are passing string instead of variable inside your dictionary

cinder plank
#

how can i change that ? @maiden kraken

lethal orbit
#

Feel free to DM if you don't want to share the code publicly.

maiden kraken
#

@cinder plank well I dont know if its your full code but you probably have email defined as variable, but in dictionary you had something like "email" : "email" <-- this should maybe be variable?

#

i assume you want to pass real email instead of string 'email'

cinder plank
#

yes

#

i just put email and pass instead so people dont see my real account @maiden kraken

maiden kraken
#

ah okay

cinder plank
#

@maiden kraken

astral musk
#

what do you guys use for entering dates in a flask form field?

limber laurel
#

I want to asser that I opened the page successfully in django channels, but eve after a redirect the page status code is 200

#

How could I test if it did not redirect and is in the same view as before?

versed python
#

Guys, is it better to ask a user to login separately after they register or just log them in directly with their new account?

small linden
#

@versed python Iโ€™ve seen it done both ways from my perspective I donโ€™t see an issue either way. ๐Ÿคทโ€โ™‚๏ธ for convince I prefer to be logged in straight away ^^

lethal orbit
#

If you need user to confirm (e-mail, phone number), you can wait for confirmation. Otherwise, no reason to do it in two steps, IMO.

cyan violet
#

cant people from somewhere else connect to my socketio?

quick cargo
#

I mean thats true for everything exposed yh

#

which is why you implement auths and cors

cyan violet
#

atleast sessions

#

still will be there

errant junco
#

is there any way to block direct access to django rest api, like from browsers and such, I want it to accept only ajax requests

twilit dagger
#

Can we ask CSS here also

solemn thistle
lethal orbit
#

Can we ask CSS here also
@twilit dagger sure, it is web dev

#

Being a python server, probably not everyone is a CSS expert though

marble carbon
mild fable
#

Is there a way to automatically replace all the links, scripts and hrefs in a pre-existing template with flask url_for or Django url?

I googled but couldn't find anything. Maybe I will create myself.

errant junco
#

@marble carbon ok I did that, browsable api is gone, but still there's plain json data itself that's still visible through browser

marble carbon
#

well unless you add authentication

#

it'll still be there

errant junco
#

oh ok

twilit dagger
#

There's a margin between my footer and the bottom of the page

#

I did margin-bottom: 0;

#

but nothing's changed

maiden kraken
#

hmm maybe you need 0px;? just guessing I am new to this stuff

sleek pecan
#

How difficult do you guys think it would be to pull try and convert this data table to work with Jinja?

#

I really like the "Rows with Details" one, i've never done this before lol

#

Does anyone know of any bootstrap data table templates specifically for jinja?

warped timber
#

@maiden kraken align-items: stretch on the container

#

wait

#

no

#

make a new container for the entire site

#

and make that flex

maiden kraken
#

@warped timber thanks for response, I kept fighting and I've got to this conclusion:
}
.container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}

.row {
width:100%;
display: flex;
}

.column {
width: 50%;
}

#

but it was just trying blindly stuff in firefox developer

lethal orbit
#

Does anyone know of any bootstrap data table templates specifically for jinja?
@sleek pecan Nope. But if you find a table that you like that takes json data, you can easily use it in jinja with javascript.

<script>
const table_data = {{ table_data_as_json }};
</script>
``` and feed that to your table. (Assuming `{{ }}` was how you printed variables in `jinja` - been a couple of years since I've last used that.)
maiden kraken
lethal orbit
#
.column {
    width: 50%;
}
``` You might want to do like most frameworks, and define `col-1, col-2... col-12` classes, and be able to choose which one you use. `col-6` would make sense with `50%` width (like many frameworks do).
#

But if you only have one style, it may be overkill.

#

Something to keep in mind for the future, at least.

maiden kraken
#

@lethal orbit thanks a lot, that's a solid advice. I often saw scrolling through sites something like col-6, col-3 etc and I've wondered from where it comes from

sleek pecan
#

@lethal orbit Would you suggest anything else? I have a mongodb that I store data in, and I want to create an html site to view it and do searches

lethal orbit
#

@lethal orbit thanks a lot, that's a solid advice. I often saw scrolling through sites something like col-6, col-3 etc and I've wondered from where it comes from
Yeah, they break up rows into 12, usually. You can choose something else. Then add a col-12 that takes all 12 (100%), col-3 that takes 25%, etc.

#

Sometimes, it is better to blatantly copy the pros than reinvent the wheel lol

#

@lethal orbit Would you suggest anything else? I have a mongodb that I store data in, and I want to create an html site to view it and do searches
@sleek pecan do you already have a front-end framework that you use for the site? Basically any table should work, if it supports JSON data.

drowsy rune
#

anyone familiar with django bakery?

lethal orbit
#

Like my previous comment; find something you like and integrate it.... No point writing 10000 lines of JS to make your own dynamic tables ๐Ÿ™‚

sleek pecan
#

Like my previous comment; find something you like and integrate it.... No point writing 10000 lines of JS to make your own dynamic tables ๐Ÿ™‚
@lethal orbit Nope... building it from scratch right now

#

I think i'm regretting creating nested dictonaries in the mongo documents, its just annyoing me now lol

sterile sphinx
#

Would python be good for making a web application for a controlpanel for a remote server where you can start and stop the server? or should i go for nodejs or any other things?

sleek pecan
#

I feel like I learn alot better when seeing examples of what the end result would look like, wheres a good place to even go to find tables that support JSON data? i've been lookin on github

#

hmm

white tree
#

Hey all. I'm newish with flask/sqlalchemy and have built something that mostly works, except for when it doesnt. Unfortunately, it's not giving me any useful feedback when it fails beyond a 500 error response from apache2, and I would really appreciate if someone could spend a dozen minutes or so going over what Ive made to tell me if anything stands out. I'd normally google stuff and figure it out on my own, but I don't really know what Im doing wrong (especially since it does work, but then fails - and fixes itself - periodically).

sleek pecan
#

@white tree No error logs?

north venture
#

What are some front end secret tricks that less people know about?

white tree
#

sadly, no. it does log "wsgi error" - but its not actually mentioning whats wrong

sleek pecan
#

You can't turn on extra logging somewhere?

mortal socket
#

how do i disable static routes in django?

white tree
#

all I get is stuff like this:

19 [Sun Sep 13 09:47:07.200438 2020] [wsgi:error] [pid 14699] FROM pages ORDER BY pages.id
20 [Sun Sep 13 09:47:07.200544 2020] [wsgi:error] [pid 14699] 2020-09-13 09:47:07,200 INFO sqlalchemy.engine.base.Engin e {}

#

I could, Im just not sure where/how to turn on extra logging.

#

sometimes it takes days to get the error to occur, and thus far no clear indication of what causes it /why its happening, because it just seems to be like.. maybe a rate-limit caused by malicious bots? I do see a lot of scanner failures in my error.log, but I have fail2ban on so not sure how much else I can do to stop them from trying

light willow
#

hi, i wanna ask something about flask. do u guys usually keep the main logic on routes or keep it separate? lets say i have a prediction using neural network, is it a good idea to put it on route files?

frozen spear
#

is it possible to iterate templates
like once u submit a giveaway with the values and everything
its creates/show the same template but with differect values
so like template for every pk giveaway

lethal orbit
#

@lethal orbit Nope... building it from scratch right now
@sleek pecan fair enough :D
I like leveraging third-party things, especially for the front-end since js is hell even if it is much better than it used to be.

#

Would python be good for making a web application for a controlpanel for a remote server where you can start and stop the server? or should i go for nodejs or any other things?
@sterile sphinx what kind of server? starting a remote physical server is hard to impossible... whether it is node js or django.

#

I feel like I learn alot better when seeing examples of what the end result would look like, wheres a good place to even go to find tables that support JSON data? i've been lookin on github
@sleek pecan I do as much of my web dev as possible using Quasar :p
https://quasar.dev/vue-components/table <-- these tables take JSON data

twilit dagger
#

I have a div with margins inside a container, but the margins of that div aren't from the container border but rather from the page boundary itself. Why is this?

#

So when I change the screen size then it doesn't align and overflows

native tide
#

Anyone have any sort of experience with Cpanel i want to shoot myself because of this trash

lethal orbit
#

so like template for every pk giveaway
@frozen spear depends how similar you want them, and what you are using. Django with function-based views, and have the same template but with different values? You can create a context dict inside the view, assign it the values you want, and return a response, and access the context inside your template.

native tide
#

hello everyone

#

I would like to move this button next to the prompt

#

here is my html code

frozen spear
#

add css to do that

twilit dagger
#

flexbox

native tide
#
<div class="tab-pane fade" id="Blacklist" role="tabpanel" aria-labelledby="blacklist">
  <label for="input1" class="titillium-web left medium">Blacklist a website:</label>
  <input type="text" id="GUI" placeholder="eg. https://google.com/" name="input1" class = "titillium-web medium-left"><br><br>
  <button type="button" class="button">Add Site</button>
</div>```
frozen spear
#

@lethal orbit bit of confused but i will do more research

twilit dagger
#

@native tide If you put both inside a div then give that div display:flex; then it should automatically move there

native tide
#

I do display:flex right

#

yea

#

i will try

#

thanks

lethal orbit
frozen spear
#

alrighty

native tide
#

lol

#
            <div class="tab-pane fade" id="Blacklist" role="tabpanel" aria-labelledby="blacklist">
              <label for="input1" class="titillium-web left medium">Blacklist a website:</label>
              <div class="prompt">
                <input type="text" id="GUI" placeholder="eg. https://google.com/" name="input1" class = "titillium-web medium-left">
                <button type="button" class="button">Add Site</button>
              </div>
            </div>```
frozen spear
#

@native tide just add css

#

and position it

native tide
#
.prompt {
  display: flex;
}```
#

that's all i did

#

how do I position it

frozen spear
#

do position relative then u have options like bottom tom left rigt

#

play with them

native tide
#

alright

frozen spear
#

so like

#

position : relative;
top : 50px; for example

#

@native tide

native tide
#

ah okay

frozen spear
#

its also best to see live results like the inspect element in browser

#

u can edit there then copy paste

#

and save

native tide
#

it is a google extension

#

I am helping my friend

#

which is why i am so bad at html and css

#

it seems like the prompt and button are stuck together

#

actualy

#

i can inspect elemtn

#

if i open the html file

#

but i can't change css

#

because it's linked

#

i will try putting only the button in the div

#

not sure if that would defeat the purpose of a flexbox

frozen spear
#

no look

#

if the

#

button is linked with anothe text

#

so like

#

if u move the button

#

the text moves too

native tide
#

yea

frozen spear
#

u gotta create an id for the button ten

#

then*

#

so like

native tide
#

ohh

#

I see

#

I got it now

#

I move the actual button

frozen spear
#
<button id="some _ide">things</button>
#

then in css

#
button#yourid {
things
}
native tide
#

ok

#

wait what was the purpose of the flexbox

#

I can get rid of it right

frozen spear
#

what

#

the bulma css framework?

#

u can apply a css ontop of another css

#

so if ur using bootstrap or flexbox or anything

#

u can still

#

edit it

native tide
#

oh ok

frozen spear
#

and create ur own css

native tide
#

tanks

frozen spear
#

๐Ÿ™‚

#

@native tide also if ur doing just few css
u can do it directly in the html so

<button **style="position: relative; etc..."**>hi</button>
#

with the style attr

native tide
#

nice

#

okay

#

i am good now

#

I can change position

#

very good

frozen spear
#

nice

distant trout
#

hi

#

i have been using bootstrap cards for a lot of my stuff, i want something new, any ideas?

twilit dagger
#

How do I change the text color of a bootstrap button when it is hovered over?

distant trout
#

!imporant on css

shy forge
#

Are you looking for the :hover pseudo-class maybe? https://developer.mozilla.org/en-US/docs/Web/CSS/:hover

twilit dagger
#

How do I change the text color of the button if I apply a:hover?

#

Because otherwise it changes the color of the entire button

shy forge
#

What's the CSS rule you wrote?

native tide
#

flask

def home():
    return render_template('home.html', title='CTF Foundation')

it says no template found, but the file exists

ember quest
#

o/ folks

twilit dagger
#

@shy forge I wrote

.header-a:hover{
    color: #333333;
}
#

And the button is

<a type = "button" class = "btn btn-outline-light text-light header-a btn-lg">Contact</a>
#

Nothing actually changes with :hover

shy forge
#

Did you mean .header>a or .header a? .header-a would be the class header-a

twilit dagger
#

No I meant header-a since that's the custom class I gave the button

shy forge
#

Oh, yup, see it. Then yeah, that's a css specificity issue. Try adding !important or add additional specificity.

#

I personally dislike most of the the css libraries out there for this right here. They over-specify their CSS rules which makes the cascade break.

twilit dagger
#

Ok thanks !important worked

#

Now how do I align this button to the right of the navbar

shy forge
#

There are precisely half a million ways. You're using bootstrap, right?

twilit dagger
#

Yes

shy forge
#

I think there's a class that can do it for you.

#

I don't remember what it is cause it's been a while.

#

(I use flexbox for stuff like that.)

twilit dagger
#

Float-right isn't working

#

I tried -

.navbar{
    display: flex;
    background-color: black;
}

.text-right{
    justify-items: right;
}```
#

No luck

shy forge
#

justify-items doesn't support right as a value.

twilit dagger
#

Html -

<div class = "text-right float-right">
                    <a type = "button" class = "btn btn-outline-light text-light header-btn btn-lg">Contact</a>

</div>
shy forge
#

I think you need float-right on the child not the container.

twilit dagger
#

I tried that too

shy forge
native tide
#

I have a really quick question

#
<input type="text" id="input1" placeholder="eg. https://google.com/" name="input1" class = "titillium-web medium-left">```
#

if I wanted to style this in css

#

would i do

#

o shit

#

whatever

#

im blind

#

for css i woudl do

twilit dagger
#

Ok thanks justify-content:space-between did work @shy forge

native tide
#

titillium-web medium-left#input1 right

#
titillium-web medium-left#input1
#

that's how I would do it in css right

#

is I wanted to style the input

twilit dagger
#

just #input1 is enough

native tide
#

oh

#

okay

shy forge
#

You're asking how to select that element?

native tide
#

ye

shy forge
#

And yeah, if there's an id, that's 4? points of priority and always unique.

native tide
#

wdym that's 4

shy forge
#

Priority is how CSS determines which rule matters.

native tide
#

should i change id

shy forge
#

It's loosely !import >>>> id > class > element, and if you combine them they are additive.

#

So if you have two conflicting rules for an element, one is defined by a class selector, and one by an element selector, the class selector wins.

native tide
#

oh

shy forge
#

If you have two class rules, the one defined later wins.

native tide
#

I am trying to change the width of the input box

#

so how would i do it

shy forge
#

If one has two classes, and one has one, the two class rule wins.

native tide
#

it's kinda short rn

twilit dagger
#

pepo is now confused beyond consideration

shy forge
#

Well, you gave it an ID to work with the form, so I'd use that.

#

And it should just be the width attribute.

native tide
quasi berry
#

@twilit dagger what's your problem?

native tide
#

how to change width

#

hold up

#

lemme get my code

shy forge
native tide
#

oh nice

quasi berry
#
<element> {
  width: (your width)
}```
native tide
#

I am livesharing with my friend on my project and I'm editing a saved version in another editor and it turns out I was editing in the wrong editor

quasi berry
#

@native tide what's your probleme exactlly??

native tide
#

I am trying to change the width of an input box

quasi berry
#

change it from css file

native tide
#

lets gooo

#

it's all a matter of me messing up id and switching editors

quasi berry
#
input {
  width: 300px
}```
native tide
#

yea i did that

quasi berry
#

result??

native tide
#

i was trying to figure out why it wasn't changing width

#

i was using the wrong thing

#

i used wrong class

#

and right id

#

then i used wrong id

quasi berry
#

check your browser version maybe.

native tide
#

no it works

#

I can change the width now

#

it worked

quasi berry
#

ok nice.

native tide
#

I have a quesiton

#

for my blacklist a website thing, you are supposed to be able to add websites to the blacklist.

#

What I plan to do is add a click listener in the js file

#

and display all the sites on the page in the html

#

how would I add a new element every time I click the button

shy forge
#

Not much different than Python: Somewhere in your js you define a global variable with an array, then when you press the button, you verify the input then deny_list.push(value)

twilit dagger
#

What does r'^$' mean in Django

native tide
#

hmm

twilit dagger
#

Or url(r'^contact/$')

native tide
#

prob some kind of regex

#

how is my_Btn null

#

there is an element with the id my_Btn

lethal orbit
#

What does r'^$' mean in Django
@twilit dagger r"" means raw string, ^ means "string start", and $ means "string end"

#

so r"^$" refers to an empty string..

twilit dagger
#

So why is it used instead of just '' or 'contact/'

#

In fact, why is url() used instead of path()

lethal orbit
#

url() is deprecated, pretty sure... it was the old django style

#

Basically pre-2.0, you used url() and regex.

twilit dagger
#

Oh ok thanks

lethal orbit
#

And the reason you used r"^contact/$" instead of "contact" was probably because of the way the regex matching worked....

#

If you don't explicitly mark the start/end, I think it might match http://example.com/sports/full-contact/hockey ...

#

Not 100% sure on that, but something along those lines. Good to know regex and ^/$ at any rate.

vestal hound
#

So why is it used instead of just '' or 'contact/'
@twilit dagger the regex matches the empty string and only the empty string

#

the empty string matches anything that contains an empty string, which is...every string

#

a bit counterintuitive, I know

frozen spear
#

so when clicking the button enter its gonna go to another detail view url called entries
now its sending this erorr

#

so the entrydetail view

#

in the template

#

somehow

#

i didnt know how to define pk in the class

versed python
#

@frozen spear in the template {% url 'entries' pk=<some-int> %}

#

in the class, it is present as self.kwargs.get('pk')

frozen spear
#

alright i will try that out

#

thanks

#

defining self

#

hmm

versed python
#

defining self
@frozen spear you need to call it inside a method

#

what exactly are you trying to do with the pk in your view?

frozen spear
#

so its a hosting giveaways app..im done with the giveaway detail view and everything but now,it should generate a pk url which is Link/giveaway(some number)/entries
in that link it will see all the entries of that giveaway

#

so if the giveaway number is 15

#

it should see all entries of the giveaway 15 and redirects u to a detail view with a template when clicking a button

versed python
#
class EntryDetailView(DetailView):
   # other stuff
   def get_object(self):
       primary_key = self.kwargs.get('pk') 
       return YourModel.objects.get(pk=primary_key)

@frozen spear

frozen spear
#

ok thanks

versed python
#
class Post(models.Model):
    text = models.TextField()

class PostImage(models.Model):
    image = models.ImageField(upload_to='images')
    post = models.ForeignKey(Post, on_delete=models.CASCADE)

How can I put a constraint in place so that only 3 PostImage objects can be related to a single Postobject?

vestal hound
#

@versed python I think that isn't possible without restructuring your table

#

because that would amount to a check constraint on a groupby

versed python
#

that isn't an issue, i can just delete my table and start over again. Any idea on how to actually accomplish it?

vestal hound
#

which I believe isn't supported

#

okay, I'm not super experienced in this kind of thing, but my initial guess

#

is to add an additional field, like "image_index"

versed python
#

to which model?

vestal hound
#

then have a check constraint on that ([0, 3))

#

PostImage

#

as well as a unique constraint on (id, image_index)

#

but I'm sure there should be a better way

versed python
#

that sounds like a pretty hacky way tbh

vestal hound
#

you could have a constraint on a materialised view

frozen spear
#

@versed python hey ignis,thanks a lot its works but its throwing this and i already specified a template :

vestal hound
#

which I believe is the more idiomatic method

frozen spear
#

๐Ÿ™‚

vestal hound
#

but then you have to know how to create a materialised view

versed python
#

you could have a constraint on a materialised view
@vestal hound im using drf, so views are not in picture

vestal hound
#

uh

#

no

#

a materialised view is basically a precomputed result of a SQL query

#

in this case, a groupby count

versed python
#

so you're saying I should establish a database level constraint instead of a django level one?

vestal hound
#

wait

#

wasn't that what you were talking about?

#

doing this in Django is relatively easy

#

but in general restrictions should be placed as deep as possible

versed python
#

I just want to associate PostImage with Post, don't really care which method accomplishes it

vestal hound
#

otherwise it's quite simple

#

just override the .save method to check if there are already 3 images related to post

#

and raise error

versed python
#

hmmm, that sounds like a good way

vestal hound
#

Python-level checks are always easier than database-level checks

#

hmmm, that sounds like a good way
@versed python note that

#

you can use bulk_update or bulk_create to bypass that check

#

so you need to override those too

#

alternatively, you could have a periodically running task that performs an integrity check

#

it depends on how much effort you want to put in, I guess

#

which is why a database-level check is always the best

versed python
#

I don't really plan on giving my users access to my python logic so this won't be an issue

you can use bulk_update or bulk_create to bypass that check
@vestal hound

vestal hound
#

since there is only one database

#

and it can perform checks more efficiently

#

sure, your call

#

I actually have a problem like this