#web-development

2 messages ยท Page 54 of 1

feral minnow
#

Guys how I can change a width of an image depending on the user screen?

cold anchor
#

in css?

#
img {
  width: 100%;
}
feral minnow
#

oh

cold anchor
#

do you mean like if it's a phone vs if it's a laptop?

feral minnow
#

I mean like I want it to take the full width of the user screen no matter what

cold anchor
#

width: 100vw; "vw" stands for "viewer-width" and represents with with of the viewing screen

#

its height counterpart is "vh" if you ever need it

feral minnow
#

oh

#

So i have to use width: vw?

#

Thanks

cold anchor
feral minnow
#

Thanks i will save this link

#

if i needed i can go and see it

stable notch
#

when using jwt auth for single page app, should i issue a new refresh token in addition to an access token when someone uses the refresh endpoint with a valid refresh token?

#

the oath rfc says that this is optional, but i am concerned because an attacker with the refresh token could use someone's account indefinitely since the expiry of the refresh token would be reset on refresh

native tide
#

First time Ive ever had to do this

from shellmancer.forms import (
    RegisterForm, LoginForm, NewCampaignForm, UserSettingsForm, RequestResetForm, PasswordResetForm, RequestVerifyForm,
    UpdateCampaignForm
)
#

That is, start a new line on an import statement.

rigid laurel
#

If you're doing that, I personally much prefer one thing per line - e.g

from shellmancer.forms import (
    RegisterForm, 
    LoginForm, 
    NewCampaignForm,
    UserSettingsForm,
    RequestResetForm, 
    PasswordResetForm,
    RequestVerifyForm,
    UpdateCampaignForm
)```
That's what I've seen in a lot of os projects as well
#

IIRC, the Pydis projects use this as well

native tide
#

ah yeah thats pretty good.

#

Those lines do fall into below 80 characters

native tide
#

I'm starting to understand why Django over time developed so many new approaches to streamline everything. When you're learning it, it feels like you're taking a bunch of short cuts to accomplish tasks you dont really understand what's going on under the hood. But after you have repeatedly made very similar routes/views over and over and over again, you start to get it.

feral minnow
#

Actually i feel you but not with Django

#

with for loops lol

#

I was not understanding it too good but after doing some projects and using it a lot

native tide
#

Well, the project Im working on now is Flask. Flask doesnt have the short cuts that Django has. If you ever learn Django you'll know what I mean.

#

Thats honestly why I think its probably better to learn Flask first because Django isn't very good at teaching you how backend design works.

#

Mainly because it just does everything out of the box

feral minnow
#

oh

#

Im learning flask

#

its not that hard

#

or the level im in rn is not hard

native tide
#

I think it depends on what you're doing with it and how big the scope of it is. But yeah, its not that hard. But for example, you know how you have to install something to hash your passwords and in the process of doing it you learn that its important to not save plaintext passwords?

#

Well in Django you dont learn that lesson because Django does it for you.

#

Thats what I mean. Its good at getting a lot of work done really fast.

#

But if you dont understand backend design, Django isnt going to teach you how it works

feral minnow
#

oh

#

So its better to know whats going on

#

and how it works

native tide
#

I think so. I think both frameworks are worth learning if youre into webdev.

#

at least the basics of them and you can decide which you prefer

feral minnow
#

But some times I feel like we are only using the things that they offer

#

like how they created it

native tide
#

Well part of the philosophy of Flask is to have as minimal things done for you as possible so that you can easily implement things the way you want to. It takes more effort but ultimately allows you to change things more.

onyx crane
#

dont wanna interrupt but i got a question :D

native tide
#

Inj Django, editing default behavior is a pain in the ass

#

It can be done but its a pain

#

Sure

onyx crane
#

how can i set a specific context in django ?
Instead of the .objects.all, how can i use some with a condition ?
Or do i do that later on in the html ?

native tide
#

Hold on. Its been a while since I used the ORM to query. Let me look it up.

onyx crane
#

Is there another, "better" way ? or have you just not used it yourself recently :)?

native tide
#

No, if you're using Django, that is the best way to write queries

onyx crane
#

ah cool. So its basicaly djangonized SQL

native tide
#

I am mainly using Flask lately.

#

Exactly.

#

Django has an enteresting query syntax where you have fieldname__filtermethod

#

For example if you have a column called headline

#

a bunch of methods are created like headline__startswith

#

So you insert the colums you have and you can use those methods on the right side of the __

#

gte is greater than or equal to for example

onyx crane
#

thx :) will see what i can do

#

Whats the main reason for you using flask, besides learning the background design ? I am by no means a web developer but just smushing a website together for my D&D campaign so i figured django would be faster to implement

native tide
#

The main reason Im using Flask is because I'm creating a site that is nothing like any site I can imagine. Its a web game where I have to make a lot of unique things. And it makes it really hard to edit things, like for example the default User class, etc. If I was making a typical website, like a full featured blog or news article site, I would just use Django because it would make it less time consuming.

#

But because my idea is not like any basic website, its hard to fit into Django

onyx crane
#

What exactly are you trying to do?
I am planning to implement a little interactable map at a later stage with html5 canvas. Is this not possible with Django ?

native tide
#

You will end up using JavaScript to do that part. But you can mix those things Im pretty sure without trouble.

#

It's basically an RP site.

onyx crane
#

Yeah im aware. But how i understood flask i'd need to to js for that part anyway ?

native tide
#

If you're familiar with what RPGs are

#

Yeah no matter what that is the type of thing you have to make with JS.

onyx crane
#

"It's basically an RP site."
Yours or mine ?

native tide
#

mine

onyx crane
#

so what does it do thats not possible with Django ? I couldnt quite follow

#

im curious if i run into the same issues

native tide
#

There is really nothing that the other can do that isn't possible with either

#

Its just a different approach and depending on what you're doing, one might be more work than the other.

#

I think its worth making time to try out both if you're going to get into it just because they both have a use case imo.

onyx crane
#

hm, thats very broad but i guess i know what youre trying to say

native tide
#

I can tell you what made me decide that Django wasnt for my current project. It was looking through classes trying to figure out what to inherit into my new user class to make edits to the default user system.

#

Thats very often what editing Django is like, "Scrolling through miles of documentation for the class you have to edit and properties you have to add to it to make something different."

#

In Flask you would just start by writing that class yourself.

#

So in some ways if youre trying to "reinvent the wheel" Django makes it more of a pain.

#

If you're not trying to do that, Django is better

#

or at least, its less work

onyx crane
#

thats way better :)! i get that

#

kinda feels like working with a big framework in a nutshell ?

native tide
#

yes.

onyx crane
#

check

native tide
#

One is massive with everything you nee working perfectly.

#

The other is small with little pieces of things you have to fit together

#

But sometimes how massive it is makes it hard

onyx crane
#

yeah... i was so happy when i moved from .net to python and away from the freaking frameworks, but since i have such little knowledge of web at all im actually thankfull for the small "fill in this and this" parts :D

feral minnow
#

Yo guys I have a question if there's no problem

#

I want to get values from 2 select field

#

but this is really getting me crazy

#

So first I put them on the same route

#

Its was taking the values

#

but after it take the second select field value the first one will be None

#

So I created another 2 routes or functions that contain them

#

now I can't get their values

#
def startChapter():
    print("hi")
    form=Chapters()
    ChaptersName = session["ChapterList"]
    form.startChapter.choices = [ (chapter,chapter) for chapter in ChaptersName]
    checker=session["checker"]
    
    if request.method=="POST":
        print("Hi folks")
        session["startChapter"]=form.startChapter.data
        print("t",session["startChapter"])
        session["startChapter"]=session["startChapter"]
        print("t",session["startChapter"])
        
        chapterEnd = []    #This will contain the rest of chapters (up to 60 chapter)
        try:
            session["startChapter"]=form.startChapter.data
            Index=ChaptersName.index(session["startChapter"])
            for i in ChaptersName[Index+1:Index+61]:
                chapterEnd.append(i)
            print(chapterEnd)
            session["endChapter"] = endChapter    

                
        except:
            pass
        print("Hi")
        #return redirect(url_for("endChapter"))
    return render_template("startChapter_manga.html",form=form)

@app.route("/endChapter", methods=["POST","GET"])
def endChapter():
    form=Chapters()    
    checker=False
    chapterEnd = session["endChapter"]
    form.endChapter.choices = [ (chapter,chapter) for chapter in chapterEnd ]


    if request.method=="POST":        
        print("hi end")
        session["endChapter"]=form.endChapter.data
        if session["startChapter"]==True and session["endChapter"]==True:
            manga()
                    
                

    return render_template("endCh.html",form=form)```
#

first thing all of these two functions is depending on another one which give the options for the first select field/function

#
def manga_front_end():
    form=Chapters()
    if request.method=="POST":
        print("yo")
        try:
            session["link"]=request.form["link"]
        except:
            pass
        link=session["link"]
        #Scrape chapters
        res=requests.get(link)
        #print(link)
        res.raise_for_status()
        soup=bs(res.text,"html.parser")
        
        
        Elem=soup.select("a.chapter-name")
        
        ChaptersName=[]
        session["ChaptersName"]=ChaptersName
        for i in range(len(Elem)):
            href=Elem[i].get("href")
            regexName=re.compile(r'chapter_\w+\.?\w*/?')
            regexFind=regexName.search(href).group()
            fullName=regexFind.replace("/C","",1)
            fullName=fullName.replace("_"," ",1)
            ChaptersName.append(fullName)
        
        ChaptersName.reverse()
        
        #Create sessions for other functions 
        session["ChapterList"]=ChaptersName
        link=session["link"]
        chapterStart=session["ChaptersName"]
        currentName="Start Chapter"
        

        #print("This sucks")        
        return redirect(url_for("startChapter"))


    return render_template("manga.html",form=form,checker=True)``` Here it is
#
{% block title %} Downloader {% endblock %}

{% block content %}l>
                {{form.hidden_tag()}}
            <form  method="post" action="/"  >
              <div>
                <label> Manga </label>
                   <input type="text" name="link" size=50 placeholder="Enter the url" />
                    <input type="submit" value="Click"/>
              </div>
            </form>
        
            <form method="post" name="ch"  action="/startChapter">
                <label>Start Chapter</label>
                {{form.hidden_tag()}}
                {{ form.startChapter }}
                {{form.submit}}
          </form>
        
{% endblock %}``` html code for the first select field
#

so if you see the action

#

when I put it to /startChapter

#

its returning this error TypeError: Object of type function is not JSON serializable

#

wait it actually getting the value of the first function

charred scroll
#

is there a field type for FlaskWTF that just acts as a view for a field? like in my table I have a primary key which obviosuly the user shouldn't be able to edit it but I would like to display it

feral minnow
#

oh

#

you mean something with out a post method

#

something like this?

#

its not a flask form

native tide
#
@app.route('/test')
def testing():
    test = Test.query.get(2)
    return render_template("testing.html", test=test)

in a testing.html

{{ test.id }}

This is assuming that the record is already in your database, you no longer need the form to display it.

feral minnow
#

oh

native tide
#

2 is the primary key id for Test, a class in your models

feral minnow
#

im not using data bases

charred scroll
#

I think hidden still allows it to be submitted if you do it via the request headers directly

feral minnow
#
   
       #Link = TextField("Enter the manga link here", validators=[DataRequired()])
       startChapter= SelectField("Start Chapter", choices=[], validators=[DataRequired()])
       endChapter= SelectField("End Chapter", choices=[], validators=[DataRequired()])
       submit= SubmitField("Choose")```
native tide
#

Yeah it looks like you're using your site to scrape content, which you might not need one.

charred scroll
#

kinda just wanted flaskwtf to do all the html generation ๐Ÿคฃ

like
user_id = ViewField("ID", value=User.user_id)
thats kinda what I wanted

native tide
#

I will warn you that... the trouble with putting a lot of effort into a scraper is that as soon as the site changes their layout, it breaks your site. Its kind of sad when it happens. You learn that you have to have all selectors in a place separate from everything else. And to keep it working you have to edit the selectors every time they change their site. It makes it slightly less work but its still a pain.

#

But if your design has random selectors all over the place

#

You'll hate yourself when it happens.

feral minnow
#

oh

native tide
#

Its part of scraping though.

feral minnow
#

actually I have one selector

native tide
#

Oh really? Well then thats not too bad

feral minnow
#

I got from it all things

#

then edit it depending on what user choose

#

like what my script does is go to a website scrape some data

#

but I want to get what user choose

#

its not working

onyx crane
#

How can i set users as the context in django ?

#

this tutorial suggests accessing content that is connected to a user like this:

view.html

{% extends "main/base.html" %}

{% block title %}
View

{% endblock %}

{% block content %}
    {% for td in user.todolist.all %}
    <p><a href="/{{td.id}}">{{td.name}}</a></p>
    {% endfor %}
{% endblock %}

But user isnt a context

#

i tried the following but it didnt work:

def characterdisplay(request):
    return render(request = request,
                template_name='main/characterdisplay.html',
                context = { "user": User.objects.all} )
#

worked by using request.user. Is there a reason why user doesnt work anymore

native tide
#

try print(user) on the page somewhere and see what user is returning

#

I also have a question. What CSS properties or bootstrap classes can I use to get these elements in the center of the columns so that they are equally spaced?

#

I figured it out.

#
.center {
  display: block;
  margin-left: auto;
  margin-right: auto;
}
native tide
#

PArt of me wishes I was the sort of shameless asshole who would copy this entire fontawesome directory into my static files just to use a couple of icons.

#

but instead I will go through them and hand pick the ones im using

lilac root
#

Hey I need a bit of help
Client (sends data) -> Django (consumer.py) -> Db (fetch latest updated record from the db, based on clients requirements) -> Django -> Client.
After this initial sequence of events, I need to design a system where, the database keeps a track of the same row that the client requested and keep send those updates back to the client.
Db (updated) -> Django (signal.py, looks for updates) -> Django (consumer.py) -> Client

harsh flare
#

so i messaged yesterday about 403 issues on my .js and .css files. I change the permissions on the files and static folder but it still is throwing a 403 error?

native tide
#

what kind of server?

harsh flare
#

linux nginx

native tide
#

ls /etc/nginx/sites-enabled/

#

What file do you have in there and have you edited to proxy pass static files?

harsh flare
#

one file "flaskapp" and its contents ``` "
server {
# listen on port 80 (http)
listen 80;
server_name _;
location / {
# redirect any requests to the same URL but on https
return 301 https://$host$request_uri;
}
}
server {
# listen on port 443 (https)
listen 443 ssl;
server_name _;

# location of the self-signed SSL certificate
ssl_certificate /root/certs/cert.pem;
ssl_certificate_key /root/certs/key.pem;

# write access and error logs to /var/log
access_log /var/log/flaskapp_access.log;
error_log /var/log/flaskapp_error.log;

location / {
    # forward application requests to the gunicorn server
    proxy_pass http://localhost:8000;
    proxy_redirect off;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}

location /static {
    # handle static files directly, without forwarding to the application
    alias /root/AQChess/static;
    expires 30d;
}

}

native tide
#

As to your server config...

#

mine is a lot simpler

#

obviously the listen stuff before this

#
        root /var/www/html;

        server_name wsi;

        location = /favicon.ico { access_log off; log_not_found off; }
        location /static/ {
                root /home/woot/project;
        }
        location /media/ {
                root /home/woot/project;
        }

        location / {
                include proxy_params;
                proxy_pass http://unix:/run/gunicorn.sock;
        }
}
#

wsi is the name of my computer. username@wsi:~$

#

I dont know if that would help

harsh flare
#

i'll make some edits and see. Not sure how mine is much different. Still passing location /static in both in the same kind way no?

#

Hmm still nothing

#

I was following through this tutorial for all the conf set up

native tide
#

are you restarting gunicorn?

#

I dont know why that would matter really.

harsh flare
#

Restarting supervisor thats handling gunicorn yeah

#

done that

#

cleared cache and cookies to check

#

not sure whats wrong

lilac root
nova storm
#

can anyone tell me how to create virtualenv folder by cmd

#

my cmd saying "virtualenv is not an internal or external command"

native tide
#

try python -m pip virtualenv

#

im not sure because i dont use err

#

python -m virtualenv

#

and if that doesnt work python -m pip install virtualenv

obsidian parrot
#

how do you use javascript in bootstrap

#

i cant find an up to date tutorial online

#
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>``` i have this at the bottom of my body tag like the template in the documentation said to do
#

not really sure what else to do

harsh flare
#

Definitely frustrating. No idea why the static folder in this nginx flask setup is throwing a 403 error.

#

tried adjusting permissions to static folder ```
sudo chmod -R 664 static
sudo chmod -R a+X static


Even going extreme and chmod 777 myapp folder (I know not to do normally) doesn't even work so it can't be a folder rights issue?
ornate hawk
#

How can I put some html in a render_template() (like this : render_template(my_page,html_to_add=a_html_text) ) (using flask)

#

because when I try it, it convert symbols like < into a char code

zenith mason
#

Hello Everyone

ornate hawk
#

really ?!

zenith mason
#

Sorry, I'm new Here

ornate hawk
#

sorry, I didn't know it.

zenith mason
#

I'm I in the right place to ask about Laravel?

ornate hawk
#

I think

zenith mason
#

I'm a beginner in web development seeking a Mentor

#

I'm a good Student anyone that could help will be helping a Soul

#

I want to give myself to this course and live with it. Please

harsh flare
#

Laravel is PHP right? No Python? This is a Python focussed discord, but you may find help here. You're better off coming here with specific questions that you need an answer to!

zenith mason
#

Okay, Thanks!

#

I actually needed a mentor for Web Development Someone who will guide me through the right path.

#

just so I don't wonder about the internet with so many projects and nothing to show for it after a long time investment.

#

i don't mind putting up with python if it leads right. Please

#

A course could help...

onyx crane
#
{% for item in inventory.item.all %}
                                <div class="card blue darken-1">
                                    <div class="card-content white-text">
                                        <p>{{item.item_name}} {{item.item_weight}}kg {{item.item_price}}$</p>
                                        

                                    </div>
                                </div>
                                {% endfor %}
#

How would i split the 3 attributes in a repeatable spacing ?
Like a table without the table lines.

Do i need to use grid or flexbox even for simple rows ?

native tide
#
 0.0.0.0:8880 wsgi:app
[2020-04-16 13:03:09 +0000] [2937] [INFO] Starting gunicorn 20.0.4
[2020-04-16 13:03:09 +0000] [2937] [INFO] Listening at: http://0.0.0.0:8880 (293
7)
[2020-04-16 13:03:09 +0000] [2937] [INFO] Using worker: sync
[2020-04-16 13:03:09 +0000] [2940] [INFO] Booting worker with pid: 2940
[2020-04-16 13:03:12,803] ERROR in app: Exception on / [GET]
#

my app breaks on refresh

fossil mist
#

@onyx crane You also have the margin alternative, but yeah flexbox could be a good option

onyx crane
#

margin will differ the word poisitions if i have different word length though

blazing jetty
#

Can I use flask with a wordpress site?

somber burrow
#

Django Question
How do I place a degree symbol in my jinja. Tried a bunch of tags and I can't seem to get it to work

<table class="table">
    <thead>
        <tr>
            <th>Date</th>
            <th>Device</th>
            <th>Temperature</th>
            <th>Humidity</th>
            <th>Online</th>
        </tr>
    </thead>
    <tbody>
        {% for temp_device in temp_devices %}            
        <tr>
            <td>{{ temp_device.sample_date|date:"dMy Hi"|upper }}</td>
            <td>{{ temp_device.device_name }}</td>
            <td>{{ temp_device.temperature }} {{ u\N{DEGREE SIGN}|escapejs }}</td>
            <td>{{ temp_device.humidity }}</td>
            <td>{{ temp_device.device_online }}</td>
        </tr>
        {% endfor %}
    </tbody>
</table>
queen bough
#

@somber burrow Can't you just put the unicode symbol there?

coarse furnace
#

@blazing jetty with?

blazing jetty
#

?

coarse furnace
#

@somber burrow did you try &deg; ?

#

@blazing jetty so they coexist on the same domain?

blazing jetty
#

Can I run python script and website from somewhere? A discord bot script and?

coarse furnace
#

with Wordpress hosting?

blazing jetty
#

any hosting

#

cheap hosting I guess, idk

coarse furnace
#

yes, but I don't understandwhat you mean by "flask with a wordpress site" ๐Ÿ™‚

somber burrow
#

Thanks for the input! I got it to work, thank you ๐Ÿ™‚

coarse furnace
#

@somber burrow excellent ๐Ÿ™‚

blazing jetty
#

well can you use flask with wordpress site @coarse furnace

coarse furnace
#

no

blazing jetty
#

F

#

what should I do to get my discord bot running (python) and the website (flask with render_template) @coarse furnace

coarse furnace
#

get a VPS, they go for as low a $5/mo.

storm minnow
#

Hey all. I am a Data Scientist who is looking for a assistant. Let 's discuss more detail via DM

cerulean vapor
blazing jetty
#

@coarse furnace what VPS do you recommend? How can I host flask website from there?

coarse furnace
#

I use Linode, but I have not tried others.
You could set up Nginx, supervisor and Gunicorn and run them from there.

blazing jetty
#

ok thx, I'll check em out

lofty matrix
#

What is the official name of the feature where you can go to
www.mypage.com/index.html#this_is_an_id
and your browser will jump down to the element with that ID? I've seen HTML anchor, HTML bookmark, HTML link, but none of these seem to be the official name. I'm trying to find it on caniuse.com

native tide
#

does anyone know why these give an erorr

cerulean vapor
#

@lofty matrix I think "anchor" is the official term and I can't think of a single browser that doesn't support it at this point

#

@native tide the line <hr class="my-4> is missing a close quote

#

Whenever you have a problem in a file, work backwards from the first place where it reports an error

native tide
#

ty

lofty matrix
#

Thanks. I think it's difficult to find because of the name conflict with <a>

somber burrow
#

How can I get rid of this spacing in temperature?

#
{% block content %}
    <div class="table-responsive">
        <table class="table table-bordered table-hover table-sm">
            <thead>
                <tr>
                    <th>Date</th>
                    <th>Time</th>
                    <th>Device</th>
                    <th>Temperature</th>
                    <th>Humidity</th>
                    <th>Online</th>
                </tr>
            </thead>
            <tbody>
                {% for temp_device in temp_devices %}            
                <tr>
                    <td>{{ temp_device.sample_date|date:"dMy"|upper }}</td>
                    <td>{{ temp_device.sample_date|date:"Hi" }}</td>
                    <td>{{ temp_device.device_name }}</td>
                    <td>{{ temp_device.temperature }}&#730</td>
                    <td>{{ temp_device.humidity }}%</td>
                    <td>{{ temp_device.device_online }}</td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
    </div>
{% endblock %}
onyx crane
#

which spacing ?

toxic marten
#

Try <td align="center">your content</td>

somber burrow
#

The spacing in the temp column

#

@onyx crane @toxic marten

Sorry surinam, didn't get a notification

cold anchor
#

if there's no space around the temperature cell values the cell header "Temperature" text gets cut off. The reason you have that space in the column is because it's making room for the whole word "Temperature"

somber burrow
#

OH DUHHHH

#

thank you xD

cold anchor
#

๐Ÿ‘

onyx crane
#

thats what i was wondering about too :D

#
class Inventory(models.Model):
    inventory_owner = models.ForeignKey(PlayerCharacter, on_delete=models.CASCADE, related_name="inventory", null=True)
    inventory_name = f"{inventory_owner.pc_name}s Inventar"
    inventory_items = models.ManyToManyField('Item', related_name='inventorys')

    def __str__(self):
        return (f"{self.inventory_owner.pc_name}s Inventar")

I get an AttributeError => that inventory_owner (Foreignkey) has no attribute pc_name. In the return function, it does though ... why can't i access it here ?

cold anchor
#

inventory_owner is a ForeignKey that references the PlayerCharacter table by the primary key

#

it's not an instance of a PlayerCharacter

onyx crane
#

Yeah thats the idea :'D

#

but how would i access its attribute inside of the Inventory Class ?

cold anchor
#

depends on how you want to use it- do you want to store it in the database or can it be constructed at runtime from an instance of Inventory?

onyx crane
#

I want to do a many-to-many relationship between Inventory and Item.
At the same time i want my Inventory to be attched to one PlayerCharacter. I thought id need a Primary Key for that and wanted the primary Key (inventory_name) to be related to the PlayerCharacter who owns the Inventory.

I dontthink i fully understand what youre asking ? I think both would work. I don't need the value except as a primary Key so that means it could be constructed at Runtime ?

nova storm
#

my cmd not making virtualenv folder

#

what to do?

cold anchor
#

@nova storm take an available help channel please, this one is occupied

nova storm
#

what? why?

#

okay!

cold anchor
#

which database are you using @onyx crane ? not all of them require primary keys- and in fact, your foreign key does what you want

onyx crane
#

SQLite

cold anchor
#

I'd suggest settings nullable=False, index=True in your ForeignKey(...)

#

ah, well I'm not super experienced at that, so I can advise whether or not a primary key is required, but I'm pretty sure SQLAlchemy gets confused without a primary_key=True argument in at least one of the columns, whether or not it actually has a primary key

onyx crane
#

ill look into that next :D
So is there a way to access the inventory_owner.pc_name to include it in the primary key?

cold anchor
#

I'm not sure if you can do a partial foreign key, but you can definitely make a property of your class include the inventory owner name

#
    ...
    @property
    def inventory_name(self):
        return f'{self.inventory_owner.pc_name}s Inventar'
    ...
#

I'd suggest making it a property that's built on-the-fly instead of stored in your database

onyx crane
#

let me try that out :) thanks already

cold anchor
#

also sorry @nova storm I got confused and though this was a help channel- my bad!

nova storm
#

@cold anchor its okay dude!

native tide
#

hi everyone, someone know a good django dashboard template autocomplete ?

cold anchor
#

what are you trying to autocomplete?

native tide
#

autocomplete field

cold anchor
#

like google?

native tide
#

no just for django admin

cold anchor
#

I'm going to need you to be a little clearer, I can't really understand what you're asking

native tide
#

i looking for somethink like that : https://github.com/geex-arts/jet

#

but with autocomplete field

cold anchor
#

it seems like you're talking about 2 different things, 1 is a django admin template, the other is a type of input field

#

also autocomplete is usually controlled by the browser and depends on the html field configuration

native tide
#

ok i read that thank you

cold anchor
#

or do you mean an autocomplete to suggest things based on data in your database?

native tide
#

yes thats i want

cold anchor
#

you'll have to build that yourself, I think, because it depends on how you want to handle search

somber burrow
#

Reading through django docs. It looks like the appropriate way to add images or icons is to add them in the static/ directory under each application. What if I am implementing a root html file that contains the navbar for all my apps. What would be the right convention to source an image?

#

I currently have a root level templates/ directory and I was planning on placing images there but not sure if this is the right way?

#

Actually found something on STATICFILES_DIRS will use that. Thank you ๐Ÿ™‚

somber burrow
#

Huh - so I followed the instructions but I am getting static load errors

#

I registered the directory

#

and am using jinja to call it, but it doesn't work?

#
    <!-- Navation bar-->
    <nav class="navbar navbar-light bg-light">
      <a class="navbar-brand" href="#">
        <img src="{% static 'images/lizard.jpg' %}" width="30" height="30" class="d-inline-block align-top" alt="">
        Khalitos Way
      </a>
    </nav>
#

That's my settings page

coral current
#

@somber burrow - i managed to display static images this way.
my settings page:

#

then i just use the full path

#

<img src='home/pi/django_webapp/templates/images/lizard.jpg' alt="">

#

im having some issue with django forms as well... (running development server):

  1. displaying an image that the user just uploaded, I have tried passing the obj as context / image path as jinja but it doesnt work
  2. can someone point me to (an article) what to change for deployment with firebase
somber burrow
#

LOL I wasn't using load first

    <nav class="navbar navbar-light bg-light">
      <a class="navbar-brand" href="#">
        {% load static %}
        <img src="{% static "images/lizard.jpg" %}" width="30" height="30" class="d-inline-block align-top" alt="">
        Khalitos Way
      </a>
    </nav>

I did add your join though

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "templates/static")
]
#

Thank you ๐Ÿ™‚

coral current
#

ah so its working? super

somber burrow
#

Yes thanks ^_^

coral current
#

Yes thanks ^_^
@somber burrow ๐Ÿ‘

feral minnow
#

Whats up guys

#

Im getting this error TypeError TypeError: Object of type function is not JSON serializable

#
@app.route("/startChapter", methods=["POST","GET"])
def startChapter():
    print("hi")
    form=Chapters()
    ChaptersName = session["ChapterList"]
    form.startChapter.choices = [ (chapter,chapter) for chapter in ChaptersName]
    #checker=session["checker"]
    
    if request.method=="POST":
        chapterEnd = []    #This will contain the rest of chapters (up to 60 chapter)
        try:
            session["startChapter"]=form.startChapter.data
            print(session["startChapter"])
            Index=ChaptersName.index(session["startChapter"])
            for i in ChaptersName[Index+1:Index+61]:
                chapterEnd.append(i)
            print(chapterEnd)
            session["endChapter"] = endChapter    

                
        except:
            pass
        print("Hi")
        return redirect(url_for("endChapter"))
        print("yosao")
    print(form)
    return render_template("startChapter_manga.html",form=form)

@app.route("/endChapter", methods=["POST","GET"])
def endChapter():
    #print("THUG LIFE")
    #form=Chapters()    
    checker=False
    chapterEnd = session["endChapter"]
    form.endChapter.choices = [ (chapter,chapter) for chapter in chapterEnd ]


    if request.method=="POST":        
        print("hi end")
        session["endChapter"]=form.endChapter.data
        if session["startChapter"]==True and session["endChapter"]==True:
            manga()
                    
                

    return render_template("endCh.html")```
#

Im trying to make a select field

#

and let the user choose

#

the first function work fine

#

but when it come to return redirect(url_for("endChapter"))

#

It shows this error as above TypeError TypeError: Object of type function is not JSON serializable

#

I think the error is coming from the first function for some reason

#
{% block title %} Downloader {% endblock %}

{% block content %}
                
            <form  method="post" action="/"  >
              <div>
                  
                <label> Manga </label>
                   <input type="text" name="link" size=50 placeholder="Enter the url" />
                    <input type="submit" value="Click"/>
              </div>
            </form>
        
            <form method="post" name="ch"  action="/startChapter">
                <label>Start Chapter</label>
                {{form.hidden_tag()}}
                {{ form.startChapter }}
                {{form.submit}}
          </form>
        
{% endblock %}```
#

here's the html code for it

#

it worked i gave a wrong value for a variable

#

so I think it was treat it like a class or function

kindred glacier
#

Can someone help me with this flask question I have? It seems like can't get answer anywhere

feral minnow
#

@kindred glacier which elif

kindred glacier
#

@feral minnow someone recommended my to swap the order of if and elif and it works now

feral minnow
#

oh nice

native tide
#

I know a bit of Python and a little JavaScript.

#

I need your opinion on this one

#

should i learn NodeJS or Django?

cerulean vapor
#

@native tide this is a Python server, so you're almost always going to get a Python-centric response

#

if you want to learn a web framework in Python, perhaps start with a simple one like Flask

trail thunder
#

i'd actually say nodejs, depending on what you're looking for

#

it's certainly the faster choice in terms of an API

native tide
#

I need to use one of them as my backend

trail thunder
#

for what?

native tide
#

a website

#

It's either HTML CSS NodeJS or HTML CSS Django

trail thunder
#

i'd choose nodejs

#

django is going to have a lot of bulky things with it you might not need

#

and nodejs is just faster

#

fastest python has in comparions afaik is blacksheep and even then

native tide
#

i see

trail thunder
#

i refer to that a lot. it's a very good benchmark from what i've heard and while it's not a one stop shop, you can get a pretty good idea at what you may want to look into

native tide
#

thx

native tide
#

I have cloudflare pointed to ip @ https://pi.sminfo.me/
Why does gunicorn work on that
But I need an ip address and port to show @app.route wiki
and nginx config
proxypass

kindred glacier
#

When you deploy your app on a live server what do enter for databse path?

#

for example when it's hosted on my own computer i use regular path

#
def get_db():
    db = getattr(g, '_database', None)
    if db is None:
        db = g._database = sqlite3.connect("C:/Users/user/Desktop/Python projects 2/Flask Grocery List/database.db")
        db.row_factory = sqlite3.Row
    return db```
native tide
#

You cant use sqlite3 anymore. You have to enter the path to the server with the credentials. For example...

#

postgres://username:password@192.168.1.123/name_of_database

kindred glacier
#

why can't I use sqlite3?

native tide
#

Because sqlite3 isnt a real database. Its a file that runs locally on your computer. When you have a database online, other people have to connect to it to add records, to make accounts, and etc. You facilitate the connection through your code so they dont have to think about it.

#

Databases are kind of learning curve... But If you deploy to heroku with your first app, which I would recommend if you dont have the abilitiy to run your own server yet... they have a free add on of a postgres server.

#

And thats a great place to learn about it for your first time if you're not very familiar with sysadmin or virtual machines.

#

Alternatively you can try to set up your own server on a VM if you have the ability to do that

kindred glacier
#

whats the point of using sqlite3 then?

native tide
#

To make it easy to develop locally and for programs that no one else needs to connect to that only run on your machine.

kindred glacier
#

Thanks

native tide
#

Databases are kind of a learning curve. Its easier to jump in and learn to make queries with sqlite than admin of a real database

#

While Im not recommending this entire series because it kind of goes too heavily into Angular imo...

#

This is a good article that will teach you to set up your first heroku staging and production server with free database add on of postgres

native tide
#

@kindred glacier Yeah the learning curve was tough for me too but I got used it to it ๐Ÿ˜’

#

Sql syntax is easy enough

native tide
#

The hard part is if youve never had a reason to do any sysadmin tasks previously, thats new. The second part that is hard is if you're designing a database for the first time, you most likely are not doing it perfectly or at least will want to add things. And the migrations is hard.

#

Querying for whats already in there is something you can learn in an afternoon.

#

But building the database and particularly changing it once theres stuff in it is not easy.

#

I'm at the point where I have to heavily refactor my app into flask blueprints.

#

But I think I will take the entire day/night to not do any programming stuff and start tomorrow.

half scarab
#

Wich flask WSGI server would you reccomend?

native tide
#

Has a list

#

I use Gevent mmShrugMocha

half scarab
#

Thx

harsh flare
#

What are the limits of the bootstrap popover content? can I put html with a js script in there?

native tide
#

hi

#

instead of a database I would like to use a text file. Store the data in the txt file and in my case it has to work with GET and POST requests

#

could anyone help me out a bit

cloud path
#

hey guys, does anybody know a free social network template such as facebook/instagram? I just want to code the back-end with python as training and I just need a premade front-end

ornate hawk
#

How can I use html code as kwarg with flask.render_template() ?
For exemple : ```py
import flask
app = flask.Flask(name)

def a_func_that_generate_html():
return "<b> an html template for a template </b>"

@app.route("/a_page")
def a_page():
return flask.render_template("a_page.html",html_to_generate = a_func_that_generate_html())

if name=='main':
app.run()

#

Because when I run my code (it's like the exemple) it's not writing "<", but "&some_char_code"

ornate hawk
#

It makes now 2 days, that I'm searching an way to do this.

native root
ornate hawk
#

ok thx, perfect !

echo roost
maiden patrol
#

I am quite new to python and I want to make a basic website which will show the total number of confirmed covid cases

#
import json
import urllib.request

url = 'https://thevirustracker.com/free-api?global=stats'
response = urllib.request.urlopen(url)
result = json.loads(response.read())
print(result)

status = result['stat']

confcases = result['total_cases']
print(confcases)```
#

I put this together, I am getting a result for status but I am getting an error for total_cases

native tide
#

refactoring a flask app into a blueprints series of packages after your app is already huge is a terrible thing to have to do

#

Also, what is the error? Is it a key error?

#

And what is the status code?

supple loom
#

Is it necessary to install dependencies inside a virtual environment only or we can also install it inside the project directory ?

fading mason
#

anyone here familiar with AWS deployment?

#

Im trying to deploy my django app to aws but Im getting an error that says: Engine execution encountered an error

#

this is on elastic beanstalk

#

if someone can help pls dm me or ping me

nova storm
#

ohh guyz mistakely i have deleted my venv folder in pycharm

harsh flare
#

Anyone know how I could create a different id in a jinja for loop that also apply to the JS script as below:

<div id='myboard' style="width: 400px"></div>

<script>
   var board = ChessBoard('myboard', cfg);
</script>
#

I have a ``` {% for x in list %}{% endfor %}

#

but it doesn't seem to like it when I just put {{x[4]}} in.

native tide
#

how can i integrate the google sign in to my login page

#

?

nova storm
#

just add it from google

#

@native tide

#

wait let me send u link

quiet mirage
#

I'm thinking to pick up some VPS hosting for a personal website, and grounds for experimenting with various server things. Uncertain about which OS type would be best. Python will definitely be used, undecided on the server software itself. I would almost prefer to use one of the Python servers rather than Apache which I use at home.

So kinda asking if anyone has tips on which OS type might be friendliest to set up a web server, and other related services that use Python. Kind of looking between Ubuntu because I've used in the past, or FreeBSD because I've been wanting to try it out/learn it and I hear its very nice for a server environment. There are other choices, but those are my main two

restive kindle
#

Ubuntu is more of a consumer distro, it isnt dissimilar to debian - which its based upon. I would try and go commandline to remove overheads / disable the UI when you are not using it.

#

My HTML/CSS question: Is there a way to emulate the blur (backdrop-)filter without actually using it? Such as using a background-image

lofty cargo
#

Hi,

I'm using HTTPBasicAuth from requests to get data via API. Do i need to use it for each request?
I would like to use it if auth dropped. Is there any way for this?

tired root
#

@quiet mirage Unless you plan on using Flask, just get a managed web

#

I'd rather recommend using a static site generator based on Python

#

Because administrating your own web isn't trivial

#

Dealing with bugs and attack vectors isn't either

#

A static site does not offer these attack vectors, but administrating a vps is a lot of trouble, compared to the 3โ‚ฌ/month I pay for my web hosting contract

#

@lofty cargo HTTP Basic Auth isn't a good choice

#

If you need your api end point being shielded, use a web proxy over ssh or vpn

lofty cargo
#

If you need your api end point being shielded, use a web proxy over ssh or vpn
@tired root
thank you for advice. I will search about it

quiet mirage
#

Hm. I have a fair bit of experience running my own personal servers, some of them open to network with security in place to (hopefully) keep people out. And quite a bit of Linux experience in general. Thinking I'm up to the task of running a VPS, based on the amount of similar work I've done. Haven't totally decided though, so I may look in to other hosting options. Just haven't found many others that would offer me the flexibility I want.

Thank you for the advice, I definitely appreciate it. And will check around into some other types of hosting to see what else I might find ๐Ÿ‘

tired root
#

IT really depends what you want. It all boils down to this: Do you need system access?

#

as in, OS access?

quiet mirage
#

More than likely, yeah. I want to be able to try out a few different server setups. Possibily also ftp, or git as well

tired root
#

More than likely, yeah. I want to be able to try out a few different server setups. Possibily also ftp, or git as well
@quiet mirage don't...

#

use ssh

#

I am saying this because I deal with people incapable of doing something as simple as blocking RFC1918 from entering our network

#

which generates abuse emails

#

and if they reply something like "I don't understand', I lock their servers

#

and it won't be unlocked until the work I request is done

quiet mirage
#

SSH is enabled by default on most of the hosts I have seen. I've also used it in the past on my own computer, open to the network so I don't entirely see a problem with it if it's properly secured.

tired root
#

I meant ftp

#

don't use it

#

it's a plain text protocol, outdated, insecure

quiet mirage
#

FTP Isn't exactly something I'd run out to set up, but it was a thought I might want file access. I know there are more secure options nowadays, I just don't know them off the top of my head

tired root
#

sftp, ssh

#

scp

#

which is ssh

#

rsync

#

But anyway, I drifted from the topic. My point is, if you don't really need that low level access, use a static site generator for a blog or whatever and buy some managed web hosting

#

It costs less, has included traffic and causes a lot less administrative work

#

you can focus on building a site, not being a sysadmin

quiet mirage
#

I do plan on using a static site generator for at least the blog portion of the site. There are several other ideas Ive had and been wanting to put into use where I would almost certainly need the low level access. Also it's something I want to do to learn more into the sysadmin side, so kind of fits and I don't want to feel limited like most managed host plans I've seen look.

I'll still check around into some others though before making a decision. Very much appreciate your input on it, so thank you for that

dense slate
#

I have a weird Django problem. If I have a 500 error thrown from something like a bad redirect or what seems to be a view-related error, it will show my custom 500 page and log the error. However if it is something like a failed import, then I get a generic white 500 server error and no log. Am I missing something in my logger to catch these? Is there a difference between these two types of errors?

#

This is on a production server so debug=False is in place. I have to make it True to actually see the error since I'm not getting a log of it.

cold anchor
#

django can't show the custom page because it threw an error on startup- when trying to start your server versus and error it caught and handled internally

#

you can imagine that django's code is sort of like this:

# django.runserver.py

...
while self.not_received_shutdown_command:
    request = self.check_socket_for_incoming_request()
    if request is None:
        sleep(1)
        continue
    else:
        try:
            run_user_code(request)
        except Exception as exc:
            do_custom_error_handling(request, exc)
#

but if you have something like an import error, it can't even start the server, so it's actually outside of that server run loop

#

in typed languages there's such thing as a "runtime error" versus a "compile time error"- django can handle runtime errors, but you're hitting the equivalent of a compile time error, so django won't even run

feral minnow
#

what i mean is

cold anchor
#
ul {
    text-align: left;
}
feral minnow
#

it but them far left

#

I want them to stay on the center of the page but without the space

#

like the last screen shot but in center

cold anchor
#
ul {
  display: block;
  margin: 0 auto;
  text-align: left;
  width: 50%;
}
#

play with that width until you're happy

feral minnow
#

Thanks its now better

cold anchor
#
ul > li {
  white-space: nowrap;
}
feral minnow
#

Thanks a lot it worked ๐Ÿ˜„

cold anchor
#

๐Ÿ‘

native tide
#

Hello, I am doing some exercises and I tried this one, but my code is incorrect, I see that the solution is similar to what I attempted what I would like to know is what i did wrong

cold anchor
#

!or-gotcha

lavish prismBOT
#

When checking if something is equal to one thing or another, you might think that this is possible:

if favorite_fruit == 'grapefruit' or 'lemon':
    print("That's a weird favorite fruit to have.")

After all, that's how you would normally phrase it in plain English. In Python, however, you have to have complete instructions on both sides of the logical operator.

So, if you want to check if something is equal to one thing or another, there are two common ways:

# Like this...
if favorite_fruit == 'grapefruit' or favorite_fruit == 'lemon':
    print("That's a weird favorite fruit to have.")

# ...or like this.
if favorite_fruit in ('grapefruit', 'lemon'):
    print("That's a weird favorite fruit to have.")
native tide
#

?

cold anchor
#

you're missing hour before > 20

native tide
#

oh let me try that

#

thank you!

dense slate
#

@cold anchor ah that helps! So how do you log/view those errors? I assume somewhere on the server logs in that case?

cold anchor
#

it'll be in the logs of whatever tries to start the django server

#

I don't really use django, but do they provide their own server command? or do you use something like gunicorn?

lament meadow
#

Yo

#

I wrote some code to switch my first name on instagram using python requests, but it is hitting me with

"```
#

do you guys need the code?

outer apex
#

Yeah, that might be helpful

lament meadow
#
import requests
import json

base_url = 'https://www.instagram.com/'
login_url = base_url + 'accounts/login/ajax/'
username = 'rackets1'
passwd = 'password123?'
user_agent = 'user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36'

s = requests.Session()
s.headers = {'user-agent': user_agent}
s.headers.update({'Referer': base_url})

req = s.get(base_url)
s.headers.update({'X-CSRFToken': req.cookies['csrftoken']})
login_data = {'username': username, 'password': passwd}
login = s.post(login_url, data=login_data, allow_redirects=True)
s.headers.update({'X-CSRFToken': login.cookies['csrftoken']})
cookies = login.cookies
login_text = json.loads(login.text)

print(login_text)

fname = input("Name: ")

#edit = s.get('https://www.instagram.com/accounts/edit/')
post = s.post('https://www.instagram.com/accounts/edit/', {'first_name': fname})
print(post.content)
outer apex
#

And I assume the account already has an email or confirmed phone number?

lament meadow
#

Yes

#

if anyone can help me out with this, that would be great

outer apex
#

Been trying out myself and getting the same response.

#

I think it might just be Instagram's page that's the problem..

lament meadow
#

thanks for trying and nah ik people that are able to do more than just switch the username and first name but they are scummy and dont want to help

native tide
#

how did u send a piece of code like that @lament meadow . I'm new here sorry

lament meadow
#

use ` 3 times in a row

#

then enter your code

#

and then ` 3 times again

native tide
#

ight word thanks

#

i need some help with this one website im tryna webscrape. This site has mutliple "details" which goes to another link for each of them. I was able to scrape the string of each link of the details but when I'm tryna scrape data from the details links it decides to just forget everything I told it to do. Any help would be greatly appreciated im a noob.

#
import requests
from bs4 import BeautifulSoup as Soup
from urllib.parse import urljoin
URL = 'https://salesweb.civilview.com/Sales/SalesSearch?countyId=15'
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36"}
page = requests.get(URL, headers = headers)
soup = Soup(page.content, 'html.parser')

details = soup.select('td[class="hidden-print"] a')

details_urls = [urljoin(URL,link.get('href')) for link in details]
#print(details_urls); this print gives me the link for each details 

#trying to scrape data from each of those details links
for i in details_urls:
   site = details_urls[0]
#print(site) for some reason prints the link of the first details a repeated number of times, idk why   
  print(site)
  # details_site = requests.get(site, headers = headers)
   #print(details_site)
   #details_soup = Soup(details_site.content, 'html.parser')
   #print(details_soup)
glass pelican
#

hello

#

how to configure xampp to use python for mac

tired root
#

Just run the debug server

#

Xampp is not meant for production

#

So using the debug server is enough

#

@glass pelican

glass pelican
#

can you please elaborate debugging

tired root
#

app.run() in case of flask

#

that launches Werkzeug Server so you can view your website

glass pelican
#

i am using html

#

i am using html,php,ajax,angular

#

python is just for otp

tired root
#

If you just want a quick webserver, then use python -m http.server in the webroot directory

#

But does not work with php

#

Anyway, this isn't python related, therefore offtopic

glass pelican
#

yeah

#

so there is no way we can configure xammp to do so?

tired root
#

do what?

glass pelican
#

to use python

tired root
#

Xammp is download, start

#

Elaborate use python

#

you just said you are using PHP

glass pelican
#

#! /usr/bin/env python3.8

#

yeah i am using it

#

but i am using a button to generate otp

tired root
#

what is otp, what button?

glass pelican
#

that button should run a python script and update the data in database

#

OTP

#

one time password

#

it is 6 digit

tired root
#

but your script is using php

glass pelican
#

yeah

tired root
#

then just run the script from php

#

has nothing to do with Python

glass pelican
#

but when i press the button it should run a python script

tired root
#

Yes, your php code needs to do a system call

#

but again, that is offtopic, please look for a php discord

#

or just write it in php

#

doing a random 6 digit string isn't hard

glass pelican
#

yeah

#

i will find a php server

#

thanks a lot for help

#

๐Ÿ™‚

limber laurel
#

So in the documentation there are 2 ways to use Flask migrate, what difference does it make between using flask script and not usinh flask script?

iron granite
#

please @ me if you got an answer ๐Ÿ™‚

native tide
#

PermissionError at / [Errno 13] Permission denied:

#

my django gives me this error

#

@nova storm thanks yeh yesterday i found that link and did a tutorial on it

#

still have to finish my sign up page though

fresh dock
#

@iron granite beautifulsoup is the package you want

iron granite
#

@fresh dock i use Beautofulsoup already

nova storm
#

@native tide your welcome bro.

dense slate
#

@cold anchor Yea it uses gunicorn.

#

So I assume I just check the gunicorn logs.

native tide
#

bruh

glass pelican
#
<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script type="text/javascript">
        var places = [];
        $(#travel).keyup(function(keys){
            if(keys.keyCode == 13){
                var elm = document.getElementById('push').value;
                var xhttp = new XMLHttpRequest();
                xhttp.onreadystatechange = function(){
                    if(this.readyState == 4 && this.status == 200){
                        places.push(elm);
                        document.write(places);
                    }
                }
            }
        });
        
    </script>
</head>
<body>

    <div class="form">
        <form method="GET">
            First Name <input id="fname" type="text" placeholder="Enter Your First Name Here"/>
            Last Name <input id="lname" type="text" placeholder="Enter Your Last Name Here"/>
            Places visited in last 14 days <input id="travel" placeholder="Travelled Places"><button id="push" value="Add">


</body>
</html>
#

i am trying to push elements into the array when enter key is pressed in the Places visited input

#

please help me do that

#

above is what i tried

#

i am sorry if i placed it in wrong section

#

leaving python for a bit i have started some website stuff

feral minnow
#

Guys anyone know how I can make a download/loading animation(what i want is the 3 points which keep going up and down if you know what I mean )

surreal tangle
#

if you want some custom animation you use the img tag and just set a gif as source

feral minnow
#

ohh i see

#

but what i mean is just the 3 points that *. *

#

How i can explain it

#

anyway thanks for the website , appreciate it (:

#

what i meant was the 3 dots

#

I just figured out its name lol

iron granite
#

need a legend that can help me with some html parsing in python

spiral drift
#

Hello guys, I am trying to build a article recommendation site based on user interests. I have already build an API to get articles but I really hate frontend and css gives me panic attack so is there anyone interested to build this project with me as I am also a beginner and i am sure we both can learn a lot while building this.

#

@iron granite can you explain a bit more?

iron granite
spiral drift
#

Which library are using?

iron granite
#

beautifulsoup

#
soup = BeautifulSoup(skema.content, 'lxml')
    fff = soup.text
    print(fff)```
#

i got this and it prints all the innertext of the page. but i need to specify so it only gets "3f MA"

spiral drift
#

Try soup.findAll('span')

iron granite
#

then i get all innertext that has the SPAN tag

#

find_all('span', 'data-lectiocontextcard'=='HE24375160070') also gets me alot i cant use

spiral drift
#

If you want to get inner text you just need to loop through the data and do data.text

iron granite
#

i already got all innertext, but i need to specify what inntertext i need. And that is where im having trouble

spiral drift
#

U can have a if statement to check for some kind of keyword in inner text and when u find it just append that data to a list

iron granite
spiral drift
#

So from this data what exact field would you need?

iron granite
#

the "3g Ng/1"

#

which is my first class of the day

spiral drift
#

If it is the first element on that span you can just append all data to a list and then get a first element. Ex - first_element = data[0]

iron granite
#

the site is updating everyday so one day it would be [3] and other day [8]

native tide
#

I want to try using WTForms-Alchemy. Right now I'm making models and then forms for every model with SQLA and WTForms separately, and I have to get the validation to match on both form and model. Its kind of tedious. Im hoping this will be a seamless switch and then I only have to make one.

kindred glacier
#

when I make updates to my app locally whats the commend to update it on heroku?

cold anchor
#

Git push heroku master

blissful lion
#

Hey guys, I am trying to build an flask application to manage/use my discord bot (built with discordpy). Are there any tutorials for helping me understand how to do that? I was thinking of using sockets but I am not really sure what is the best approach..

native tide
#

There are guides on flask but I dont know anything about discord. Are you new to flask or just new to mixing discord bot and flask?

#

Also... I'm following a guy who is teaching es6 and typescript

#

And for some reason he downloaded this thing called lite-server from npm.

#

What I dont understand about that is... why do you need a server to test js development?

#

I just skipped that step because it seems like a pointless thing to download since js doesnt require a server

blissful lion
#

just new to mixing both

lament meadow
#

Yo guys Im trying to scrape some info from instagram but all I am getting is the response

[]
#

What I am trying to do is scrape my accounts email so I did this

import requests
from bs4 import BeautifulSoup

edit = s.get('https://www.instagram.com/accounts/edit/')
soup = BeautifulSoup(edit.text, 'html.parser')


s = soup.find_all('email')
print(s)
native tide
#

oh yes web develpment

fossil thicket
#

is it possible to crop an image with html? No css

native tide
#

I dont think so. Its generally frowned upon to style anything with HTML even in situations where the old approach to HTML means that you could. (things like <center>) HTML is for declaring the existence of an element and its features, which anything to do with styling is CSS.

frank crater
#

Why doesn't VSCode give me html snippets/autocompletion?

glass pelican
#

@frank crater you can look for it in marketplace of vscode

#

there are plenty of them

chrome vessel
#

Check the market place like vandit suggested, and also make sure your language is set to html. It should auto detect it, but if it doesnโ€™t it wonโ€™t give you any snippets.

glass pelican
#

this is a html code

#

here i am trying to push elements when enter is pressed in the input field

#

and pop when the button next to it is pressed

#

but when i call the function both of them are occuring simultaneously and the if conditions arent being checked

#

please help me fix this

#

Note: the alerts are used for debugging purpose

#

please tag me

native tide
#

hi guys

#

how did you all learn python?

glass pelican
#

@native tide i guess this is not the right channel to ask for

native tide
#

oh yeah

#

sorry man

glass pelican
#

anyways

native tide
#

yeah...

frosty mauve
#

I have a succesful working Django application I have coding throughout quaratine. It still has a long way to go but one of my next steps is to add AJAX to my favorite/like button on my ListView for my objects I am displaying. Currently, I am redirecting to the same page and this is annoying if you are scrolled own and get redirected to the page and put at the top! The solution I have read is using AJAX, however from reading about using AJAX on my Django project I have discovered serialization and rest_framework. I am a bit at a crossroads now in what I need to do...I thought I could just add AJAX to the script on the page and be done but the google searches are exploding with django serialization and passing json through creating new models and views with serialization. Any help is much appreciated ๐Ÿ˜„

queen bough
#

@hardy jewel When using Django it's best to do everything (including insertions) via the ORM.

native tide
#

I need help with JavaScript.
Each div with a class "devices" is selected and put in a list. Iterating over them, I put them into objects where I can keep record of the element and a switch that is either on or off. The purpose is to toggle the class border-purple on and off. It works on boxes 2 and 4, but on boxes 1 and 3 it does nothing. Ive checked the switches after clicking. Nothing is happening.
Here are the html elements, which are pretty simple -- https://paste.pythondiscord.com/werepajoca.py
Here is the JS

class ToggleDiv{
  constructor(elem) {
    this.elem = elem;
    this.switch = false;
  }
}

function highlightDiv(div) {
  div.elem.classList.add('border-purple');
  if (!div.switch) {
    div.switch = true;
  } else {
    div.elem.classList.remove('border-purple');
    div.switch = false;
  }
}

let div;
let toggleDivs = [];
const devices = document.querySelectorAll('.devices');
for(let dev of devices) {
  div = new ToggleDiv(dev);
  toggleDivs.push(div)

for(let i in toggleDivs)
  toggleDivs[i].elem.addEventListener("click", function(){
    highlightDiv(toggleDivs[i])
  });
}
#

I'm not very good at JS, so Im hoping someone who is will see why 1 and 3 will not respond.

#

Sorry if the use of "div" and "dev" is confusing. Each div represents a selection of a "device" that hasnt been filled with content yet.

#

It makes no sense that two of them work and two of them dont work

#

I dont even understand where to begin with looking for why that would happen

#

I'll make a fiddle, I forgot that is standard procedure with asking for frontend help[

blissful dome
#

Hello
How do I make a region selector tool with google maps api?
like a freehand region selector, rectangle region selector, circle region selector
etc

native tide
#

I figured it out, I'm missing two braces. Im too used to python.

fossil thicket
#

@native tide sure, i wanted to crop an image included in a notebook tho rather than a web page

#

Thinking about it, i might be better off using an ipython widgit thing

native tide
#

hi bois

#

i am learning html and css

#

is javascript hard?

#

I think that it is hard as a first language, yeah. That's my opinion though.

#

ohhhh

#

hmmmm

crude spruce
#

Can anyone give me a complete list of skills (languages,databases,libraries etc..) of a full stack web developer?

native spindle
#

Has anyone used the fastapi framework? Should I use it over Flask for a backend server?

quasi ridge
#

I haven't used it, and am not sure I've even heard of it

half sky
#

Hello, I'm using a pipenv to host a server, but im having trouble getting a default module in python 3.7 to work. I'm getting a modulenotfound error for Json. Anyone know why this may be?

quasi ridge
#

paste the relevant code, as well as the command line that you use to invoke it

half sky
#

ok

#
#!/usr/bin/env python3
"""
Very simple HTTP server in python for logging requests
Usage::
    ./server.py [<port>]
"""
from http.server import BaseHTTPRequestHandler, HTTPServer
import logging
import functions
import json
#

invoking command: pipenv shell python server.py 25565

quasi ridge
#

and what's the error ?

#

(you realize that you don't need pipenv for code that has no third-party requirements, right?)

half sky
#

I use pipenv to keep some environmental variables secret

#

like api keys

quasi ridge
#

that's ... unusual

#

I've never heard of that

half sky
#

idk, learned it in school

quasi ridge
#

are you sure you didn't mean to type run instead of shell?

half sky
#

either work

quasi ridge
#

anyway, paste the traceback

half sky
#

sure

#

File "server.py", line 9, in <module>
import functions
File "C:\Users\lesko\desktop\coolstuff\functions.py", line 3, in <module>
import JSON
ModuleNotFoundError: No module named 'JSON'

quasi ridge
#

try using lower-case

#

also you clearly did NOT paste that particular bit of code, but rather, some other bit

#

the code you did paste has json properly spelled, and the import is on line 10, not line 3

half sky
#

mm

#

could be because i tried importing twice?

#

or does redundancy not matter

quasi ridge
#

no, it's because you wrote JSON instead of json. Case matters.

iron granite
#

my question^

quasi ridge
#

oh sorry

#

this isn't one of the reserved channels ๐Ÿ™‚

iron granite
#

yes okay

quasi ridge
#

oy. You're trying to scrape a web calendar. Good luck ๐Ÿ˜

#

if you're really lucky, that calendar will provide an API. Chances are it doesn't though.

#

Or if it does, you'll need to use OAuth to authenticate, which will take you approximately the rest of your natural life to figure out ๐Ÿ˜

#

Guess I'm in a pessimistic mood today

half sky
#

oh thanks for the help btw, guess it was a really dumb help question

#

we all have those patrick star moment though ๐Ÿ™‚

iron granite
#

can anybody see what i am doing wrong?

hollow horizon
#

hi all, I want to convert this : [<h1 class="mvp-post-title left entry-title" itemprop="headline">La semifinal del spring split de LEC tuvo mรกs espectadores que la final del aรฑo
pasado</h1>] into this: La semifinal del spring split de LEC tuvo mรกs espectadores que la final del aรฑo pasado`. Has anybody knows how to remove the HTML code? Thanks all!

iron granite
hollow horizon
#

thanks a lot! @iron granite

iron granite
#

๐Ÿ‘

half sky
#
os.mkdir("players/" + name)
os.chmod("players/" + name,0o777)
#

when i made directory i made sure to modify it so everyone can read and write, but when i try to make a file within the directory, i get permission denied

#

anyone know why this might be the case?

#

nevermind, for some reason i forgot to give the file a name :/

feral minnow
#

Guys why when I want to redirect the user to another route which is the download process page it just go to it(it execute the code)with out rendering the template

feral minnow
#

Anyone know how to change the size of a Selectfield from flash_wtf?

native tide
#

hello, i've been following this tutorial (https://mesa.readthedocs.io/en/master/tutorials/adv_tutorial.html) using pycharm and my problem is when i try to run the server, it says in console that the server starts (Interface starting at http://127.0.0.1:8521/) but then I also get some errors in this order

server.launch() server.listen(port, address) self.add_sockets(sockets) self._handlers[sock.fileno()] = add_accept_handler( io_loop.add_handler(sock, accept_handler, IOLoop.READ) self.asyncio_loop.add_reader(fd, self._handle_events, fd, IOLoop.READ) ...\AppData\Local\Programs\Python\Python38\lib\asyncio\events.py", line 501, in add_reader raise NotImplementedError

and when i visit http://127.0.0.1:8521/ chrome says it cant access this address.

i also have a hunch it may have something to do with me using the hotspot wifi from my phone (cant use normal internet because of corona quarantine), i googled it but got lost, i would appreciate a point in the right direction if anyone recognizes this problem.

dense slate
#

In Django, Is there a generic reason why I can access a page normally if I'm logged in, but I get a 404 "No CustomUser matches the given query" as an anonymous user?

#

login_required is not applied

#

If I print the request and variable passed to the view, they are there

fallow marsh
#

Anyone here ever use Selenium?

wild thunder
#

guys, a doubt on flask css

#

i'm using bootstrap and i want a file of "my css", then i created main.css
<link rel=stylesheet type=text/css href="{{ url_for('static', filename='main.css') }}" />
i've defined only a test class for checking.

.test {
    font-family: monospace;
}

but this is actually changing all my bootstrap fonts to monospace

#

actually, this is solved

native tide
#

make sure you have kep the proper scpacing

#

oh k

#

sorry

wild thunder
#

my css file was in the wrong directory

#

was like:

css
(empty)
main.css

#

they were in the same folder

native tide
#

ohhh

#

could you send a pic of what the website looks like

dusky lake
#

I'm looking to log into one of the sites I use programatically so I can pull/monitor my information there. I'm posting here, because I'm not sure how to read the site's code. Anyone able to spare a moment for some quick question?

keen widget
#

use requests and bs4

#

what site this may be?

dusky lake
#

networksolutions.

#

www.networksolutions.com, I'm wanting to pull my domain information, they don't have an api or the ability to export your information from it.

keen widget
#

probably you can craft a request to the particular page then scrape it

quasi ridge
#

maybe you can get that information from the command line via ssh; in which case you'd use paramiko, and/or pexpect

dusky lake
#

Do a select of the form, and when I have it print a summary, a good bit of hidden types in there.

slender jungle
#

but i am quite new to web scrapping

#

any advice

dusky lake
#

You know there's a download csv link on there right?

harsh flare
#

Anyone know how I could create a different div id = '' and Chessboard('', cfg); in a jinja for loop? I've tried creating a str variable in 'list' but it doesn't seem to want to behave properly.

{% for x in list %}
<div id='myboard' style="width: 400px"></div>

<script>
   var board = ChessBoard('myboard', cfg);
</script>

{% endfor %}

whole jungle
#

youre not using the x tho

harsh flare
#

Sorry, if I were though

#

It doesn't seem to work

#

I'm creating a list item in list as date = game.headers['EndDate'] time = game.headers['EndTime'] dt = str(date + time) and calling that in list as {{x[4]}} in the above as.

{% for x in list %}
<div id={{x[4]}} style="width: 400px"></div>

<script>
   var board = ChessBoard({{x[4]}}, cfg);
</script>
{% endfor %}
alpine jackal
#

I'm working on a web app project , wherein I used Python to web-scrape a page and stored the text in a variable.
I want to be able to select just a specific line and store the value in a variable.

Language : Tamil 
Song     : Yamunai Aatrile
Movie    : DhaLapathi
Defaults : s r2 g3 m2 p d2 n3 (See Legend for more details) 
Scale/Key: C (Orig:F, Transpose:+5)

Yamunai aatrile eera kaatrile kaNNanOduthaan aaaada
S S S   S  S S  S R  R   R R  G~RG R~SSS     SnRSn
C               G             C              C   Em

Paarvai pooththida paadhai paathida paavai raadhayO vaaada
S   S   S    S  S  S  R    R  R  R  G~RG   R~SS  S  SnRSS
C                  G                C

Iravum pOnadhu pagalum pOnadhu mannannn illaye koooda
SS S   S S S   S S R   R R R   G~RG~R~G R~SSS  SnRSn
C              G               C               C   Em

ILaya kanniyin imaithidaadha kaN inngummm angume thaeda
SS S  S  S S   SS  R  R  R   R   G~RG~R~G R~SSS  SnRSS
C              G                 C

Aaayarpaadiyil kaNNanillayOOOO  aasai vaippadhe annbuthollayOOOO
P~GM  P  P P   PMPMDP  M GMPMG  P~GM  P   P P   PMPMDP   M GMDMG
C              Em               G               Em

Paaavamm Raaadhaa
PMGDPMGP MGRPGRSn
Am  Em   D   G

Yamunai aatrile eeera kaatrile kaNNanOduthaan aaaada
S S S   S  S S  S~RR  R   R R  G~RG R~SSS     SnRSn
C               G              C              C   Em

Paarvai pooththida paaadhai paathida paavai raadhayOOOO vaada
S   S   S    S  S  R n p    pnRR  R  P  P~M G~RG  RGRPG R~SS
C                  G                 C
#

That is the text I have...

#

and I need just the second line "Song : Yamunai Aatrile"

#

If I try text[1] , I get the second character and not the second line. So how do i select the second line?

gilded monolith
#

you can read by lines

#

it depends on the way you open the file of course

#

usually a new line is also marked as \n

#

so you can check the text between the first and second

leaden lantern
#

How can i extract title from this

<a class="entity-nav-next" href="/pokedex/wigglytuff" rel="next">#040 Wigglytuff</a>
feral minnow
#

@leaden lantern try this Elem = soup.select("a.entity-nav-next")[0].text.strip()

green echo
#

is this the channel to ask about crawlers?

#

it is really about the crawler but on how to convert the py to exe,

#

Scrapy creates a project template which isn't really portable

leaden lantern
#

@feral minnow Worked Thanks

feral minnow
#

No problem

supple loom
#

how to seed database in fastapi

cold anchor
#

manually, like almost everything in fastapi having to do with your ORM

supple loom
#

what if i have to enter a long list

cold anchor
#

can you be more specific?

#

what's the actual scenario you have?

supple loom
#

i have to enter a list of cities and then retrieve it later

cold anchor
#

do you already have that list of cities in code somewhere?

supple loom
#

it's in a json file

cold anchor
#

do you already have your ORM hooked up to fastapi?

supple loom
#

not yet...i will consult with you in some time

cold anchor
#

it seems like your best bet might be to hook that up and then make a "GET /seed-db" endpoint that seeds the database if it's not seeded already

supple loom
#

yeah that seems to do it

charred scroll
#

Is it possible to have a dynamic search field in Flask? So as you type, fields popup base on the text

cold anchor
#

that's usually done by the browser or custom logic, what specifically are you trying to do?

charred scroll
#

So I have a bunch of users in a table called customers

And I have a license form which associates a user with a license. I want it so that the user types in the first (or first + second name) and then it shows those users

#

like this

cold anchor
#

how many users do you have?

charred scroll
#

there wont be an insane amount

maybe 1000 max

cold anchor
#

if you have a small enough amount that you feel comfortable throwing that all in the frontend you could use a select library

#

the other option is to have a "typeahead" endpoint on the backend that you can render text search results from

charred scroll
#

Is 1000 considered a small amount? ๐Ÿ˜„ Will that affect the loading speed significantly?

cold anchor
#

1000 is pretty small but it also depends on how it's rendered, rendering 1000 elements might be expensive depending on the element

charred scroll
#

Alright thanks ๐Ÿ‘

I'll take a look into a typeahead endpoint - maybe someone has written a library based on it already

cold anchor
#

are you using react? I can send you some sample code

charred scroll
#

I'm using bootstrap

cold anchor
#

probably wouldn't be too helpful then, good luck!

charred scroll
#

Thanks for the help!

#

This seems to have a "typeahead" endpoint

cold anchor
#

that'll work, though you'll want to adjust it to work for your filtering in the database

zealous talon
#

Hi there I am new to this py dev. I have managed to dev Quasar-Vue js (localhost) and Python 3.8 + Flask + .. (localhost) Windows. I used CORS to accept request from Quasar(8080 ) to API call on Py (5000) which fetches data from Postgres. Earlier with my little knowledge in xampp, I used put all UI files with PHP files in htdocs. Now my question is can I put these js (Quasar build file) inside Py directory that I am working so that I can make one call to Quasari UI to initiate Py API call. Once I have a hold I have to put to gcloud that is my next step. I use vscode pipenv for my projects fyi. Kindly advise.

zealous talon
#

@zealous talon I found an answer. app = Flask(__name__, static_url_path='', static_folder='/myquasarfolder',) and return app.send_static_file("index.html") hope it helps for a py newbie like me..pystrong

dark hare
#

can someone recommend learning resources for django-allauth, OAuth2 and general authorisation/sessions please
@dark hare

onyx crane
#

heyo im using materialized css in combination with django to style my website, but now i gotta include some js code somewhere.
How do you normally deal with js files in django ? Do i just slap the link onto the html in question ?

limber flare
#

Hey everyone, I have a simple question but it's driving me up a wall

#

I'm setting a view as the root directory of the site, but doing so disables the admin panel

#

i'm using django

#

url(r'^', include('jobs.urls')),

#

what am i doing wrong?

onyx crane
#
urlpatterns = [
    path("", include('main.urls')),
    path('admin/', admin.site.urls),
]
#

with this, you can link your url.pyfrom your app (given your app nameis main)

#

ah your app name is jobs.
In that case just add the admin path and it should be working

limber flare
#

urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('jobs.urls')), ]

#

Your code brings up this error: NameError: name 'path' is not define

#

I'm using Python 3.8.2 and Django 3.0.5

onyx crane
#
from django.contrib import admin
from django.urls import path, include```
#

mb

limber flare
#

yeah, no luck

#

`from django.contrib import admin
from django.urls import path, include

urlpatterns = [
path("", include('jobs.urls')),
path('admin/', admin.site.urls),
]
`

#

Fixed it!

#

ty

onyx crane
#

np :)

atomic zodiac
#

Is anyone able to help me with a program including python, sqlite and python

quasi ridge
#

it's entirely possible!

#

but we'll never know until you ask

#

"python, sqlite and python" sounds uncannily like "spam, eggs, sausage, and spam"

atomic zodiac
#

good point i'll post my specific error

limber flare
#

Hey, I'm building a web app in Django and I'm setting up the register form but whenever you register, the info is not being added to the db and I cannot figure out why.

#

nvm

onyx crane
#

Django:
I added a dropdown to my navbar, which requires some js/jquery. I am loading all of the css & js in the navbar. All of my pages extend the navbar which worked fine so far.
Now on my root page, the dropdown works perfectly fine, on my other pages it doesnt. Anyone has an idea on why the js/jquery doesnt work on all pages ?

#

Second Django Question:
How can i build dynamic/ user specific links ? Depending on the link clicked i want a specific template rendered with different context.
(Feel free to @me)

cobalt oyster
#

@onyx crane use template inheritance for first case. But if you don't want to, might wanna check the order at which you have placed those links in your other pages

#

@onyx crane and your second question. You can uses JINJA2 in HTML to make a specific case like.

onyx crane
#

why would i need template inheritance ?

cobalt oyster
#
{% if condition is True %}
  <a href='somepage.html'>somelink</a>
{% else %}
  <a href='otherpage.html'>othet link</a>
{% end if %}```
onyx crane
#
    {% block content %}```
This is above the page where it works, and above the pages where it doesnt
cobalt oyster
#

does it work in main/navbar.html?

#

you can check by opening the file in browser

onyx crane
#

if i copy the same template and rename the file, it doesnt work anymore

cobalt oyster
#

so all the pages have {% extends "main/navbar.html" %}

#

?

#

and only some work?

onyx crane
#

only one works

cobalt oyster
#

can you post the code in here?

onyx crane
#

Charactercreation.html

<body>

    {% extends 'main/navbar.html' %}
    {% block content %}

        <div class="container"></div>

            <h5 style="color: white;">Rasse:</h5>
            <div class="input-field col s12">
                <select class="browser-default">
                    <option value="" disabled selected>Wรคhle deine Rasse</option>
                    {% for race in races %} 
                        <option value="3">{{race}}</option>
                    {% endfor %}
                </select>
            </div>

            <h5 style="color: white;">Klasse</h5>
            <div class="input-field col s12">
                <select class="browser-default">
                    <option value="" disabled selected>Wรคhle deine Klasse</option>
                    {% for race in races %} 
                        <option value="3">{{race}}</option>
                    {% endfor %}
                </select>
            </div>

            <h5 style="color: white;">Talente:</h5>
            <div class="chip">
                Erste Hilfe
                <i class="close material-icons"> x</i>
            </div>
            <div class="chip">
                Weird Talent
                <i class="close material-icons"> x</i>
            </div>
            <div class="chip">
                Second Weird Talent
                <i class="close material-icons"> x</i>
            </div>



        </div>
    
    {% endblock %}



</body>
#

home.html

<body>

    {% extends "main/navbar.html" %}
    {% block content %}
    <div class="row">
        {% for race in races %} 
            <div class="col s12 m6 l4">
                <div class="card blue-grey darken-1">
                    <div class="card-content white-text">
                        <span style="font-weight: bold;" class="card-title">{{race.race_name}}</span>
                        <p>{{race.race_description}}</p>
                    </div>
                    <div class="card-action">
                        <a href="#">This is a link</a>
                        <a href="#">This is a link</a>
                    </div>
                </div>
            </div>
        {% endfor %}
    </div>
    {% endblock %}


</body>
cobalt oyster
#

can you post the main/navbar.html?

onyx crane
#

navbar.html (the one which is being extended)

<head>
    {% load static %}
    <link href="{% static 'tiny/css/prism' %}" rel="stylesheet">
    <!-- Compiled and minified CSS -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
    <!-- JQuery-minified -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <!-- Compiled and minified JavaScript for Materialize CSS -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>

    
    <script>
        $(document).ready(function() {
            $(".dropdown-trigger").dropdown();
        });
    </script>

    
</head>


<body style="background-color: #222831;">

    <ul id="charactercollectiondropdown" class="dropdown-content">
        {% for char in characters %}
            <li><a href="#!">{{char.pc_name}}</a></li>
        {% endfor %}
    </ul>


    <nav class="nav-wrapper blue-grey darken-1">
        <div style = "margin-left: 20px; margin-right: 10px;" class="nav-wrapper ">
            <a href="/" class="brand-logo">PUN & PAPER</a>
            <ul id="nav-mobile" class="right hide-on-med-and-down">
                <li><a href="characterdisplay">Character Display</a></li>
                <li><a class="dropdown-trigger" href="characterdisplay" data-target="charactercollectiondropdown">Charaktere</a></li>
                <li><a href="charactercreation">Character Creation</a></li>
                <li><a href="badges">Active Games</a></li>
                <li><a href="collapsible">Regelwerk</a></li>
                <li><a href="register">Log In</a></li>
            </ul>
        </div>
    </nav>

    
         
    <div class="container">
        {% block content %}
        {% endblock %}
    </div>

</body>
cobalt oyster
#

ok

onyx crane
#

and the springing point is the loaded jquery (i think)

#

normally the page content should really not matter. I can have a blank page with just a heading and the dropdown does not work

cobalt oyster
#

try to remove the <body> </body> tags on the html

#

and check

onyx crane
#

alrighty. (though theyre also in home.html)

cobalt oyster
#

yeah

onyx crane
#

where should i remove them ? navbar or the others ?

cobalt oyster
#

other just try one of them

onyx crane
#

same result :/

cobalt oyster
#

ok

onyx crane
#

got it, kind of

#
urlpatterns = [
    path("", views.homepage, name="homepage"),
    path("register", views.register, name="register"),
    path("charactercreation", views.charactercreation, name="charactercreation"),
    path("characterdisplay", views.characterdisplay, name="characterdisplay"),
]

if i swap views.homepage with another view it works. / or just change the html template refered to in homepage

#
def homepage(request):
    return render(request = request,
                template_name='main/characterdisplay.html',
                context = { "characters": PlayerCharacter.objects.all, "races": Race.objects.all} )

if i change this to anything else, the dropdown works.

#

what kind of an odd behaviour

cobalt oyster
#

the charecter dropdown?

onyx crane
#

yus

cobalt oyster
#

do your other views have the characters passed in as context?

#

the views where it dosen't work?

onyx crane
#

no. but i just added them and it does not change anything. I also dont know why it would

#
def navbar(request):
    return render(request = request,
                template_name='main/navbar.html',
                context = { "characters": PlayerCharacter.objects.all})

Since it is already given here ... it shouldnt matter

#

(thanks for the effort already ... feels like stepping in the dark)

cobalt oyster
#

ok

#

your welcome

onyx crane
#

pasting the whole header from navbar.html into the other templates does not solve the problem either. Hm

#

Even when i dont extend the navbar into the other templates, but instead have the complete html in one file (including the script imports in the header) it does not work ...

It must have something to do with the home.html being set up as the header

#

Heading to sleep. If someone knows ... pls @me

frank crater
#

boto.exception.NoAuthHandlerFound: No handler was ready to authenticate. 1 handlers were checked. ['HmacAuthV1Handler'] Check your credentials

#

How do I connect to S3?

#

I have a discord.py bot which has a token but I don't want it to be public, that's why I have the token file inside of the gitignore file, but I want heroku to fetch it for me if the bot is not running locally

#

I'll give a more detailed explanation

#

This is a code in my main bot file which says "Try to get Token.txt" because if it gets Token.txt (Which is in gitignore, meaning it will not go to heroku) then it assumes it is running in my local machine. But if it raises an exception, which I assume is going to be FileNotFound error, then it goes looking for the variable which stores the token of my bot

#

This is the code I mentioned above: ```py
from boto.s3.connection import S3Connection

try:
with open("Token.txt", 'r') as TokenFile:
client.run(str(TokenFile.readline()))
except:
client.run(S3Connection(os.environ['BotToken']))

cold anchor
#

a couple things:

  1. I'd recommend checking how to get the token based on the environment, and not the other way around, it'll make doing differences based on environment easy if you only check it one way
  2. you can configure your heroku app to have the AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables, which will give it access based on the permissions you provide to that role
  3. I'd recommend making your token an environment variable unless you wanted to access it locally or had another good reason to keep it in a bucket instead of local to the production server
  4. lastly, here's a snippet that downloads a file from s3 and returns a file pointer:
from io import BytesIO
import boto3

s3 = boto3.client('s3')
fp = BytesIO()
s3.download_fileobj('your bucket name',
                    'your file name in S3', fp)
fp.seek(0)
onyx crane
#

mighty rdbaker :D do you have an idea what my issue might be

cold anchor
#

you're using a very old library, upgrade to boto3 and you'll have a lot more support from newer documentation

#

oh sorry I assumed you were somebody else, let me read back

#

check your network panel and compare the js/css files being loaded on the page it's working and the page it's not working and see if there's a difference

valid cypress
#

I need help with Django AllAuth: How to use django-allauth for login to admin?

cold anchor
#

I've never used it and haven't used django in years but I can try to help

onyx crane
#

Css&js are both properly loaded. Good idea though

cold anchor
#

have you tried running $(document).ready(function() { $(".dropdown-trigger").dropdown(); }); manually in the JS console?

#

after the page fully loads

onyx crane
#

same result on working & not working pages

cold anchor
#

see if removing the extra <body> tag you have in your templates helps

#

you already have <body> in your nav html page

onyx crane
#

we tried that yesterday already and it didnt work :/

#

Working page and not working pages both got the body tags

cold anchor
#

it'd still be a good idea to remove them, some libraries attach to <body> and can have unexpected behavior if there's 2 of them

onyx crane
#

will do :)

#

the only difference i can see is that the page where it is loading is the root localhost:8000 while the others are localhost:page

cold anchor
#

(assuming you mean localhost:8000/page) and both are over http? (not https)

onyx crane
#

yeah.... ๐Ÿ˜…

#

havent gotten to the https part yet :D or deploying it

cold anchor
#

ah well that comes later anyway

#

would you mind sharing a screenshot of the network tab on the / page and any other page?

onyx crane
#

not working

#

working

cold anchor
#

are there elements in that list on the other page? 5.8kb vs 1.9kb is a big difference

onyx crane
#

element in what list ?

cold anchor
#

in the <ul> of characters

onyx crane
#

not sure if i can follow.

The difference in size originates from the fact that characterdisplay.html displays a users character. Since i just logged in as a new user there are no characters to display => nothing needs to be loaded

cold anchor
#

check the actual elements of the page when you do "inspect" to confirm that there are items in the list when you expect there to be and no items when you don't expect it

onyx crane
#

ooooooooooooooooooooooooooooooooooooooh

#

๐Ÿง

cold anchor
#

๐Ÿ‘

onyx crane
#

ok i fixed it

#

but i got a question

#
 <ul id="charactercollectiondropdown" class="dropdown-content">
        {% for char in characters %}
            <li><a href="#!">{{char.pc_name}}</a></li>
        {% endfor %}
    </ul>


    <nav class="nav-wrapper blue-grey darken-1">
        <div style = "margin-left: 20px; margin-right: 10px;" class="nav-wrapper ">
            <a href="/" class="brand-logo">PUN & PAPER</a>
            <ul id="nav-mobile" class="right hide-on-med-and-down">
                <li><a href="characterdisplay">Character Display</a></li>
                <li><a class="dropdown-trigger" href="characterdisplay" data-target="charactercollectiondropdown">Charaktere</a></li>
                <li><a href="charactercreation">Character Creation</a></li>
                <li><a href="#!">Active Games</a></li>
                <li><a href="#!">Regelwerk</a></li>
                <li><a href="register">Log In</a></li>
            </ul>
        </div>
    </nav>

This is in navbar.html

#
def navbar(request):
    return render(request = request,
                template_name='main/navbar.html',
                context = { "characters": PlayerCharacter.objects.all})

def characterdisplay(request):
    return render(request = request,
                template_name='main/characterdisplay.html',
                context = { "user": User.objects.all})

#

here i passed the characters as context to the navbar ... so i assumed that whatever page i load, no matter if i give it characters as context or not, navbar (which is always a part of the page) does ... so why do i need to pass characters to the "bottom part of the page"

cold anchor
#

ah, unfortunately, that's not quite how it works

#

the "full" template is constructed based on the "template_name" and the inheritance of that template

#

that "full" template page then gets passed the context you give it

onyx crane
#

oh so it doesnt matter what context i give the parent template

cold anchor
#

correct, those are two different "renders" so they have different context

#

inheritance stops at stitching the html page together

onyx crane
#

Hm hm hm.... If i want context in the header/navbar , everything the page needs must be passed to every template :/?

cold anchor
onyx crane
#

thanks so much ๐Ÿ˜ โค๏ธ i feel like im always learning a lot when youre poking around the isssues :D!

cold anchor
#

lol glad to hear that, happy coding!

native tide
#

Hey I should read that too.

#

Im kind deep into TypeScript atm.

#

This is a cool feature of TypeScript

let userInput: unknown;
let userName: string;

userInput = 4;
userInput = "shanaynay";

userName = userInput; // 'unknown' not assignable to 'string'

if (typeof userInput === 'string') {
    userName = userInput;
} // after type check, works without error
#

unknown is basically a type that will allow you to transform it if you include a type check statement for that type.

simple basin
#

Hello. I am trying to use flask to create an input form.

Currently, I am using the IntegerField from Flask-WTF as an input field in the form. However, it generates this HTML source:

<input id="quantity" type="text">

How can I generate this kind of HTML instead?

<input type="number" id="quantity" name="quantity" min="1" max="5">

Is there some other type of input field or do I have to move away from Flask-WTF and use some other method.

Thanks.

cold anchor
#

take a look here

#

{{ myform.quantity name="quantity" class_="my-class" min="1" max="5" type="number" }} should work

simple basin
#

thank you!

toxic wing
#

I have a domain with a cloud server website. I want to put my personal laptop so itโ€™s reachable on a subdomain wherever I take it. What is the search term or source for more information? Thanks.

leaden lantern
#
<a tone="gray" target="_blank" href="/images/search?text=%D1%80%D0%B0%D1%82%D1%82%D0%B0%D1%82%D0%B0" class="Button2 Button2_width_auto Button2_view_default Button2_size_l Button2_type_link Button2_tone_gray Tags-Item"><span class="Button2-Text">ั€ะฐั‚ั‚ะฐั‚ะฐ</span></a>

How can i scrap ั€ะฐั‚ั‚ะฐั‚ะฐ this from above code?

#

Mention me if someone knows.

late gale
#
<li class="nav-item"><a {% if request.path == '/about' %} class="nav-item active" {% endif %} href="{% url 'About' %}"
                                >About</a></li>

Can anyone tell me what's the wrong here

simple basin
#

How can I implement a PDF viewer for a web page served using flask? I am generating the PDF and have seen example usage of base64 to display pdfs. however, none of that seems to be working, even in pure HTML/CSS/JS

supple loom
#

while defining schemas in fastapi do we need to define something for relationship too?

#
class City(db.Model):
    __tablename__ = 'city'

    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(128))
    state_id = db.Column(db.ForeignKey('state.id'), index=True)
    description = db.Column(db.String(2048))

    def __repr__(self):
        return self.title

    state = db.relationship('State')
#

this is my model for class City

#
class CityBase(BaseModel):
    title: str
    description: str = None

#

is this schema correct?

#

@cold anchor take a look please

cold anchor
#

lol no need to ping me, if I'm online and can help, I will

#

I'm not super familiar with fastapi but if the BaseModel is anything like Marshmallow, it's just for serializing data, so you probably don't want to allow relationships to be posted, but handled explicitly by the code

#

e.g. POST /api/states/CA/cities { ... } you probably don't want to let the client specify the state in the payload, and instead control the relationship in the view

#

though you'd probably want to include the relationship in the schema for deserializing

#

er, I mixed up serializing/deserializing - other way around in my earlier messages

native tide
#

Anyone here need UI design?

charred scroll
#

https://stackoverflow.com/questions/39614604/autocomplete-search-box-and-pass-value-to-flask

So I'm following this but I'm encountering something extremely weird. It seems that the searching only works if the endpoint returns a literal?

<script>
        $('#autocomplete').autocomplete({
            serviceUrl: '/search/customers',
            dataType: 'json',
            onSearchComplete: function (query, suggestions) {
                console.log(query);
            }
        });
    </script>
@app.route('/search/<string:endpoint>', methods=['GET'])
def process(endpoint):
    query = request.args.get('query')
    print("query: ", query)
    if endpoint == 'customers':
        customers = Customer.query.filter(Customer.first.like(query) | Customer.last.like(query) 
                                    | (Customer.first + ' ' + Customer.last).like(query)).all()
        
        # suggestions = [{'value': customer.first, 'data': customer.customer_id} for customer in customers]        
        # return jsonify({"suggestions": suggestions}) # Doesn't work
    
    suggestions = [{'value': 'song1','data': '123'}, {'value': 'song2','data': '234'}] # Only literals work?
    return jsonify({"suggestions":suggestions})
#

I've noticed that when I have the commented code, it only sends the first character to th endpoint too.

eg:
a --> ?query=a
aa --> request not sent
b --> ?query=b

cold anchor
#

I'd suggest using the official autocomplete jQuery library instead of the "devbridge" version https://jqueryui.com/autocomplete/#remote

#

ah, actually that version looks very old, I don't know if I'd suggest that, either

#

honestly I've only ever done these by hand, but I'd guess it has to do with the autocomplete library you're using

toxic wing
#

I had someone kick back a near completed project and say no jquery, use vuejs, redo it all

#

the amount of dollar signs and smooth braces that are missing from my life now.....

snow sinew
#

Hello all, I am trying to read some data from an API using the Requests api. Somehow I dont seem to get the entire data in JSON, as I get from the curl command line.
Any ideas what I am doing wrong.

#

headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36',
'Accept': 'application/json; charset=utf-8'
};

get_body=requests.get(get_url,headers = headers)
json_items = get_body.json()
cold anchor
#

use get_body.request.headers to see all the headers that requests sent over

#

and compare that to the output of curl -v ...

snow sinew
#

@cold anchor Thanks will take a look

#

@cold anchor from curl I got this :

#
  • ALPN, server accepted to use http/1.1

GET /api/v3/references/thesaurus/json/test?key=abcd HTTP/1.1
Host: dictionaryapi.com
User-Agent: curl/7.47.0
Accept: /

< HTTP/1.1 200 OK
< Date: Tue, 21 Apr 2020 19:46:30 GMT
< Server: Apache
< Access-Control-Allow-Origin: *
< Transfer-Encoding: chunked
< Content-Type: application/json; charset=utf-8
<

#

get_body.request.headers is this : {'User-Agent': 'curl/7.47.0', 'Accept-Encoding': 'gzip, deflate', 'Accept': 'application/json; charset=utf-8', 'Connection': 'keep-alive'}

cold anchor
#

and curl returned correct data but requests did not?

snow sinew
#

Nope

#

Sorry I meant to say curl worked fine but requests did not.

cold anchor
#

and you're passing your API key in the same way as well?

snow sinew
#

yes

cold anchor
#

it does look like the headers are slightly different between the two, can you make sure they're the exact same and try again?

snow sinew
#

ok

cold anchor
#

I would be surprised if that was it but I've seen stranger things happen before

snow sinew
#

I am specially suspecting the 'Accept-Encoding': 'gzip, deflate' from Requests

molten temple
#

how i can change my django server default encoding? because now i am using lithuanian letters in my index.html template, and utf-8 cant recognize it

viral osprey
#

any one have experience with Zeep and SOAP API?

molten temple
flint shoal
#

any with django knowledge?

honest flame
#

Hey any of you use vue.js

native tide
#

I was looking at the JS frameworks today and decided I will probably not learn any of them. They drastically change the development process into something I am going to hate. I am learning scss and typescript. So in some ways I am leveling up my frontend a lot.

#

Scss is weird.

native tide
#

Why when I use Flask, all css files don't work?

cobalt yew
#

any ideas how to fix this issue

#
    margin-top: 0.5em;
}

[data-role="dynamic-fields"] > .form-inline [data-role="add"] {
    display: none;
}

[data-role="dynamic-fields"] > .form-inline:last-child [data-role="add"] {
    display: inline-block;
}

[data-role="dynamic-fields"] > .form-inline:last-child [data-role="remove"] {
    display: none;
}```
#
$(function() {
    // Remove button click
    $(document).on(
        'click',
        '[data-role="dynamic-fields"] > .form-inline [data-role="remove"]',
        function(e) {
            e.preventDefault();
            $(this).closest('.form-inline').remove();
        }
    );
    // Add button click
    $(document).on(
        'click',
        '[data-role="dynamic-fields"] > .form-inline [data-role="add"]',
        function(e) {
            e.preventDefault();
            var container = $(this).closest('form');
            var new_field_group = container.children().clone();
            new_field_group.find('input').each(function(){
                $(this).val('');
            });
            container.append(new_field_group);
        }
    );
});
    </script>```
modern comet
#

How come i get this error?

#

It's super simple and it's driving me mad haha

#

It seems as if no matter where i put my_list = [] it never assigns in the context

quasi ridge
#

you need a global statement inside your function

supple loom
#

i have defined models, schemas and CRUD in my fastApi...do i need to run the migrations first before running the app?....coz right now it gives the error moduleNotFoundError : no module named 'mysql'

quasi ridge
#

I think you typically do need to run migrations first, to set up the db; but if it's saying "no module named 'mysql'" that's a different problem

#

you have to do something like python3 -m pip install --user something-like-mysql although unfortunately I can't tell you exactly what to use for the something-like-mysql

supple loom
#

it says --user site packages are not visible in this virutalenv

#

py -m pip install --user mysql

#

when i am running pip install mysql it gives errored out with exit status 1...microsoft visual c++14.0 is required install it with build tools for visual studio

zealous siren
#

you need C++ 14.0 installed

supple loom
#

it's different from microsoft visual c++ 2015-19 redistributable x64 14.25.28508?

zealous siren
#

maybe

#

run the MSI and find out

supple loom
#

MSI?

zealous siren
#

there are C++ for each version

#

the installer

supple loom
#

i don't have it

#

or do i?