#web-development

2 messages · Page 64 of 1

native root
#

In addition, your sys.path.append happens on every call to /order/, which makes it grow slowly

#

I'm not sure what happens if it gets big

native tide
#

can you link me a request

#

I mean a doc

#

sorry

#

this core library will get quite big

#

hehe

native tide
#

This?

#

This is my current tree

#

at is my project

#

and autotek is the base of my django

native root
#

Yes, I think so

native tide
#

i replaced the 2 lines

#

but it gives me module not found

native root
#

just 'dracoengine.draco'

native tide
#

ok

#

ImportError at /order/5933921/
Module "dracoengine" does not define a "draco" attribute/class

native root
#

oh, right. Drat.

#

you can try from dracoengine import draco, or there's another solution but that one's much cleaner

native tide
#

works

native root
#

Yeah, in django all imports start at the "project level" -- or immediatley inside your outer autotek folder

native tide
#

This is my current code

native root
#

the reason import_string failed is it expects a __init__.py file I believe

native tide
#

should i maek a init.py

native root
#

I'd move the load_module to before all the views probably

native tide
#

ok good

#

Works well

#

so the _ init _ .py

#

What does it do

native tide
#

ahh

native root
#

it indicates to python that the files in that directory should be considered available for import

native tide
#

but i also want my draco engine lib to work with discord

#

Cause its like Core

native root
#

basically, from folder import file works but not import folder.file iirc

native tide
#

ah

#

what if draco engine is in /autotek/dracoengine/subdir/draco.py

#

would it be from dracoengine/subdir import draco

native root
#

from folder.folder import file

native tide
#

Ok Thank you 🙂

#

I appreciate your help

native root
#

You can use appconfig.ready() to call something when django's about to be ready

#

See the green note as well, this should let you "start" a discord.py bot and run django at the same time, mostly

native tide
#

Ooo

#

Really

#

That would be nice

wide kettle
#

ive been trying to compress my requests body using zlib (post request)

#

What I did was:
garageString = zlib.compress(bytes(garageString, "utf8")) and I changed headers = {"Content-Type": "application/x-www-form-urlencoded"} into headers = {"content-encoding":"gzip"}.

For some reason my request still isnt working because it gives back the error "invalid request".

I strongly believe that this is because it recieves the request in the form of a b string with the b still in it 🤔

#

Any help would be appreciated, thanks!

past cipher
#

Anyone here use flask-sqlaclhemy? I'm trying to use Float data set, but unable to.

from flask_mysqldb import MySQL
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import FLOAT

"Incorrect column specifier for column 'product_price'")

#
class Orders(db.Model):
    __tablename__ = 'orders'
    id = db.Column(db.Integer, primary_key=True)
    seller_id = db.Column(db.Integer(), nullable=False)
    order_id = db.Column(db.String(50), nullable=False)
    order_date = db.Column(db.String(50), nullable=False)
    payment_method = db.Column(db.String(50), nullable=False)
    total_paid = db.Column(db.Float(50), nullable=False)
    product_name = db.Column(db.String(100), nullable=False)
    product_price = db.Column(db.Float(100), nullable=False)
    product_file = db.Column(db.String(50), nullable=False)
    delivery_status = db.Column(db.Boolean, default=False, nullable=False)
    buyer_email = db.Column(db.String(200), nullable=False)
    buyer_ip = db.Column(db.String(30), nullable=False)
native tide
#

what do you put on a Portfolio website's footer

past cipher
#

personally I put my website name, and social links

#

checkout other junior developers portfolios and decide from there

native tide
#

and copyright

#

ok

past cipher
#

yeah and copyright

native tide
#

seems pretty empty

#

that's why i asked

#

oh i guess if it's a company website it gets filled with a bunch of links.

#

not portfolio Ok

cold anchor
#

@past cipher what's the db schema? that's a mysql error being bubbled up to sqlalchemy so it's likely a mismatch between the data model in python and the table schema in mysql

past cipher
#

InnoDB

#

I switched it to String for now, since it will work that way

#

I just weren't sure why float wasn't working

cold anchor
#

what does describe orders; return from the mysql shell in that db?

native root
#

I suspect that Float(50) is the culprit

cold anchor
#

so your Float(100) might be what it's rejecting

#

try 53 instead

native root
#

oh there's a float 100, missed that

past cipher
#

Will test now

#

Yep that fixed it. I was getting confused. I had 100 on float as I was thinking of the max character count

#

Thanks!

cold anchor
#

happy to help!

balmy olive
#

I'm trying to convert an existing python script I've written into a web app using flask. I've never used flask before and I'm having trouble formatting everything correctly. I think the bulk of it is correct but I have a table that generates from data that I can't get to work/don't know how to format in the code

#

Anyone able to help me with this? Can post code

cold anchor
#

sure

#

what's the code?

balmy olive
#

Can I post a couple text files? It's too long lol

cold anchor
#

!paste

lavish prismBOT
#

Pasting large amounts of code

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

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

balmy olive
#

ahh!

#

!paste

#

can I send another one?

#

oh I see

#

I know it's very wrong but just got no clue how to make it do what I want to do

ancient citrus
#

Where do i store javascript file in my django project?

native root
#

What you're looking for @balmy olive is jinja templates

#

You write your template file like this:

cold anchor
#

might want to delete those pastes and make new ones that don't have the client_id in them

#

you should keep that private

native root
#
<html>
.....

{% for streamer in streamers %}
  <div>{{ streamer.name }}</div>
{% endfor %}
#

Then you load it into your pythono and call template.render(streamers=streamers)

cold anchor
native root
#

There's what I was looking for, thank you

balmy olive
#

Ah good point. Thanks, will try that

#

I'm a little confused. I have the jinja template setup but how do I actually pass the info from the different lists into it and get it to iterate through to generate the table?

cold anchor
#

return render_template('hello.html', mylist=mylist) will "render" the template and give it the variable "mylist", from here we can check the jinja documentation for looping

past cipher
#

{% for item in mylist %}
{{item}}
{% endfor %}

balmy olive
#

I might be going at this a bit backwards, sorry. I'm self taught. I need data from 3 different lists to create the table

past cipher
#

pass all three lists

#

do you have example of your current code

balmy olive
#
<html>
    <head>
        <link rel=stylesheet type=text/css href=index.css>
        <title>Who is live?</title>
    </head>
    <body>
        <img src='stv.png' alt='logo'>
        <table class='center'>
            <tr>
                <th>Streamer</th>
            </tr>
            <tr>
                <td>
                    {% for streamer in streamers %}
                        <a href ={{link}}>{{name}} is live!</div>
                    {% endfor %}
                </td>
            </tr>
            </table>
        </body>
</html>
#

!paste

lavish prismBOT
#

Pasting large amounts of code

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

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

balmy olive
#

I realise I'm not doing anything with that client actually but I'm also not sure how to get that to work either

#

I need to add channel = client.streams.get_stream_by_user(streamers[x]) in there somewhere but again, not sure where to put it

#

Sorry if I'm not explaining very well

past cipher
#

is {{link}} and {{name}} part of streamer list ?

#

if so it should be

{% for streamer in steamers %}
  {{streamer.link}}
  {{streamer.name}}
{% endfor %}
balmy olive
#

No, sorry. I'll send the full script that I'm trying to convert to the webapp

past cipher
#

okay tag me, i will take a look

balmy olive
mild wind
#

Hi guys, does anyone know of a useful python library that can help to validate the shape/datatype of request parameters?

balmy olive
#

If it helps I can try and explain what the goal of the code is and how it works in that script I sent

past cipher
#

This could be wrong since I have never used multiple for loops of list, but maybe:

{% for streamer in streamers %}
    {% for name in names %}
        { % for link in links %}
            {{streamer}}
            {{name}}
            {{link}}
        {% endfor %}
    {% endfor %}
{% endfor %}
balmy olive
#

do I stick that between the <td> tags in the jinja template?

#

If it's easier I could probably work with it just being the links there instead of everything

past cipher
#
 <td>
                    {% for streamer in streamers %}
                        {% for name in names %}
                            { % for link in links %}
                                <a href ={{link}}>{{name}} is live!</div>
                            {% endfor %}
                        {% endfor %}
                    {% endfor %}
                </td>
#

I think anyway

balmy olive
#

It's throwing an error

#
jinja2.exceptions.TemplateSyntaxError: Encountered unknown tag 'endfor'.
 File "/usr/lib/python3.8/site-packages/flask/app.py", line 2463, in __call__
   return self.wsgi_app(environ, start_response)
#

That's the first useful one, there's a load being thrown

acoustic oyster
#

probably the space in

 { % for link in links %}

maybe? just a guess

balmy olive
#

Yup! That was it

acoustic oyster
#

hooray!

past cipher
#

Nice

balmy olive
#

It's not actually getting the data to generate the table though.. I've got no idea how to make that work

past cipher
#

can you send a screenshot of what you mean, I'm not understanding

mint umbra
#

sorry if this question is a bit general, but how would I make an account system for my website?

acoustic oyster
#

that is very general

past cipher
#

do you mean a login system

acoustic oyster
#

flask? django?

mint umbra
#

Javascript

acoustic oyster
#

lel

shadow hornet
acoustic oyster
#

a pseudo login? Or are you looking for like a production website?

balmy olive
#

ah it's not working because i've not added the code, but not sure where to stick it

for x in range(len(streamers)):
        channel = client.streams.get_stream_by_user(streamers[x])
        channel = str(channel)
        if channel == 'None':
            print('not live')
        else:
            webpage.write("    <tr>")
            webpage.write("        <td>")
            webpage.write("            <a href="+link[x]+">"+names[x]+ ' is live!'"</a>")
            print(names[x])
            webpage.write("        </td>")
            webpage.write("    </tr>")

this is the code that I was using to ping the twitch.tv API to determine if a streamer from the list is live. it uses the channel = client.streams.get_stream_by_user(streamers[x]) to get that info then depending on what's returned it writes a line in the table or just prints something in the console

mint umbra
#

I apologize, I thought non-python was allowed in this channel and just saw some people talking. Won't ask any js stuff here again

balmy olive
#

It's obviously different now but I'm not sure what to stick in the part to ping the api to get the data for the table

acoustic oyster
#

If you use pure JS, you can just add, like, an input and check if that input is == user password.

Otherwise you need a DB and I would use something like php.

#

but yeah, you'll get more help on a non-python specific server

past cipher
#

@balmy olive append it all to a list, and then render the list with the template

mint umbra
#

okay, thanks

balmy olive
#

Will try that, thank you @past cipher !

acoustic oyster
#

I'm actually here to ask a question too, lol.

I'm using Django and MySql. I am converting my JSON methods over to a MySql db.

I have a list of strings "inventory" and need to store this data in MySQL somehow. Any have any ideas as to what the best way to do this is?

#

My current plan is to save it as a string == "[item1, item2, item3]", but this seems sloppy

zealous siren
#

nooo

#

inventory should be a table it sounds like

acoustic oyster
#

Can you elaborate? I am very new to this sort of stuff (as you may already know haha)

zealous siren
#

I don't know what invetory means

#

like inventory of what but if it's a user inventory, you have a table called inventory, it would have userid and inventoryid (or itemname)

acoustic oyster
#

it is a list of all the items a user has in my DD style game i.e inventory == ["sword", "potion"]

zealous siren
#

so inventory table with userid and itemname or itemid depending on how you structure it

#

items should be it's own table

acoustic oyster
#

basically all that needs to be stored is that string (the name of the item) for now.

#

it will belong to a class Character that will be many-to-one to a user

zealous siren
#

ok

acoustic oyster
#

what would be the best way to keep track of which items a Character has in its inventory?

zealous siren
#

inventory table

#

with characterid and itemname

acoustic oyster
#

ok. In this case each player will have several characters, each character having an inventory.

Would this be fine for performance then? if I have, say, 50 characters each with their own inventory?

zealous siren
#

sure

#

as long as characterid field is indexed

acoustic oyster
#

ok, ty very much!

What do you mean by indexed? (I will be studying DBs today lol)

zealous siren
#

meaning the database server keeps internal check so it quickly answer select against that table without doing full table scan

acoustic oyster
#

ok, ty.

When this is done, I'll owe you a credit LOL

balmy olive
#

@past cipher I've added a loop that appends 0 to a list if a channel isn't live and 1 to the same list if the channel is live. Can I pass this to the jinja template then it will create a table row if the value is 1? And with flask, does it run the function to generate the page each time someone will load it?

past cipher
#

{% if variable == 1 %}

do something

{% endif %}

balmy olive
#

It's not throwing an error. Just not creating the table

#

Or the rows for the table

dark hare
#

why are you doing
client = TwitchClient(client_id="CLIENTID") and passing CLIENTID as a string?

#

is that just your placeholder?

balmy olive
#

CLIENTID is the placeholder but I am passing it as a string

past cipher
#

in your template you're checking for integer, not string

#

try if variable == '1'

balmy olive
#

ahh damn it

#

Will do, thanks

dark hare
#

have you read the docs?

balmy olive
#

for the twitchapi? No, but the issue is not with the api call I think. I've been passing the clientid as a string and it's been working properly

#

@past cipher That didn't work, still not generating the table

dark hare
#

why are you doing {% if live == 1 %}

#

live is a list of integers

#

not a single integer

#

you are appending strings

#

but then comparing a list of strings to a single integer

#

in the template

balmy olive
#

OY just said that, I changed it to {% if live == '1' %} and that still hasn't worked

dark hare
#

do you know how for loops work?

balmy olive
#

Yes, I see what you're getting at now

dark hare
#

have you got any tests ?

balmy olive
#

No

native tide
#

What would be best way to implement server side form verification while using vue on front end ?

dark hare
#

looks to me as if you're making a very big step

#

why dont you get rid of all of your logic

#

and just get one single request and streamer displaying on your screen first

#

you are making too big of a step

balmy olive
#

I've done that. I've got the whole thing working. I made this script yesterday and it generates a html file but because I want to host it as a web app I am now trying to migrate it to flask to make it all work

past cipher
#

Yeah my bad, its a list. So you should be checking if 0 or 1 is in the list.
{% if '1' in list %}

dark hare
#

those for loops are not going to work how you expect

#

you should look up how for loops work

native tide
#

what does error mean?

#

error: 'myFirstWebsite/' does not have a commit checked out

#

i was trying to do git add .

#

was tryna post my flask website i created years years ago to github

balmy olive
#

I know how for loops work. I'm now trying to get it to work in jinja. I didn't know what jinja was 2 hours ago, @past cipher has been helping me with it but that change hasn't worked either

acoustic oyster
#

@native tide make sure it is in a git repo, you may want to "git add *" to add everything.

#

I think that error is that there is no local repository

real hare
#

@native tide did you run
git init?

acoustic oyster
#

^^

native tide
#

does tb selenium work for windows 10?

real hare
#

If that was done, did you run
git commit -m "commit msg" ?

native tide
#

its the tor browser library for selenium

#

i did run git commit and git init

#

everything fails

real hare
#

did you do git init first?

native tide
#

i kinda figured out

#

yes yes

real hare
#

ok, grand

native tide
#

i figured out to do it via githb

acoustic oyster
#

nice, I figured better to reply late than never haha

native tide
#

but i think the whole things donefor

#

haven't used it in years and i didn't comment my py files to know what to do so

#

it's a pretty crappy website too tho. my complete beginner website😅

#

Does anyone know how to run tor browser with selenium on windows 10

real hare
#

Using Django

User registers to site. However, if they go to create a post they are unable to it. It throws an Exception when the submit button advising that Author cannot be null ( it's linked by a foreign key).

Here is my models file:


User = get_user_model()


class Author(models.Model):
    """ Inherits the auth user model  """
    user = models.OneToOneField(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.user.username


class Category(models.Model):
    """ Generic entries so posts can be filtered """
    title = models.CharField(max_length=20)

    def __str__(self):
        return self.title


class PostView(models.Model):
    """Uses PostCreateView """
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    post = models.ForeignKey('News_Post', on_delete=models.CASCADE)

    def __str__(self):
        return self.user.username


class News_Post(models.Model):
    """Inherits Category & Author Models """
    title = models.CharField(max_length=100)
    content = models.TextField()
    date_posted = models.DateTimeField(default=timezone.now)
    date_modified = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(Author, on_delete=models.CASCADE)
    categories = models.ManyToManyField(Category)
    featured = models.BooleanField()
    post_img = models.ImageField(default='default.jpg')

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('post_detail', kwargs={
            'pk': self.pk
        })

    def get_update_url(self):
        return reverse('update_post', kwargs={
            'pk': self.pk
        })

    def get_delete_url(self):
        return reverse('delete_post', kwargs={
            'pk': self.pk
        })
    def update_author(self):
        np_auth = News_Post.author = Author.user
        return np_auth

#

This is the Exception message:

IntegrityError at /create_post/
(1048, "Column 'author_id' cannot be null")
#

The only hacky way around this would be creating an 'Author' via admin

acoustic oyster
#

The issue may be that you updated your model while it already existed in the database. So django is seeing that the Foreign key does not exist and cannot complete the table.

#

I literally just had a similar issue. I do not have any Users, but am trying to test my models, so I commented those lines out until I am ready to specify a User.

real hare
#

Did you resolve it?

acoustic oyster
#

Oh one sec, I just re-read your question

real hare
#

If so, how so? I'm unfamiliar with Djangos ORM

#

I'm used to dealing with SQL directly

acoustic oyster
#

In this case, wouldnt your author BE the user?

#

Since your author essentially IS a user, I think this way makes more sense.

real hare
#

So drop the 'author' class then?

#

Or is there some way to instruct Django to populate this field?

acoustic oyster
#

I believe that is the best way.

The way I have it is: The User signed in at the time owns the post and is the author

#

The author class seems redundant to me, unless you plan on expanding on it.

real hare
#

I was thinking of maybe extending it to probably include like a 'profile' photo down the line

#

Or maybe I'll not bother

acoustic oyster
#

In that case, you would probably still want the User to be the foreign key, not an author

#

I have a separate profile for extra info, but the user "owns" the profile and also all the posts

real hare
#

Ah yes, I also do have a profile sort've model too

acoustic oyster
real hare
#

so, I should just reuse the profile model?

acoustic oyster
#

The top left is just the username, but you can use djangos "jinja" to make it a full name or whatever.

real hare
#

or should I say, reference the profile model

#

User on my profile model is like:
user = models.OneToOneField(User, on_delete=models.CASCADE)

#

I think maybe just using the user from it then as the substance of post creation then 🙂

acoustic oyster
#

I use this for profiles, but this just allows the user to change their picture. The User

real hare
#

Oh that's cool I like that

#

I just referenced it in mine like {{user.get_full_name}}

#

Didn't use the str method

#

but that's a good way to also do it

acoustic oyster
#

You could probably force the Author to work in the foreign key, but I do not think it is worth it given what you are trying to accomplish

real hare
#

Yeah maybe not

acoustic oyster
#

also Corey Schafer on youtube is the hero of our generation.

real hare
#

I come from a Python 2 background, so this can be a bit perplexing at times too

acoustic oyster
#

lol, I feel it.

#

tbh I'm learning Django now, I just happened to be confronting a similar issue.

real hare
#

Yeah, it's an interesting tool. I've done web stuff with other languages involved, Django is great though

acoustic oyster
#

I love Django too much. That admin page alone makes me so happy every time.

real hare
#

Yeah it's quite good, I use regular Python a lot in work but mostly scripts

fickle fox
#

guys i need some help
docs for flask login are kinda confusing to me
so basically what every login fuction needs???
function*

#
def form():
    form = LoginForm()
    users = Users.query.filter_by(name=user)

    if form.validate_on_submit():
        user = request.form['username']
        if users is not None and user == users:
            login_user(users)
        else:
            return 'user is not found'

    else:
        return render_template('login.html', form=form, user=users)```
#

i know this is messy and user is undefineed
undefined*
but this took me more than 7 days qwq
if anyone knows what i need just ping me

native tide
#

Anyone using vue i need some help with forms validation ?

past cipher
#

@balmy olive did you fix what you need to do

balmy olive
#

Yup I have it all working properly! Thanks so much for your help earlier 😄

#

just if you're curious

            {% for x in range(names|length) %}
                {% if live[x] == '1' %}
                    <tr>
                        <td>
                            <a href ={{link[x]}}>{{names[x]}} is live!</a>
                        </td>
                    </tr>
                {% else %}
                {% endif %}
            {% endfor %}
#

That's what I had to do

past cipher
#

Nice! Glad you got it all working

crisp saddle
#

@fickle fox yes user is undefind, it looks like you want to get a username from your form object, you should fo form.name or w/e you called your variable and pass that in instead of name=user. Furthermore even after you do that you would still have to finish your query. Fx user = Users.query.get(form.username) If the username from the form is your primary key for the users table. Or if it's not your PK you should do user = Users.query.filter_by(name=form.username).one_or_none() and then check if user is None

burnt night
#

herro herro herro...

#

there is something that i've been wondering for a fairly decent time now

#

when you make a back end web app, and post it to a hosting site... how does it launch?

quasi ridge
#

depends greatly on the hosting site

burnt night
#

seeing as how normally in dev i have to type like...
node start or whatever i have the command as

#

i'll be using mainly github

quasi ridge
#

they host apps?

#

I know they host static sites

burnt night
#

oh?

#

any suggestion as to what i should use then?
for back end hosting?

quasi ridge
#

not really. I myself use an ec2 instance, but that's pretty low-level

burnt night
#

?

quasi ridge
#

heroku is pretty slick

burnt night
#

i'll look that up

#

so heroku is best bet? 🤔

quasi ridge
#

an ec2 instance is just a plain old Linux box

#

I didn't say it's the "best bet"; I said it's nice

#

try it and see

burnt night
#

ah... got ya

quasi ridge
#

there are probably 1,000 other hosting providers that I don't know about

burnt night
#

that's fair

#

thanks for your input regardless

native tide
#

Hey guys I'm getting a 502 Gateway Error with Google Cloud Platform when deploying my Flask app

#

Anyone know how to fix this?

strange turret
#

Hi, my goal is to learn django (to become a developer) and I am unsure as which resource to pick to learn - there is too many to pick from online I enjoy learning from books, but am open to videos as well. Any suggestions?

native tide
#

How does /admin work

#

how do i make a login for my site

warm leaf
#

@burnt night I personally use digital ocean myself for hosting my backend

Idk what the pros/cons of amazon ec2 vs digital ocean vs heroku are

burnt night
#

cool cool

#

appreciated

native tide
#

I like to learn mongoDB to make an API for my React project, should i start with Flask or Django ? Is another alternative for mongoDB ?

cold anchor
#

flask vs django is ultimately preference, django comes loaded with a bunch of things that you can add to flask manually or via community libraries

#

mongoDB's alternatives include any database (such as any flavor of SQL)

native tide
#

i have professional experience with .NET and pgSQL so i want to learn noSQL with python

#

so flask is smaller than Django and is better for start practicing ? If i gain experience with flask cna i learn DJango easily or the gap beetween the frameworks is too big ?

cold anchor
#

the fundamentals transfer pretty easily no matter what

#

and mongo is a great db to do nosql with, pymongo is the official library for that

native tide
#

Thanks!

native tide
#

So I have used this to create a route
@app.route('/hi')
Def hello():
return "Hello World"

But now if I go to mydomain.com/hi is works good but if I go to mydomain.com/hi/ it throws a 404 error any idea

nimble epoch
#

Add it like /hi/

#

.route(‘/hi/‘)

native tide
#

If I wanted to do a website with Django for people used to work with CMS (Wordpress) and FTP, would it work if I would set up an FTP server and let them change html templates files that would contain only html but no logic at all? What are the problems to such an approach?

fickle fox
#

@app.route('/form', methods=['POST', 'GET'])
def indexx():

    login = LoginForm()
    if request.method == 'POST':
        if login.validate_on_submit():
            ph = PasswordHasher()
            username = login.username.data
            password = login.password.data
            user = Users.query.filter_by(name=username).first()
            if user and ph.verify(user.pw, password) is True:
                login_user(user)
                return redirect('/')
            else:
                return 'Error in Login'

    return render_template('login.html', form=login)```
#

i get error at login user(user)

#

AttributeError: 'Users' object has no attribute 'is_active'

#

what might cause this?

fickle fox
#

nvm it

#

but guys how can i sort posts by data (newely created data)

#

basically when i create new posti get firstly older data

#

i want to change it

pseudo lantern
past cipher
#

Hey. I am trying to process paypal payments for multiple users. The plan is to get a seller to sign up. They enter their paypal email. When customer purchases their items, the money goes straight to their paypal. I see Adaptive Payments is no longer available for new sign-ups. Can anyone point me in the right direction so I an achieve this

jagged lark
#

Is this "id" a keyword?
@pseudo lantern it is a built in function, but it is used as an attribute name here

#

I think PayPal still have a payment API, but I never worked with it OY

past cipher
#

They have an API however I think its just for you to process payments; no way to send direct to someone elses email

#

I found the payouts API, but that means I must receive payments, and then send to the seller. With this it would mean I am facing the chargebacks etc. I want to send direct to the seller

indigo jacinth
#

Good morning all, I have a question regarding LAMP installation on a digital ocean droplet.

#

Does this mean I have to go back and change it all?

#

For example, /var/www/my_domain is ok for the folder, but when its asking me to put it into config files, should I have used my-domain.com ?

fickle fox
#

ehh god

#

guys i have again problem with post undefined even if i defined it :v

#
        return render_template('posts.html', posts=all_posts)```
#
    {% for post in posts if post.pinn.True %}
    <h2>{{ post.title }}</h2>

        {% if post.author %}
            <h3>By: {{ post.author }}</h3>
        {% else %}
            <h3>By: N/A</h3>
        {% endif %}
    <p>{{ post.content }}```
echo ingot
#

hey guys, i have this project in mind but i have no idea where to start

pulsar nova
#

anyone hav an idea how to create custom groups in django from group

onyx gulch
#

I'm using flask-httpauth for a server, and I'm messing around with bearer tokens
Here's my code:

from flask import Flask, jsonify
from flask_httpauth import HTTPTokenAuth

app = Flask(__name__)
auth = HTTPTokenAuth(scheme = "Bearer")
tokens = {
    "token1" : "abc"
}

@auth.verify_token
def verify_token(token):
    if token in tokens:
        return tokens[token]

@app.route('/test', methods = ['GET'])
@auth.login_required
def test():
    return jsonify({'haha' : 'noob'})

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

I'm using postman to test it, and using the authorization section. When I use the key "abc", which is what it is in the code, I get an unauthorized error

honest dock
#

Anyone here used Django Rest-Framework?

past cipher
#
def post_feedback(token):
    form = FeedbackForm()
    check_token = Feedback.check_access_token(token)
    if (not form.validate_on_submit()) or (not check_token):
        flash('Something went wrong. Please try again')
        return redirect(request.referrer)
class Feedback(db.Model):
    __tablename__ = 'feedback'
    id = db.Column(db.Integer, primary_key=True)
    seller_id = db.Column(db.String(10), nullable=False)
    order_id = db.Column(db.String(50), nullable=False)
    access_token = db.Column(db.String(500), nullable=False)
    rating = db.Column(db.Integer, nullable=True)
    comment = db.Column(db.String(200), nullable=True)
    timestamp = db.Column(db.String(50), nullable=True)

    def add(self):
        db.session.add(self)
        db.session.commit()

    def update(self):
        db.session.commit()

    @staticmethod
    def check_access_token(token):
        query = Feedback.query.filter_by(access_token=token).first()
        if not query:
            return False
        return query

Can anyone see what's wrong with this

rocky garden
#

hello guys anyone here used flask and jss to create an website application ?

#

i'm stuck at a problem

past cipher
#
__init__() takes from 1 to 2 positional arguments but 3 were given
#

check_token returns <Feedback 1> so its not False. However when using if (not form.validate_on_submit()) or (not check_token): this is where the error occurs

#

Actually its form.validate_on_submit() that is causing the issue

#

nvm I fixed it. My form had inputrequired() instead of input_required()

late stone
#

hey guys sorry to bother with my stupid as questions i am very new to web dev, when i import usercreationform then i create an instance of it what am i creating exactly? is it a dictionary with missing values

#

btw is acquiring a post request

#

im so confused, i mean my code is working and everything but im trying to understand whats truly happening under the hood

cold anchor
#

what's the code for usercreationform ?

timid sphinx
#

So currently I have a grid set up like an excel document. I have a title row on top with the data below. To create the sheet used:

grid-template-columns: 1.5fr 1fr 2fr 2fr 1.7fr 3fr 3fr 3fr 3fr 4fr .6fr 2fr 1fr 1fr 4fr;

I used this line both in my title class and my data class so they are the same size, then I populated the info.

I added resizability of the title with resize: horizontal. The issue I have now is i need the data class dimensions to mimic the title's dimensions so it resizes along side it
I don't want them to have the option to resize the tables from data, only title. I just need the data columns to be the same size of the title as the title expands/shrinks

cold anchor
#

I think that'll have to be done with javascript

timid sphinx
#

how so?

cold anchor
#

doesn't look like there's a standard way to do it

timid sphinx
#

Ah. Well thanks for pointing me in the right direction!

peak wagon
#

anyone here who could help with django admin override?

#

i have created a new custom view for updating some fields of a model, it's kind of a change_view but there will be 3 or 4 of this views, with different subsets of model fields

#

the thing is that in add_view as in change_view, the datetime widget is admin styled, but when i create a custom view inside admin, the datetime field is nonadmin, (the difference is really anoying, admin style datetime has 2 separate inputs for date and time, the nonadmin has only one char input field with no browser widget for date or time)

#

thanks in advance

simple meadow
#

Hello guys! I have read that using MongoDB with Django might not be an optimal approach. Does the same apply for Flask?

gentle lark
#

is there a simple time zone conversion package?

#

@simple meadow idk about flask but usually postgres is the best option for python

heavy sigil
#

I am new to django and was having a bit of issues in my

#

code

#

views.py

from .forms import SignUpForm
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required

def register(request):
    if request.method == 'POST':
        print(request.POST)
        form = SignUpForm(request.POST)
        if form.is_valid():
            form.save()
    else:
        form = SignUpForm()
    return render(request, 'bankapp/register.html', {'form': form})

def logout(request):
    try:
        del request.session['email']
    except:
        pass
    return render(request, 'bankapp/login.html', {})

def login(request):
    if request.POST:
        email = request.POST['email']
        password = request.POST['password']

        user = authenticate(email=email, password=password)
        if user:
            return render(request, 'bankapp/home.html', {})
    return render(request, 'bankapp/login.html', {})

@login_required
def home(request):
    return render(request, 'bankapp/home.html')
#

forms.py

    firstName = forms.CharField(max_length=15)
    secondName = forms.CharField(max_length=15)
    email = forms.EmailField(max_length=254)
    password = forms.CharField(max_length=30)

    def clean(self):
        cleaned_data = super(SignUpForm, self).clean()
        firstName = cleaned_data.get('first-name')
        secondName = cleaned_data.get('second-name')
        email = cleaned_data.get('email')
        password = cleaned_data.get('password')

        if not firstName and not secondName and not email and not password:
            raise forms.ValidationError('You have to write something!')```
#

urls.py

from . import views

urlpatterns = [
    path('', views.home, name='home-page'),
    path('login/', views.login, name='login-page'),
    path('register/', views.register, name='register-page'),
    path('logout/', views.logout, name='logout'),
]```
#

The register page works perfectly

#

but the login page does not

#

I use @login_required but after logging in it still redirects me back to the login page

#

Please help if you can

shadow orchid
#

hello

#

I have an api

#

I use heroku to host

#

but the problem is the 512 Mb Ram is not enough

#

but I do not wang to pay 7$ for a bbby version

#

whatrs a cheap and better host for an api built on Open Api v3

#

I used the Fast Api lib

slow rivet
#

im crying

#

how to heroku flask

#

istg im so done

#

im getting the exact error

#

as here

#

but

#

its a big rip for me

#

no solution posted

terse surge
#

hello

#

i have a problem

#

with jquery

#

when i select the first option listed in jquery

#

it does what i coded it to

#

but

#

when i do it to the second one

#

it doesnt

#

heres js

#
$("#id_rank_choices").change(function() {
  if ($(this).val() == "dev") {
    $('#div_id_dev_name').show();
    $('#span_id_dev_name').show();
    $('#div_id_dev_email').show();
    $('#span_id_dev_email').show();
    $('#span2_id_dev_name').show();
    $('#span2_id_dev_email').show();
    $('#div_id_dev_ign').show();
    $('#span_id_dev_ign').show();
    $('#span2_id_dev_ign').show();
    $('#div_id_dev_age').show();
    $('#span_id_dev_age').show();
    $('#span2_id_dev_age').show();
    $('#div_id_dev_timezone').show();
    $('#span_id_dev_timezone').show();
    $('#span2_id_dev_timezone').show();
    $('#div_id_dev_time_spend').show();
    $('#span_id_dev_time_spend').show();
    $('#span2_id_dev_time_spend').show();
    $('#div_id_dev_why_staff').show();
    $('#span_id_dev_why_staff').show();
    $('#span2_id_dev_why_staff').show();
  } else {
#
$('#div_id_dev_name').hide();
    $('#span_id_dev_name').hide();
    $('#div_id_dev_email').hide();
    $('#span_id_dev_email').hide();
    $('#span2_id_dev_name').hide();
    $('#span2_id_dev_email').hide();
    $('#div_id_dev_ign').hide();
    $('#span_id_dev_ign').hide();
    $('#span2_id_dev_ign').hide();
    $('#div_id_dev_age').hide();
    $('#span_id_dev_age').hide();
    $('#span2_id_dev_age').hide();
    $('#div_id_dev_timezone').hide();
    $('#span_id_dev_timezone').hide();
    $('#span2_id_dev_timezone').hide();
    $('#div_id_dev_time_spend').hide();
    $('#span_id_dev_time_spend').hide();
    $('#span2_id_dev_time_spend').hide();
    $('#div_id_dev_why_staff').hide();
    $('#span_id_dev_why_staff').hide();
  }
});

$("#id_rank_choices").trigger("change");

$("#id_rank_choices").change(function() {
    if ($(this).val() == "mod") {
      $('#div_id_mod_name').show();
      $('#span_id_mod_name').show();
      $('#span2_id_mod_name').show();
    } else {
      $('#div_id_mod_name').hide();
      $('#span_id_mod_name').hide();
      $('#span2_id_mod_name').hide();
    }
});
$("#id_rank_choices").trigger("change");
native tide
#

hey
I'm currently working on a pipeline for a php web app and I've got some issues with php caching resolved symlink paths.
I was wondering, do Django or Flask also store realpath of symlinks in a cache?

distant trout
#

can someone help me figure this out.

#

I want a user to be able to post a embed link to my flask website

#

and i want it so whenever its posted, it gets shown as an iframe embeded video

#

how would i go about doing that?

#

so i need a form so a user can post the link but how would i make it so that the link the user has posted is put inside of an iframe

limber laurel
#

I use WTForms, in my form I return a custom error called LoginError, how do I make it register as a field error without making it into a ValidationError?

nimble epoch
#

I have a question about flask_httpauth how can I authenticate user using flask_httpauth?

wild thunder
#

it's a bit up of the middle

#

tried margin top

#

but it makes the line bigger

#

padding not working too

cold anchor
#

give the wrapper element display: flex; align-items: center; is probably the easiest way to vertically center

wooden path
#

Is it possible to host a flask website using github pages?

wild thunder
#

give the wrapper element display: flex; align-items: center; is probably the easiest way to vertically center
@cold anchor thanks! worked!

waxen hedge
cold anchor
#

I'm honestly very surprised that works

#

also I don't understand the question

#

oh I see, you want it to replace the random characters?

#

you can't do that from flask by returning more every time, once you send data, it's sent

wild thunder
#

actually i used the code partially

#

haha

#

but found the error at my code

#

i'm stuck with a 2x4 table

#

to to make it fit?

#

how*

#

tried width

cold anchor
#

the container is fixed width, if you remove the width or max-width from the styles it should just fill to container the elements

wild thunder
#

the font is a little to big, i will certainly make it smaller,

#

the container is a bs4 card

cold anchor
#

do you have any customer styles on the embarques card container?

wild thunder
#

no, not really, just in the table itself

#

i tried to hardcode it directly in the table

#

but i have an custom.css file to add stuff if needed

cold anchor
#

as a sidenote: I don't think cards are semantically made to contain things like tables, so I understand this issue happening

#

what are the classes on the card container?

wild thunder
#

wow, actually that's a huge guess, i'll remove the card

#

hahaha

#

i was putting everything inside cards

#

but i guess it'll be better off the card

#

1 sec

#

it's definetely better, but still oversized

cold anchor
#

yeah if you're just trying to make a table with a container, title and border with a slightly different background color just do that

wild thunder
cold anchor
#

you don't need bootstrap for that

#

what's the UI you're trying to do?

wild thunder
#

it's in my dashboard

#

1 sec

#

sent via dm

#

that will show me "goal achievment"

native tide
opal yarrow
#

Can anyone help me to connect to db2 database on my django project please? Is it even possible I wonder?

native tide
#

does any one know js?

native tide
#

Hey I wanna create a website for my business model, I wanted to ask whether choosing multiple products from other websites (such as Amazon , Ebay) and adding them to your own website to create a monthly subscription box ... I am thinking of selenium and web scraping to add the items to my website , and place the order automatically each month to any given customer , is that possible? If not , is there any other way of doing it?

#

ping me if someone comes up with an idea , thanks!

limber laurel
#

People who use flask, how do you make headers/navigation bars?

tame hatch
#

does any one know js?
@native tide
Yeah

#

Can anyone help me to connect to db2 database on my django project please? Is it even possible I wonder?
@opal yarrow
Did anyone help
I also want to know

deep grail
#

Hey guys. I am scraping a site with bs4. The element is like below. How do I find it using find() ?

glass sandal
#
soup.find("span",itemprop="name")
#

Probably

#

Or a better way could be:

soup.select("span[itemprop=name]")
bleak bobcat
soft trellis
#

Hey, I have a question about flask. Previously have I used local static images and looped over into a render template and that works fine. But Now do I like to do the same but with a list of urls to img (ex imgur hosted) but I cant find any way to do that. Is that my google skills that failing me or is that not a proper usecase?

quick cargo
#

@soft trellis How are you getting the urls, Is it via context or just in the code or what?

soft trellis
#

@quick cargo right now do i have them in a json file that I loading

quick cargo
#

hmmm okay well you probably wanna pass it via context, as a dict or somthing

#

and just have src="{{ images.image1 }}" which would represent images['image1']

soft trellis
#

I will give that a try, thx 🙂

soft trellis
#

@quick cargo With a little bit of fixing si it now working as planned. thx!

dry pawn
#

I'm using "djangorestframework-simplejwt==4.4.0" for the authentication. It uses a scheme which gives user two jwt, the access token and the refresh token. The access token is valid for small amount of time and must be provided for each authenticated call. The refresh token must be used to receive a new access token when the current one has expired. The access token is valid for 10 minutes, the refresh token for 1 day.

  • 1 day seems short, I don't want my user to have to login every single day. I'd think that something like 30 days seem much more suitable. Is it a good idea ? My previous job would use 1h access token and 30 days refresh token.
  • When should I refresh the access token ? When I get a 401 response ? When I notice it's expired as I'm checking it regularly ? I'm going to develop a front with Angular and I don't think it enforces anything on that aspect.
hasty remnant
#

Hey could anyone give me a good reference about django rest framework?

pliant falcon
#

Anyone knows if I can scrap multiple currencies from amazon? for example, scrap price from amazon by USD and EUR for a specific product

past cipher
#

Using Flask SQLAlchemy, I have a table and it has a column called rating. Inside is a float. I have about 10 records. I want to make a query which returns 3 rows with the highest float value inside rating. Any idea how I can achieve this?

#

nvm I achieved it with User.query.order_by(User.rating.desc()).limit(3).all()

distant trout
#

How can I get flask form data with javascript and put it inside of an “SRC=” attribute for iframe?

#

so, i want it like this..... User clicks on submit > get the form data > create "iframe" element > put the form data inside of "src" attribute

warm igloo
#

sounds .. dangerous?

you're saying you want someone to fill out a field and then on the next page, what they put in becomes part of the src attribute of the iframe? Taking that kind of data from the user and then turning around and embedding it in your site allowing them to call an iframe ... scary. Make sure you sanitize all those inputs.

distant trout
#

oh now that i think of it.. it actually does sound scary

#

ill think of something else then 😅

warm igloo
#

#1 rule of web dev -- don't trust ANYTHING from the user.

distant trout
#

oh lol.. Yeah, I'll keep that in mind from now on! thanks 😄

warm igloo
#

that's of course me saying all this not knowing your use case, I can imagine some legit reasons too

Let's say your user fills out a "name" field and you want load an iframe on the next page with src=mycoolanimationpage.com/?name={{form.name}} or something .. contrived example, but say the iframe just takes the name and animates it. And its via iframe cause the animation thingy is on another site. I guess? LOL. Just making this up.

So you CAN do this, just you would obviously want to sanitize the name, make sure they aren't passing anything nefarious, etc.

But ultimately I'd go "Hmm, do I really want to do it this way?"

#

or the form element is the location of a restaurant and you're dynamically passing the location to a google maps iframe, that's legit, still handle with care, but legit

#

etc

distant trout
#

yeah, i am going to try and keep it simple and try to see if there are other ways I can do this. sanitizing everything the user puts in seems hard lol

unkempt snow
#

Hiya, did anyone have a problem where logging into Admin page (django) loads it without the CSS?

oblique tide
#

May someone please give me some advice? I’ve been trying to program in python I like it but I heard PHP is easier.

#

So should I switch to PHP?

dark hare
#

why? are u trying to get hired?

oblique tide
#

It’s not a necessity. I only just started learning python more seriously and consistently lately tbh.

#

Plus Google says that python is easier for novices anyways.

dark hare
#

I'm confused, what is your goal

oblique tide
#

I’d like to get into AI and data science but the light at the end of the tunnel feels too far away. I’d like to maybe get into algo trading one day but that maybe a crapshoot. On the positive side I could in theory be self taught. Unfortunately those are all advanced subjects.

#

Plus Idk if I’d like AI and data science.

#

For all Ik I could dislike it.

#

Those two fields would be very difficult for someone with no advanced maths background to break into.

#

Let alone someone with no industry experience.

#

It just doesn’t sound like a realistic goal for me to have anymore.

#

Unless I become like Elon Musk and study my bum off.

native tide
#

Is anyone working with Vue on front end ?

oblique tide
#

However in theory anyone could get started with AI.

#

“Ik that it works but not entirely how” mindset

dark hare
#

@oblique tide do you have a degree or education in that area?

oblique tide
#

Nope.

#

And that’s my point.

#

Plus Idek if I’d like to actually do it.

#

Sure the satisfaction is in achieving that big goal.

#

But I mean.

#

Can I and should I?

dark hare
#

hmm..I think getting a first job doing data science or AI related is unrealistic unless you have a project that clearty demostrates you have built something showing off those skills

oblique tide
#

That’s my point

#

Let alone without an advanced maths background.

#

Linear algebra, statistics, and calculus

dark hare
#

whats wrong with going into web dev first using python? then maybe look to it in the future?

oblique tide
#

Nothing. I was just wondering if PHP is easier?

dark hare
#

but i dont understand your goal? is it just to get hired?

oblique tide
#

No. To learn the basics and make stuff.

dark hare
#

python is known as one of the easier languages to learn for your first language

oblique tide
#

Oh ok. Then I’m on the right path.

#

Someone on YouTube suggested PHP.

#

So I suppose I was wondering if he was suggesting that it’s easier.

dark hare
#

thats all you need

#

I have a pinned post in the careers channel if u need more help

#

Good luck

oblique tide
#

Thanks!

#

I also would definitely have getting hired as a goal

dark hare
#

Then look for what companies are looking for in your area, what languages and skills and career progession

#

dont learn x y or z language because some guy on youtube said

#

learn what is realistic to you!

oblique tide
#

Yeah. I just wanna start small.

dark hare
#

Then you wont go far wrong with python!

oblique tide
#

Plus. Once I can get some stability in my life in the future and experience, getting into more advanced fields would be more of an achievable goal if I’m still interested.

dark hare
#

Exactly!

oblique tide
#

But that goal won’t likely be achieved until 10 years sadly 😂

#

I’ll likely live a fairly monastic life until then.

#

If I get married and have kids

#

I likely won’t ever achieve other things

#

Unless I’m a time management pro

#

There’s just so much to life.

dark hare
#

python changed my life in less than 2 years

#

each to their own 😉

oblique tide
#

That’s nice!

dark hare
#

do u mind me asking how old u are?

#

roughly 😉

oblique tide
#

20

dark hare
#

if i could be 20 again, holy s***

#

the things i would of done differently

#

If you want a career in programming then get stuck in, you have more than enough time to do what u want to do! You will be years ahead of me thats for sure

oblique tide
#

What is all of your advice to me?

#

What have you learned about life over the years?

dark hare
#

I have learned that nothing worth learning happens quickly, which is why good developers get paid so much money

oblique tide
#

Yeah. I heard they are even constantly learning new things.

dark hare
#

I dont want to try and persuade you, all I can say is python has changed my life in the last 2 years, and im almost 30. If you learn python well enough you will never regret it

oblique tide
#

Thanks! I’ll definitely take your advice seriously since you’re almost 10 years older than me lol.

dark hare
#

What I would give to learn python at 20

#

I would give so much

oblique tide
#

Why?

#

I’m curious

dark hare
#

Because I was a laborer and delivery driver for years and years and I suffered from serious mental health problems for years because of it

#

and someone close to me send me a job advert for something called python I had never heard of

#

I had zero IT experience

#

read my post 😉

oblique tide
#

Your story sounds pretty inspiring ngl

dark hare
#

My advice would be, if you want a 9-5 job and have a stable income then programming is great, if you want to earn bigger bucks and overtake people that are years ahead of you then you have to dedicate more time to it

#

its a very competitive market

oblique tide
#

Yeah. I definitely wanna go big. But honestly a stable income and living is also a really nice goal to achieve. Unfortunately in this society, at least in the US, the social safety net isn’t as good as it could be.

dark hare
#

I live in UK, i plan to move to USA in next few years

oblique tide
#

Unless you’re a monk, you may not be happy with an unstable low income.

#

Or you’re rich to begin with

#

😂

#

Why would you move to the USA?

dark hare
#

more money

#

for senior and principal engineers

#

compared to UK

oblique tide
#

True. Plus you probably pay very high taxes.

dark hare
#

I pay 40% right now

oblique tide
#

Idk if that’s a lot. Sounds like it.

dark hare
#

put it this way

#

if i was senior-lead in USA

#

i would pay 30% max

oblique tide
#

Yeah. Rich ppl can pay less taxes over here.

#

I consider 6 figures rich.

dark hare
#

Yeah and I hate UK mindset

oblique tide
#

Because I never even made 5 figures in my entire life

#

😂

#

Monthly

#

I mean

dark hare
#

completely risk-adverse and non-entrepenurial

oblique tide
#

Yearly

#

That’s kind of how all of Europe is tbh

dark hare
#

depends

oblique tide
#

Unless you count Berlins small tech startup scene

#

In Germany

sand oasis
#

How important is leetcode really

#

I just landed my first job as a software dev, but I didn't have a leetcode problem \

dark hare
#

forget leetcode

#

ive never touched it

#

and i get paid everyday

oblique tide
#

I would reconsider your decision to move to the US if I were you. There is no synthesis between capitalism and socialism. Plus the rioting, racism, and police. It may only get worse over here tbh.

sand oasis
#

how old are you @dark hare

dark hare
#

29

sand oasis
#

What countries are you guys from

oblique tide
#

The USA

dark hare
#

@oblique tide dont worry im in no rush 😂

#

UK

sand oasis
#

you are exactly 10 years older thanme

#

Ahh i am the little brother of the equation

#

Canada here

#

hahah

dark hare
#

then you got 9 years headstart on me

#

congrats

#

wanna swap? 😉

sand oasis
#

you got a job first time last year?

oblique tide
#

@sand oasis we are around the same age lol

sand oasis
#

2000?\

dark hare
#

yeah u should check out my post, pinned in careers channel

sand oasis
#

@oblique tide

#

will do!

#

what kind of work do you do?

oblique tide
#

I’m just learning tbh.

#

I don’t have a job.

sand oasis
#

that was meant to be towards @dark hare sorry lol

oblique tide
#

Oh

#

XD

sand oasis
#

are you in college @oblique tide

dark hare
#

I maintain several apps built using python/django, one is in flask. I also build features for them. They are mainly user facing websites with an ecommerce part to them

#

plus internal systems for moving data around

#

i.e. using lambdas and data transfer etc

haughty turtle
#

`Command 'sqlite3' not found, but can be installed with:

sudo apt install sqlite3` weird doesn't Sqlite come by default?

sand oasis
#

that sounds neat

#

how grueling is the work on a daily basis

#

@dark hare

#

one thing i'm scared about of my upcoming job is how stressful it'll be\

#

but idk if it'll really be as i imagine

dark hare
#

@sand oasis my job is easy as piss, easier than learning python from scratch thats for sure

#

obviously that doesnt speak for all companies

#

but i do a lot of extra learning outside of work hours to make my job easier and improve my own skills

sand oasis
#

i see

#

thanks for sharing

dark hare
#

All the best, ofcourse my advice is biased against my own experience

#

but theres no such thing as knowing too much 😉

oblique tide
#

@sand oasis yes I am.

sand oasis
#

you look for some internships this summer? @oblique tide

#

Covid kinda messed the process up big tim

oblique tide
#

Nope. I’m still learning the basics.

sand oasis
#

ah i see

woeful fable
#

Could python in any way help with web devellopment? I didnt think so but Ive heard

dark hare
#

django and flask are two main frameworks

steady belfry
#

I'm doing a few external API calls from my django server, would it be better to call the APIs and insert the data into a DB, and serve locally, or cache the api calls and serve from the cache?

elder flame
#

whats the average turn around time for getting questions answered on this server?

simple sentinel
#

Depends on the question and how it's asked/phrased. A fairly simple question about standard library python should get answered quickly. But trying to figure out complex code with a library not everyone is necessarily familiar with could take awhile.

elder flame
#

I see, is the flask web framework not used by many people?

native tide
#

That is a loaded question

#

It is used, by many people

elder flame
#

sorry i must not be asking the right questions at the right times,
been on this discord for about a day and so far, havent gotten much traction in the help channels
maybe im asking at the wrong times?
maybe people are off to lunch? asleep? or just not near there computer?

I'm not intitled to a response but the frustration and lack of progress is starting to catch up with my patience

native tide
#

Well, what is your question, exactly?

elder flame
#

Its in the help-boron channel

native tide
#

anyone here know django and want to work on a project with me?

#

please dm me

tall lake
#

How do i make a file or something to make a website?!?

woeful fable
#

Do you have a text editor or an IDE?

#

@Fat#7813

#

Oh he left

valid crane
#

does anyone have good beginner resources for posting data to django backened via ajax/jquery?

snow dragon
#

@valid crane You have a lot of freedom to design your APIs how you'd like when using ajax or jquery. Do you have any further requirements? I typically go for Django Rest Framework to build restful APIs easily and then integrate with those but that partly depends on your needs.

valid crane
#

i have just encountered an error with my code and it seems that the yt tutorial that im following isnt applicable for django

snow dragon
valid crane
#

sure, thanks

limber laurel
#

I have a function called login for my LoginForm, my question is, how can I make them the correct form of field errors, so for example if the passwords dont match under my password field it will say so

opal radish
#

Hi, I'm wondering if it is possible to use the app.route decorator as a normal function.
Specifically, I want to know if something like this is valid

def setup(app):
    app.route("/favicon.ico", lambda f: send_from_directory(os.path.join(app.root_path, "static"), "favicon.ico"))

instead of this

def setup(app):
    @app.route("/favicon.ico")
    def favicon():
        return send_from_directory(os.path.join(app.root_path, "static"), "favicon.ico"))

The only reason for this is to silence the error about favicon not being used in my editor 🙂

#

Mareks, what are you using?

#

nvm, app.add_url_rule seems to work well

limber laurel
#

Is there a way I can setup error handlers using flask.views and make it class base?

limber laurel
#

@opal radish Flask and WTForms

#

Oh damn my grammar in that sentence is uhh sorry to whoever read that lol

fading vortex
#

in my django models i want to be able to select a list of actors and generes

#

atm i can only select one

vestal hound
#

you want ManyToManyField

#

@fading vortex

#

ForeignKey is for many-to-one relationships i.e. one actor can be in many movies, but one movie can only have one actor

native tide
fading vortex
#

@vestal hound okay thanks

honest dock
#
class Point(models.Model):
    class Meta:
        db_table = 'Point'

    account = models.ForeignKey(User,  on_delete=models.CASCADE, related_name='pointAccount', db_column='pointAccount')
    latitude = models.CharField(max_length=50, null=False, db_column='latitude')
    longitude = models.CharField(max_length=50, null=False, db_column='longitude')
    name = models.CharField(max_length=50, null=False, db_column='name')
    description = models.TextField(db_column='description', null=True, blank=True)

    def __str__(self):
        return self.name + " (" + self.latitude + ", " + self.longitude + ")"


Gives me this error:

Please select a fix:
 1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
 2) Quit, and let me add a default in models.py
Select an option: 
#

Anyone know why? The tables are empty.

jagged lark
#

It doesn't really matter, the ORM will ask you to use a one-off default in case another database somewhere have some objects in it

#

You can use a random value I guess

honest dock
#

Thing is it's just a foreign key

#

can i remove it later on?

jagged lark
#

Remove what?

#

You could make it nullable then I guess

honest dock
#

thing is it works perfectly fine in this model:

#
pointA = models.ForeignKey(Point, on_delete=models.CASCADE, related_name='pointA', db_column='pointA')
    pointB = models.ForeignKey(Point, on_delete=models.CASCADE, related_name='pointB', db_column='pointB')
jagged lark
#

I mean, if you try to add a pointC key in it and make a migration, it will ask you for the default

honest dock
#

No, since the table is empty..

jagged lark
#

Alternatively you can get rid of the whole migration file, but you'll have to create a new database

#

It doesn't matter

honest dock
#

How?

#

It's the dev server

jagged lark
#

The migration history is like a git history, you need to be able to go back and forth, no matter what the database contain

#

Well, delete the migrations folder, make a new one, and delete and recreate the database on your dev server

honest dock
#

Oooooo

#

love you bro! worked

#

#nohomo

jagged lark
#

Nice!

native tide
#

should i desgin my contact form inputs with labels or with placeholders

gloomy acorn
fading vortex
abstract python
#

I'm following the Django Girls tutorial, and have come unstuck with the post_detail section.

In my urls.py I've got got this:

    path('', views.post_list, name='post_list'),
    path('post/<int:pk>/', views.post_detail, name='post_detail'),
]
#

and thus gives me an error.

#

but I'm not sure what I did wrong.

fading vortex
#

that tutorial just follows the django docs

vestal hound
#

huh

#

I don't understand your point

fading vortex
#

is that urls pattern in your main app

#

i try to make another movie but the relationships with the actors carry onto it

#

from the first movie

vestal hound
#

those are all the objects of that type that exist

fading vortex
#

LOOL im sorry

gloomy acorn
#

@abstract python what the file views.py contains?

abstract python
#

@gloomy acorn views.py has (the relevant bit at least), this:

    post = get_object_or_404(Post, pk=pk)
    return render(request, 'blog/post_detail.html', {"post": post})```

Which I've checked against the tutorial and that's what they've got as far as I can tell.
vestal hound
#

hm

#

more pertinently

#

is your HTML correct?

abstract python
#

the link is:
<h2><a href="{% url 'post_detail' pk=post.pk $}">{{ post.title }}</a></h2>

vestal hound
#

I'm like 95% sure

#

something is wrong with your template

#

I don't actually use Django templates, but it's not your urls.py that has an issue

abstract python
#

that wouldn't surprise me tbh, HTML is the thing I've learned least-recently so is probably the most likely thing for me to botch 😄

vestal hound
#

because basically

#

what is happening is

#

the link that is generated by your template is wrong

#

think of it this way

#

URLs are addresses, and views are the buildings that appear at each address

#

i.e. URLs answer "where is this thing" and views answer "what does this thing do"

#

what's happening above is that you are getting the wrong link

#

not that you have the correct link but it's doing the wrong thing

#

and the reason for that is that your template should be generating the right link, but it's not

abstract python
#

yeah, not sure where all the %7B% stuff is coming from. IIRC %20 is a space character?

vestal hound
#

if you look at the URL in your a, it looks like this: {% url 'post_detail' pk=post.pk $}

#

yes

#

it's basically a way to encode URIs (URLs are a type of URI)

gloomy acorn
#

@abstract python i ll give u my example
<a style="text-align:center;" href="{% url 'articles:detail' a.id %}"><h2 style="margin-top:30px;background:#79AEC8;">{{a.art_title}}</h2></a>
urlpatterns = [ path('', views.index, name = 'index'), path('<int:article_id>/', views.detail, name = 'detail'), ]
def detail(request, article_id): try: a = Article.objects.get(id=article_id) except: raise Http404('Page Not Found') return render(request, 'articles/detail.html', {'article' : a})

vestal hound
#

okay I think

#

I see the problem

#

you have an $ where you should have a %

#

right before the closing }

abstract python
#

wellll that's incredibly embarassing 😄

vestal hound
#

that's my guess, based on what the logical syntax would be

abstract python
#

yeah, that works fine now. Sorry for wasting your time.

#

probably should've noticed that myself heh.

gloomy acorn
fading vortex
#

i dont understand rn im sorry doing my own work

vestal hound
#

@abstract python no problem

#

if you were comparing it to something from a tutorial

#

one thing that can help is to copy-paste from the tutorial and ctrl-F in your code

gloomy acorn
#

ok then

abstract python
#

@vestal hound Aye, I was stubbornly refusing to copy and paste and work it out on my own, when in reality doing that after 10 minutes or so just to find any differences would've saved a lot of time!

vestal hound
#

no, no

#

you should work it out on your own

#

typing the code out yourself is good for your learning

#

but when comparing to a source ctrl-f is helpful

abstract python
#

yeah, that's what I mean. Writing the code myself = good. Refusing to copy and paste even to ctrl+f to see what's different in my code = bad.

burnt mirage
#

@abstract python Haven't been following, but do you know how to do a diff?

abstract python
#

I know it's a thing, but I'm not totally sure on how to do it.

burnt mirage
#

Good editors have a way to do it built in, but point is it's a way to see differences between code without relying on just your Spot The Difference skills

nova storm
#

Can anyone tell what 'python manage.py shell' do??

#

And how to use it?

haughty root
#

I want my app to work on 80 port but I don't wanna run the entire program as root. Is there a way I can make 80 port nonpriveleged or something

zealous siren
#

no

#

but you can change permissions to allow certain binary ability to do it

#

cap_net_bind_service is what you are looking for

#

most people wouldn't recommend it

haughty root
#

But if I set it for python interpreter all programs willbe able to use a priveleged port

zealous siren
#

if you want to run something like Flask/Uvicorn or like, run Nginx in front then proxy incoming on port 80 to whatever high port you select

haughty root
#

ok gotta learn about nginx

zealous siren
#

or docker

#

basic nginx as proxy is really easy

#

I think config file will be like 7 lines

haughty root
#

Should I use nginx on my development machine?

#

Or only in production

sudden crest
#

Yeah, recreating your prod environment is generally a good idea

zealous siren
#

Docker look into docker

rigid mist
#

Is webscraping against Reddit's TOS?

past cipher
#

Hey. So I'm working with flask, and I have a question. I have a javascript file called main.js which I use for every single page. I load by using include. Now I have /edit-product and it gets passed a list from the backend called product. If I include a script tag at bottom of my page, I can use the product variable like: alert('{{product.name}}'). However if I do the same in my main.js file, it doesn't work.

How do I pass variables through to the main JS file ?

#

@rigid mist use the reddit API

crisp saddle
#

@past cipher I would generally discourage of making frontends in flask that needs this, however it can be done:
You almost had it yourself,
In your main.js just make a setup function that you call from your HTML after you include main.js that takes the thing you want as a parameter.

fierce sphinx
#

How is python used in web dev? It is in the web page or it running on the server and does things on it or with the page?

crisp saddle
#

I use it daily for creating REST API's :-)

#

So that would be running on the server.

zealous siren
#

I do REST APIs as well

#

people do make full web sites with Python using Flask/Django but that's not "new" hotness

crisp saddle
#

@zealous siren what framework do you like for REST API's?

native tide
#

I think Flask is pretty good for this. I‘ve seen some people using it for REST APIs

crisp saddle
#

That's what I use too, and have been for the past 2 years, but I think I'll try Fast API next time :-)

zealous siren
#

FastAPI

past cipher
#

@crisp saddle would you mind sharing why you would discourage it?

#

I managed to fix it by doing inline script styles

#

I thought I could of used {% with %} but turned out I couldn't

#

I really do need to learn Javascript soon though. I'm having nothing but problems..

zealous siren
#

It's just so easy to get going with FastAPI

past cipher
#
{% for item in codes %}
        <script>
            document.getElementById('digital_codes').append('{{item.code}}');
        </script>
    {% endfor %}

This seems to only append the first item, but I'm not sure why

#

and I know its going to produce multiple script tags, but I have no idea how I would do a for loop inside a script tag while looping through a list

pulsar ivy
#

Get all elemenents by id

past cipher
#

its one element

#

text area, it should append each item.code

pulsar ivy
#

Like that you are selecting only first "thing" with that id

past cipher
#

because there is only one "thing"

#

a text area

pulsar ivy
#

Hmm

past cipher
#

it should append each item.code to the text area

#

but its only appending the first code

#

and no error in console either

distant trout
#

so I have been working on making a flask blog that is decent for a beginner I'd say(4 weeks). Now I am thinking of learning Django. Is that a good idea or should I keep learning more about Flask?

quasi ridge
#

hard to answer.

#

If your goal is to just learn for the sake of learning, then yes: they're both popular frameworks, and it'd be interesting and useful to know how they're similar, and how they're different

#

but if you just want to serve up some simple web pages, and flask is working, then ... maybe not

distant trout
#

hmm. I feel like I want to learn more about Django and maybe how flask/django are similar. I think im going to give it a shot

quick cargo
#

They are overall quite diffrent

#

One is a very Heavy framework which controls how you lay stuff out heavily (django)
The other is a micro framework where you have much better low level control but the framework does less for you (flask)

distant trout
#

Yeah, I feel like I kind of plateaued with my flask project, dont know what more to add or what more I CAN add. So maybe its time to check out django

onyx gulch
#

I'm using flask. How can I have bearer tokens work for only certain endpoints? So say I want token 1 to access /test, and not be able to access /hello, and token 2 to only access /hello, and not /test

crisp saddle
#

Are you using Flask Restplus @onyx gulch ?

#

Well the answer is kinda the same, you just make a decorator that requires it for an endpoint, and leave it out if the endpoint doesn't need token auth 🤷‍♂️

native tide
crisp saddle
#

@native tide it's telling you, you are missing a required argument.

native tide
#

i know, but i don't need UserCreationForm since i made my own model

crisp saddle
#

If you don't need it, why don't you just delete it?

#

I have never developed django

native tide
#

I can't delete it

#

it came with the django package

onyx gulch
#

@crisp saddle I'm using Flask Http auth

#

Should I switch to Restplus?

crisp saddle
#

I have no experience with that framework but the overall design pattern is the same I would assume.

onyx gulch
#

With rest plus can you specify which token is needed for the endpoint

crisp saddle
#

can you show me an endpoint that has auth?

onyx gulch
#

So I could have more than one token

#

alr

#

one moment

#
from flask import Flask, jsonify, request
from flask_httpauth import HTTPTokenAuth

app = Flask(__name__)
auth = HTTPTokenAuth(scheme = "Bearer")
tokens = ['abc']

@auth.verify_token
def verify_token(token):
    if token in tokens:
        return token

@app.route('/test', methods = ['GET'])
@auth.login_required
def test():
    return jsonify(databasemanager.getAllProducts())

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

So the reason you wanna do this, is because you don't want to develop user roles?

onyx gulch
#

Correct

#

I want to have different tokens be able to access different endpoints

crisp saddle
#

I see, well you could make a decorator that is decorated by @auth.login_required

#

and in that decorator decode the token and see if it's of the type that you need.

#

sec

#

actually what's wrong with your verify token @onyx gulch ?

onyx gulch
#

no i was just wondering if i could have different tokens access different enpoints

#

endpoints

crisp saddle
#

so verify_token is the decoded token? 'abc' ?

#

in that case you just create two type of tokens, user-role#somerandomstrings

and then check the role when you verify it?

onyx gulch
#

can i access which route is requested via verify token

crisp saddle
#

yeah

#

with requests

onyx gulch
#

how would i do that

#

sorry im still learning this library

onyx gulch
#

ah ok

#

thanks

lavish canopy
#

I haven't developed a site in flask yet, is it like WAY easier than Django?

#

Been working on this Django site for like 2 months (because I'm learning from scratch and want to make sure I understand everything) and I barely feel like I'm making headway

#

I broke the site once by referencing objects by IDs and then had to change them all to reference by PKs instead

#

I don't know why it worked... But it worked

#

Before I go further into things, do I HAVE to reference HTML files that are in apps instead of just a folder in the main directory?

#

I'm writing a blog and e-commerce app, but they all live in a single web app

#

Ideally I'd like for a user to simply make ONE account that can access the other apps in the project

onyx bough
#

I'm trying to setup django on python anywhere and I can't get it working

#

!rules

lavish prismBOT
#

The rules and guidelines that apply to this community can be found on our rules page. We expect all members of the community to have read and understood these.

onyx bough
#

Does anyone know a better host to use? I don't really like this one

snow dragon
#

What do you mean by host? Framework? An alternative to Django?

onyx bough
#

Like server hosting

#

Im using PythonAnywhere

snow dragon
#

I've never used any managed hosting service, only cloud services (GCP/AWS). I've heard good things about heroku though.

signal pasture
#

Hey guys im trying to refresh a webpage from my flask app every five minutes but I cant figure out how. Basically it is webscraping and uploading it to the webpage for real time data. However I cant figure anything about refreshing. Anyone know how?

crisp saddle
#

@signal pasture you can do it in pure html :-)

#

@signal pasture

<meta http-equiv="refresh" content="300; URL=http://www.yourdomain.com/yoursite.html">
#

if it's the same page you can omit URL

split steeple
#

@onyx bough try PyCharm

signal pasture
#

@crisp saddle i see thanks

native tide
signal pasture
#

@crisp saddle Will that change the values of the variables from the flask app because when i refresh it gives the same data

reef pendant
#

Can I get invite to djando server or this is it?

native tide
#

dm me @reef pendant

reef pendant
#

@native tide I don't understand?

dull needle
quartz badge
#

hey guys just starting to learn docker with django in vscode, and I am having a weird issue.

debugging the default django launch everything works fine on the admin page.

however if I do docker-compose up and look at the site it seems to be missing the css things for the admin side

quick cargo
#

Oh that issue

#

I used to have the same this when the site was in debug mode it would load it when it wasn't it couldn't

quartz badge
#

I assume I am just missing something here, what do you do to fix it?

native tide
#

does anyone here have experience in selenium?

glass sandal
#

Guys why does Flask have less job opportunities than Django?

#

Just curious

limber laurel
#

How do I import a html file in a html file, for example an navigation bar in my base file without it overwriting other things?

glass sandal
#

{% extends %}

limber laurel
#

If I do that with my nav bar to my base html file I only see the mav bar

glass sandal
#

{% extends filename %} to be specific

limber laurel
#

And nothing else

glass sandal
#

You have to put blocks

#

Like {% block navbar %}

#

{% block body %}

#

You define these in the navbar code

#

and write it in another page

#

Just learn a bit more Jinja2

limber laurel
#

Ok, ty

glass sandal
#

np

limber laurel
#

If I have fir example block content defined in a different file I ahould call it differently just like a variable right?

glass sandal
#

{% block blockname %}

#

And then like this :

{% extends "index.html" %}
{% block head %}
<title>Hello</title>
{% endblock head %}
limber laurel
#

Ty very much everything works now, had an error for a bit and I had forgotten to use "" when extending 😅

glass sandal
#

np

limber laurel
#

Can I extended multiple times somehow?

#

Oh, Include

glass sandal
#

Guys why does Flask have less job opportunities than Django?
Just curious

#

Like flask could do anything that django does

#

It's more flexible

#

and ...

#

I'm fan of both btw

limber laurel
#

You need more different libraries than Django, for example an admin pannel, in flask you would need to make it bacically yourself, but Django already comes with things like that

#

For bigger applications it often makes more sense to use Django

#

That is from what I have heard, as many of the flask libraries are made by different people and there is no guarantee that they will keep developing them for example 3 years from now
But tht is from what I have heard, haven't had real world experience with this myself, but I often see when searching how to do something with flask that with Django there is already a tool for that

haughty root
#

How do I await in aiohttp_jinja2 templates?

pulsar ivy
#

Guys is there a way to save search history locally on device in flask

cold anchor
#

what kind of search history?

#

like what they're typing into a search bar on your website?

quick cargo
#

@haughty root You normally have to await the render

glass sandal
#

@limber laurel But flask is flexibility god

#

And you make everything you want in any way you want

bleak bobcat
#

Flask is a sandbox. Django is a sandbox with a few sandcastles already there, but you can just remove them...

fickle fox
#

Guys i need to improve my webdev skills so what are good exercises orprojects?

haughty root
#

@quick cargo I use it through decorator, like ```py
@routes.get('/{name}')
@aiohttp_jinja2.template("hello.jinja2")
async def hello(req: web.Request):
return {'name': req.match_info['name']}

quick cargo
#

pithink Which framework is this?

haughty root
#

aiohttp

quick cargo
#

oof

#

Why Aiohttp not somthing like Quart or Sanic?

haughty root
#

I heard only about flask, django and aiohttp

quick cargo
#

Quart is legit just async flask

haughty root
#

And sanic?

quick cargo
#

Its a lower level Async framework thats much faster but you have to do alot of the stuff yourself

haughty root
#

O, I also heard about vibora, is it good?

quick cargo
#

But on the @aiohttp_jinja2.template("hello.jinja2") IIrc that decorator a should get awaited by the original call

#

I havent used it directly, I know some of their bench marks are a lil sketch

#

Looking at their github aswell development seems to of stalled

native tide
#

Hey where all do you suggest I go to learn the ins and outside of Django? I've done the polls app in the docs, but then what?

marsh canyon
#

More projects

#

Like a todo app, social media site, quiz app

#

Go through the model query page in the docs, they come in handy

nova storm
#

Guyz how to paste our code here??

glass sandal
#

do ` ``py

#

and close with ` ``

#

``py ``

nova storm
#

I dont understand what to do with this code??(problem is in .img format)

glass sandal
#

There is not an item with id 2

nova storm
#

This is django documentation

#

I got this one from there

#

But I don't what we r doing in it?

glass sandal
#

You get the item with id 4

#

In the database

nova storm
#

I just copy paste it in my ide

#

But it showing me some error

glass sandal
#

Cause you didn't add any item to database

nova storm
#

Wait let me send u the error details

#

Okay

#

How to add it?

glass sandal
#

Do you have sqlite installed on your laptop/pc?

nova storm
#

Yup

glass sandal
#

Ok so open the database (the .db file) in sqlite3