#web-development

2 messages Β· Page 88 of 1

vestal hound
#

except my limitation on the number of related objects is dynamic

#

I asked in #databases and the conclusion was that it would need an (SQL) function

versed python
#

okay, thanks for your help

vestal hound
#

yw

versed python
#

I'll wait around for a few more opinions though

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

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

How can I put a constraint in place so that only 3 PostImage objects can be related to a single Postobject?
@versed python can someone else give their preferred way to accomplish this?

scarlet perch
#

I cannot connect to my localhost ( 127.0.0.1 ), it says localhost refused to connect, ERR_CONNECTION_REFUSED

frozen spear
#

yes run the server

#

before

#

in ur console make sure ur in the dir of where manage.py file is

#

and do

scarlet perch
#

python manage.py runserver
@frozen spear didnt really get it, super new to web stuff

#
aiohttp.client_exceptions.ClientConnectorError: Cannot connect to host 127.0.0.1:2333 ssl:default [The remote computer refused the network connection]
#

here is the error πŸ‘†

frozen spear
#

ur super super new u really should visit docs

#

or tuts

vestal hound
#

does anyone send emails asynchronously with Django

#

what do you use

frozen spear
#

a smtp server to send emails with django

versed python
#

@frozen spear does Entry object with pk=15 actually exist in your database?

frozen spear
#

yeahh

vestal hound
#

a smtp server to send emails with django
@frozen spear what?

frozen spear
#

@versed python wait

#

lemme check

#

prob no

versed python
#

lol

frozen spear
#

@vestal hound sending actual emails with django?

vestal hound
#

the point isn't to send emails

#

it's to send them asynchronously

#

I realised Celery doesn't actually have support for async tasks

#

and I don't want to block

frozen spear
#

oh

#

hmmm

#

i never sent an actual email but just in terminal

vestal hound
#

yeah...

#

that's not really the problem I'm facing though

frozen spear
#

sorry

vestal hound
#

np

#

not blaming you

#

it's not a common problem apparently

#

😩

wispy quiver
#

hello

#

i'm trying to automate a series of tasks

#

that requires me to go to a website

#

search a couple of things

#

and download the results

#

i'm wondering if there is any automation tools out there

vestal hound
#

selenium sounds like what you want

wispy quiver
#

i'm looking at selenium but

#

the find elements is kind of lacking

#

yeah i'm just wondering if there's anything better

vestal hound
#

the find elements is kind of lacking
@wispy quiver what do you mean

wispy quiver
#

i'm trying to type a url into this field

#

but i can't find the right element finder

#

but that might be more due to my lack of experience with selenium

vestal hound
#

use xpath

wispy quiver
#

than any problem with selenium itslef

vestal hound
#

to find it

wispy quiver
#

ah ok

#

i'll look into xpath

#

lol

#

i usually avoid things that looks too complicated
but that prob just makes me a worse programmer

frozen spear
#

is there a way to define the model and use it here in specific template this my first time using detail views,i have my model already set up and imported and everything now i want to iterate but i need to define model to use it in template

#

views ^

versed python
#

@frozen spear you can access your instance inside the template using {{object}}

frozen spear
#

@versed python hm?

versed python
#

you need to explain your problem a bit better than that

@versed python hm?
@frozen spear

frozen spear
#

spoiler by accident

#

so

#

i want these vars

#

to display

#

in the template

versed python
#

you don't need a for loop

#

simply type {{object.text}}

frozen spear
#

but to iterate

#

so like once u submit an

#

entry

#

its gonna display it

versed python
#

simply type {{object.text}}
@versed python just type this

frozen spear
#

@versed python still the same D:

#

prob cuz not defined in the detail view

versed python
#

@frozen spear you need to learn the basics of DetailView. Look at the django docs

frozen spear
#

alrighty

#

:D

#

omg nooo

#

an error

versed python
#

you have written a lot of useless code

#

and the get_context_data method doesn't even do anything in your case

#

do this:

#

replace getpk with get_object

#

remove get_context_data

#

and replace for loop in your html, and write {{object.text}} etc

#

@frozen spear

frozen spear
versed python
#

Jesus

#

Look DetailView doesn't inject a queryset into your template. It injects a single object (thats why it is called DetailView duhh). By convention you can access the injected object in the html file by {{object}}. @frozen spear

abstract rover
#

Hello, could someone please help me with a XML/XSL problem:

#

Sample XML data:

<superbowl>
  <games>
    <No.>I</No.>
    <Date>Jan. 15, 1967</Date>
    <Location>Los Angeles Memorial Coliseum</Location>
    <Winner>Green Bay</Winner>
    <Result>Green Bay 35, Kansas City 10</Result>
  </games>
#

I want to use XSL to select and show only the Superbowl Winner Teams who won after the 1960's

#

The problem is that the date is in Mon. DD, YYYY format: Jan. 15, 1967
And I need to sort by year.

#

I think I have to break down the date format into variables and then sort by the variable which contains YYYY

#

But I don't know how.

#

Or use regex to select 4 digits, store it in a variable and then sort

abstract rover
#

Here is my solution:

<table border="1">
  <tr>
    <th colspan="2">Superbowl Winners after 1960</th>
  </tr>
  <tr>
    <th>Winner</th>
     <th>Date</th>
  </tr>
  <xsl:for-each select="superbowl/games">
    <xsl:variable name="year" select='matches("\d\d\d\d")'/>
    <xsl:sort select="year" data-type="number" order="ascending"/>
    <xsl:if test="year &gt; 1960">
    <tr>
      <td id="Winner"><xsl:value-of select="Winner"/></td>
      <td id="Date"><xsl:value-of select="Date"/></td>
    </tr>
    </xsl:if>
    </xsl:for-each>
</table>
dawn heath
native tide
#
{
  "users": [
    {
      "email": "sairamkumar2022@gmail.com", 
      "id": 1, 
      "keys": [], 
      "name": "Sairam", 
      "password": "123456789", 
      "type": "developer"
    }, 
    {
      "email": "ponvannan2006@gmail.com", 
      "id": 2, 
      "keys": [], 
      "name": "Ponvannan", 
      "password": "28454", 
      "type": "developer"
    }
  ]
}

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

#

Well, the id startswith 1 instead of start number

#

I've even set the type of squence to bigint

#

but still doesn't work

vestal hound
#

but still doesn't work
@native tide what?

native tide
#
id = db.Column(BIGINT, db.Sequence('users_id_seq', start=100000000000000000, increment=1), primary_key=True)
#

I have something like this

#

@vestal hound

#

the sequence is not used

vestal hound
#

is that SQLAlchemy?

native tide
#

I want to start the ids with 100000000000000000 but it doesn't work

#

yes

#

flask-sqlalchemy

#

now how should I fix it?

vestal hound
#

which database?

safe palm
#

Sorry, could somebody help me to retrieve an image from a site that requires auth in #help-donut

#

?

native tide
#

@vestal hound postgres sql

#

postgres

#

@versed python ?

#

please ping me everytime responding

versed python
#

@native tide I think you meant @vestal hound

native tide
#

can you help me?

#

I think he is offline

wide leaf
#

can you do front end web development with python?

versed python
#

can you help me?
@native tide nope, I don't use flask

native tide
#

ok, fine

versed python
marsh canyon
#

there is something called brython also

native tide
#

Hey, anyone there?

#

@worn rapids hello?

marsh canyon
#

hello @native tide, this channel is for questions related to web dev (the channel topic), for general discussion, you can use off-topic channels

#

!off-topic

lavish prismBOT
frosty bluff
#

hey @marsh canyon

marsh canyon
#

yes?

desert lake
#

Can I ask you a question about "django"?

marsh canyon
#

yes @desert lake

frosty bluff
#

i want sum of column where student = xyz

#

in django admin

desert lake
#

All parameters of the user request are created in "QueryDict" object.

marsh canyon
#

do you number of students? @frosty bluff

frosty bluff
#

ya

marsh canyon
#

is Student a model?

desert lake
#

Why are all the parameters of QueryDict listed?

frosty bluff
#

ya

marsh canyon
#

you can do Student.objects.Count() to get number of students

#

you can tweak the admin pannel to include this too

#

Why are all the parameters of QueryDict listed?
@desert lake i didn't quite understand your question

frosty bluff
#

no i want to sum column values of another model and display right next to each student name

marsh canyon
frosty bluff
#

i saw that already 😬

marsh canyon
#

you need to override the list_display variable

frosty bluff
#

i know

marsh canyon
#

can you show me ur models

frosty bluff
#

i need just annotate funciton

desert lake
#

sorry.

#

The parameter of url becomes QueryDict.

ex: http://url?a=1&b=2.
-> QueryDict(a=[1], b=[2])

Why is a single variable to QueryDict in "list"?

frosty bluff
#

i can dm you @marsh canyon

marsh canyon
#

k

#

because @desert lake this is also a possibility

#

this is from the docs

desert lake
#

yes. I readed but

#

Isn't a single variable more efficient?

#

Why is it forced to be "list"?

marsh canyon
#

well thats how it is :/

desert lake
#

XD ok ty iceman !!

marsh canyon
#

I dug into the source code and found that QuerySet inherits from MultiValueDict @desert lake

#

so i guess that explains it, it kinda expects multiple values for the same key

desert lake
#

@marsh canyon I thought so, too. Thank you so much!!

marsh canyon
#

also, another reason is consistancy i guess

#

example, you never know if ur geting 1 value or multiple values, and if u have mixture of lists and strings in the request object, then u will have to check each time

humble bobcat
#

Django: "FATAL: remaining connection slots are reserved for non-replication superuser connections" what a way to wake up on a Monday πŸ™ƒ

native tide
#

Is my question offtopic?

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

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

#

Well, the id startswith 1 instead of start number
I've even set the type of squence to bigint
but still doesn't work

#
id = db.Column(BIGINT, db.Sequence('users_id_seq', start=100000000000000000, increment=1), primary_key=True)
#

I want to start with 100000000000000000 instead of 1

#

anyone?

#

I'm using Postgres with Flask

#

SQLAlchemy with Flask, and python 3.8.5

#

PostgreSQL

#

Info enough?

#

do I need to post the whole code?

zealous cloud
#

Can anyone help me access items from this list of python dictionaries? I am trying to use this info in my jinja template, but my code below is only printing the first bill_id and title of each dictionary. This list contains 4 total dictionaries. I would like all the bill_id and title from each of the 4 dictionaries, but have no idea how to access them or loop through.

{% for record in members_data %}
    <div class="row justify-content-center mt-3">
      <div class="card bg-white w-75 my-4">
        <div class="card-header font-weight-bold">
          <a href="/search/bill/{{record['results'][0]['votes'][0]['bill']['bill_id']}}">{{record['results'][0]['votes'][0]['bill']['bill_id']}}</a>
        </div>
          <div class="card-body bg-info">    
            <h5 class="card-title">Bill info - <span class="text-primary">{{record['results'][0]['votes'][0]['bill'].bill_id}}</span></h5>
            <p> {{record['results'][0]['votes'][0]['bill'].title}} </p>
          </div>
      </div>
    </div>

{% endfor %}

And here is my pastebin with the json object. I've been quite stuck for several hours trying to mess around with this data so any help is greatly appreciated
https://pastebin.pl/view/2ee67239

nimble epoch
#

@zealous cloud can i see your dict?

zealous cloud
#

@nimble epoch The pastebin doesn't show it?

nimble epoch
#

Oh ok

#

Sorry man. Gotta go. Maybe next time.

zealous cloud
#

That's the object Im working with. It's basically a list with 4 dictionaries inside

#

no worries

native tide
#

I would remove all the css classes and simply the dict and see if it works then.

zealous cloud
#

@native tide Im getting the correct info, but I'm not looping through this object correctly. My guess is the results[0] line. Basically the current bug I have is that the loop goes to the first bill of all four dictionaries and returns the bill_id and title. I want to loop inside of each of these dictionaries and get all the bill_id and all the titles, but I don't know how to do this

versed python
#

they have a discord, you might find better help there

native tide
#

wait a sec

#

it is an issue with database

versed python
#

you have been asking this question for a long time, maybe no one knows the answer @native tide

#

I recommend you get more specialized help from flask discord

native tide
#

@zealous cloud I see. I think that's a simpler problem then. You need a nested for loop then. first loop handles members. Second loop handles bills for each member

#

well, it is a problem with Database

#

id isn't startwith correct one

#

that is 10000000000

#

instead it startswith 1

#

which I don't want

zealous cloud
#

@native tide Oh i hadn't considered a nested loop. Can I handle that in my jinja template as well?

#

I guess I didnt consider this because I was getting back the correct info, but only the first item of each of the 4 dictionaries, so I thought it must've been some other error on my part

versed python
#

@native tide if your model defines an autoincrement then you cant start from 100000

native tide
#

well, I think so

#

but if I put autoincrement=False

#

then it don't even increment

#
id = db.Column(BIGINT, db.Sequence('oauth2_code_id_seq', start=10000000, increment=1), autoincrement=False, primary_key=True)

it didn't even made the sequence if I put autoincrement=False

zealous cloud
#

@native tide Awesome thanks. Ill give it a look

native tide
#

@versed python see

rotund token
#

surely someone should help me re-organise my files??

versed python
#

@native tide as I said earlier, I don't know how to solve this problem. I again suggest you go to r/flask or flask discord

#

surely someone should help me re-organise my files??
@rotund token is it a django project?

winter spindle
#

hello !

#

why doesnt anything show up on my webpage when i do so ?

#

soo i have started learning flask soo this is the issue i am into

#

can some1 help?

zealous cloud
#

@winter spindle Are you running your flask environment as development? What sort of output are you getting?

winter spindle
#

no it runs absolutely fone

#

fine

#

but i dont get any thing on my page

zealous cloud
#

oh is your app = Flask(name_) line supposed to be called flaskblog?

#

I think it might be looking for something called app

#

but doesn't look like you have that

winter spindle
#

wait lemme explain

#

its like

#

the problem is in redering templates

native tide
#

@versed python invite??

winter spindle
#

cuz if instead of rendereing templates i do return

#

it shows up fine

native tide
#

got a ping

versed python
#

check dms

zealous cloud
#

so your about route is returning the h1 with the about page but your / route is not rendering the template?

sturdy sapphire
#

remember guys that we do not allow ads on this server. including non-partnered discord servers.

winter spindle
#

no none of the templates are rendering idk why

versed python
#

remember guys that we do not allow ads on this server. including non-partnered discord servers.
@sturdy sapphire sorry dude I was sending an invite to @native tide for flask discord, since no one was able to answer their question here

winter spindle
#

only this is there in my webpage !

cinder juniper
#

There's the official flask server you can find in the server discovery by searching flask @native tide

native tide
#

oh

#

ok

#

thanks

sturdy sapphire
#

I see... it might just be a slow day. we normally have a lot of experience with flask here

winter spindle
#

i have issue rendering templates

#

can some1 help ?

native tide
#

well, I'm having issues with db

winter spindle
#

@anyone ?

#

@sturdy sapphire can u help me regarding rendering templates ?

native tide
#

I'll wait, finish off everyone's doubt, then finish off my issue, if possible

versed python
#

@native tide you can try to get a help channel?

native tide
#

well, I got one, but no one helped me

versed python
#

try again

native tide
#

ok, will try

rotund token
#

@rotund token is it a django project?
@versed python nah

zealous cloud
#

Do you need that last line that says if name_ = main? Try to comment that out for now and then add this route

@app,route('/)
def get_home():
    return render_template('home.html')

if you're starting flask from your command line just copy the url that pops up under running on, make sure the environment is set to development. Let me know what that shows.

winter spindle
#

wait i ll try

native tide
#
@app.route('/')
def get_home():
    return render_template('home.html')

@winter spindle fixed some syntax error

winter spindle
#

ohkayy got it i am such a fool !

#

i didnt save my html file

#

thanks a lot !

zealous cloud
#

it happens

zinc hill
#

My template is using deleted static css.file and im so confuse

#

I made a base.html which use the style.css static file (resturant/static/resturant/style.css)
but when I delete that static folder, the html is still using it.....

#

but if i delete

    <link
      rel="stylesheet"
      type="text/css"
      href="{% static 'resturant/style.css' %}"
    />
``` it breaks
#

anyone have any ideas why?

#

omg its mb its ctrl+f5 to bypass the cache....

acoustic oyster
#

You can also do shift+refresh button to refresh the cache on many browsers

astral musk
#

best to test your site in incognito mode

grizzled sand
#

hey guys, sorry for nubby question about Django, but cant realize what is wrong, trying follow by official mozilla documentation but getting error on step database makemigrations

django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'catalog.urls' from 'M:\\Site\\catalog\\urls.py'>' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import.``` 

link on education resource what i use: ``` https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/skeleton_website ```**

Thanks**
versed python
#

can you post catalog/urls.py? @grizzled sand

grizzled sand
versed python
#

you have misspelled urlpatterns

#

also urlpatterns list shouldn't be empty

grizzled sand
#

thanks so much!

astral musk
#

what would you call an input field that acts like a search field that lets you look up entries that can be selected as input values for that field?

#

like for example when you tag someone on twitter, you write @cosmic drum and the user shows up

marsh canyon
#

I would pick a charfield

astral musk
#

this is a django field?

marsh canyon
#

that can be selected as input values for that field?
by this, you mean choices?

astral musk
#

yeah, choices

marsh canyon
#

ur working with django?

astral musk
#

no, flask

marsh canyon
#

okay shouldn't be much different

astral musk
#

I just looked up charfield and got a lot of django results

marsh canyon
#

u will need javascript if you want names to pop up while searching

astral musk
#

yeah figure as much

marsh canyon
#

so you will need an endpoint that will return a list of similar name

astral musk
#

what I'm after is to create an input field where you search for names, have the names pop up, select some names and send those as a list or whatever

marsh canyon
#

so the input field, can be just text tho, nothing related to django/flask on the field

#

okay so you want to select multiple users

astral musk
#

I'd basically need the javascript to be able to tap into my database and display their names in the field but send their id tags as values

#

I'm just looking for terms to google

zinc hill
#

autocomplete search

marsh canyon
#
-> search field(input text field in html)
-> User types in search field
-> javascript checks for event and sends a GET request to get similar names to the user input```
vague ibex
#

its just basically a check in the database, adding the suggest words from database to array and applying a method to it so that the suggestion thing comes up

#

if you're having a database

marsh canyon
#

u dont want to check the database directly from javascript, have an endpoint in ur flaskapp that does that

astral musk
#

guess I could look into making an api for it

marsh canyon
#

yes

versed python
#

making an api would be overkill, just return the data in json format

astral musk
#

good starting point, thanks

native tide
#

Hey guys how can I pass data from the backend to a React frontend? Will Jinja2 still work (I don't think so)

astral musk
marsh canyon
#

@native tide when you plan on using a front end framework, like react, you will want to fetch data from a server via a rest API (in ur case, its flask), jinja2 will only work if you render templates using flask.
But as you plan on using react, you will need to send HTTP requests to ur flask server to get the data, process it and the display it. In this process, you are not rendering template using flask instead, react is doing the template stuff, so jinja2 will not work here.

native tide
#

Thank you @marsh canyon, just getting started with it. I'll try to hack something up πŸ™‚

versed python
#
class Layout(models.Model):
    image = models.ImageField(upload_to='path/')

I want to create a new instance of Layout using Layout.objects.create(image='?'). However I can't really figure out what to put in place of the ?. Do I put the file path? Or the file.read()?

This is django

#

also please note that uploading images using admin works fine. I am looking for a way to automate it

burnt night
#
{% if form.confirm_password.errors %}
    {{ form.confirm_password(class="form-control form-control-lg") }}
    <div class="invalid-feedback">
        {% for error in form.confirm_password.errors %}
            <span>{{ error }}</span>
        {% endfor %}
    </div>

{% else %}

    {{ form.confirm_password(class="form-control form-control-lg") }}
    
{% endif %}

Has the way to do this changed? (Checking for form errors)

native tide
#

anyone here who can help me with a flask problem?

versed python
sly canyon
#

is it possible to add an event listener (to a button, for instance) that doesn't relly on JS?

native tide
#

ok

astral musk
#

@burnt night looks about right to me, lacking label though
here's mine:

<div class="form-group">
    {{ form.confirm_password.label(class="form-control-label") }}
    {% if form.confirm_password.errors %}
        {{ form.confirm_password(class="form-control form-control-lg is-invalid") }}   
        <div class="invalid-feedback">
            {% for error in form.confirm_password.errors %}
            <span>{{ error }}</span>
            {% endfor %}
        </div>
    {% else %}
        {{ form.confirm_password(class="form-control form-control-lg") }}
    {% endif %}
</div>

burnt night
#

label was right above it, so my bad

#

Oh, was it just because i was missing the is-invalid class?

#

Yay, it's working now... thx

astral musk
#

thats what would make it look red if you type in something wrong

burnt night
#

i wasn't getting anything at all until i added it in πŸ€·β€β™‚οΈ

#

i don't understand...

#
password = PasswordField("Password",
    validators=[DataRequired(), Length(min=5)])
    confirm_password = PasswordField("Confirm Password",
    validators=[DataRequired(), Length(min=5), EqualTo(password)])```
I have this
#

Where did i do something wrong?

jagged lark
#

Look at how you defined your field password

#

You used quite a few variables to define it, including password itself

#

But, that’s impossible, because you use password to define password

burnt night
#

πŸ˜•

#

I don't understand...

astral musk
#

looks like he used password in confirm_password

#

should be fine

#

do you have a longer traceback?

native tide
#

in flask i have a navigation bar that lets the user switch between multiple html pages. the contents of the html pages are dynamic and i currently have the problem that when html page 2 wants to redirect to html page 1 there will be an 400 bad request error because the dynamic content that is supposed to be displayed in html page 1 is not known by html page 2. html page 1 only knows what to display because at the start of the execution there is a python script that passes these values as parameters to the html page. but the other html pages dont know these parameters so is there any way to make a html page "remember" the dynamic contents it is supposed to be displaying?

astral musk
#

or anything from debug mode

burnt night
#

No :(
Debug mode errors will be shown in console?

#

i don't see the debug file so i assume it wasn't created

astral musk
#

debug mode would just display the traceback in your browser

burnt night
#

all i'm seeing is

Invalid field name '<UnboundField(PasswordField, ('Password',), {'validators': [<wtforms.validators.DataRequired object at 0x03985BF8>, <wtforms.validators.Length object at 0x03985C10>]})>'.```
#

i'll check now

#

or so i said... but where would it show?
I thought there was a debug tab in inspect element

astral musk
#

when you run the app, set debug=True
I do it like this

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

burnt night
#

yea i have that

astral musk
#

oh

swift sky
#

lets say I had a for loop in jinja which listed some parsed urls and their date

astral musk
#

in confirm_password you have it set to EqualTo(password)

swift sky
#

how would I actually change those urls to actual links

astral musk
#

you want EqualTo('password')

burnt night
#

OH

astral musk
#

guess thats what @jagged lark meant

burnt night
#

it works... Thanks

swift sky
#

any help xD

#

 <body>
    {% extends "staff_parent_template.xhtml" %}
    {% block content %}
    <h1> Welcome to the Knowledge Articles page </h1>
    <p> these are the new articles for today </p>
    <h3>
        {% for url in dict_to_be_passed %}
        {{ url }}
        {{ dict_to_be_passed[url] }}
        {% endfor %}
      }}</h3>

    {% endblock %}
  </body>```
astral musk
#

url_for()

swift sky
#

yeah but

#

that wont work in this scenario?

#

because basically those urls are loaded and parsed every 2 hours

burnt night
#

what are the 2 closing braces for?

swift sky
#

so it'll always change

astral musk
#

no routes for those urls to use?

swift sky
#

yeah it's an external link

#

not something I want to store locally

#

I think I could just make them an href somehow?

astral musk
#

and they change every 2 hours?

swift sky
#

yeah, basically my script loads a sitemap and parses it for pages htat have been updated within the last 3 days

#

and it does that every 2 hours

#

it then takes that content and places it in a page, within my flask app

astral musk
#

I'd send those urls as arguments through the route that generates the template then

swift sky
#

so i have it as a kwarg

astral musk
#

yea

#

urls=urls πŸ˜„

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

dict to be passed is the dictionary containing the urls and time of last modification

astral musk
#

guess you can iterate through that dict?

swift sky
#

one second

hardy thicket
#

how do I write my html the correct way to access the form data using flask WTForms?
my HTML right now is:

<img class="wave" src="./static/img/wave.png">
        <div class="container">
            <div class="img">
                <img src="./static/img/bg.svg">
            </div>
            <div class="login-content">
                <form action="/login" method="POST">
                    <img src="./static/img/avatar.svg">
                    <h2 class="title">Welcome</h2>
                    <div class="input-div one">
                    <div class="i">
                            <i class="fas fa-user"></i>
                    </div>
                    <div class="div">
                            <h5>Username</h5>
                            <input type="text" class="input">
                    </div>
                    </div>
                    <div class="input-div pass">
                    <div class="i"> 
                            <i class="fas fa-lock"></i>
                    </div>
                    <div class="div">
                            <h5>Password</h5>
                            <input type="password" class="input">
                    </div>
                    </div>
                    <a href="#">Forgot Password?</a>
                    <input type="submit" class="btn" value="Login">
                </form>
            </div>
        </div>
        <script type="text/javascript" src="../static/js/main.js"></script>```
#
class LoginForm(FlaskForm):
    username = StringField('username', validators=[InputRequired(), Length(min=4, max=15)])
    password = PasswordField('password', validators=[InputRequired(), Length(min=8, max=80)])


@app.route('/')
@app.route('/home')
def home():
    return render_template('index.html')

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

    if form.validate_on_submit():
        return '<h1>Test, ' + form.username.data + '</h1>'
    return render_template('login.html', form=form)```
swift sky
astral musk
#

well there you go

#

could be prettier but the links are there

swift sky
#

 <body>
    {% extends "staff_parent_template.xhtml" %}
    {% block content %}
    <h1> Welcome to the Knowledge Articles page </h1>
    <p> these are the new articles for today </p>
    <h3>
        {% for url in dict_to_be_passed %}
        {{ url }}
        {{ dict_to_be_passed[url] }}
        {% endfor %}
      }}</h3>

    {% endblock %}
  </body>```

@swift sky @astral musk this is the iterating of the urls

#

yes but you can't click them

astral musk
#

surround them with a tags

swift sky
#

so here

#
        {% for url in dict_to_be_passed %}
        {{ url }}
        {{ dict_to_be_passed[url] }}
        {% endfor %}
      }}</h3>```
astral musk
#

yea

swift sky
#

as such

#
        <a>
        {% for url in dict_to_be_passed %}
        {{ url }}
        {{ dict_to_be_passed[url] }}
        {% endfor %}
        </a>
      }}</h3>```
#

but then also the dates shouldnt be links

#

they should jsut be dates

astral musk
#

    <p> these are the new articles for today </p>
    <h3>
        {% for url in dict_to_be_passed %}
        <a class="prettyclass" href="{{ url }}"> name for url </a>
        {% endfor %}
      }}</h3>
    {% endblock %}
  </body>

#

although I suspect dict_to_be_passed[url] will return something confusing

swift sky
#

one second

#

testing

#

ok well

#

that did something

#

it basically turned the dates into urls

astral musk
#

yeah youre iterating through a dictionary in a template file, might wanna look up how thats done

swift sky
#

well the dates navigate to the right url

#

so that's kinda good

astral musk
#

you could cheat and pass two lists that you know are in the same order instead of the dict

#

just turn the dict into two lists in your route

swift sky
#

I'll see

#

is there a way that I can narrow this out, should I do this in CSS?

#

I don't like the formatting

#

like each entry should be its own line

astral musk
#

add a <br/> behind the </a>

#

could also wrap the <a> in a <div> and give that a nice style

#

if you want to cheat you could just throw bootstrap at it

swift sky
#

so im working with a friend

#

I put him in charge of a lot of the front end stuff

#

my main problem was the urls not being clickable

#

so thank you!

astral musk
#

fair enough, just wrap it in a <div> and give it a class so he has something to work with

swift sky
#

add a <br/> behind the </a>
@astral musk should there also be a <br>

#

and by behind the </a> your mean <br/></a>

astral musk
#

no, those are unique, they just turn into a line shift. But if you wrap it in a div you don't need the <br/> at the end

#

no

swift sky
#

i wrapped it in a div

astral musk
#

behind πŸ˜›

swift sky
#

i did wrap it in a div

#
    <p> these are the new articles for today </p>
    <div class="urls">
    <h3>
        {% for url in dict_to_be_passed %}
        <a class="updated_urls" href="{{ url }}">
            {{ url }}
        {{ dict_to_be_passed[url] }}</a>
        {% endfor %}
      </h3>
    </div>```
astral musk
#

the div should take care of it once your friend styles it

#

but I guess the <br/> wont do too much damage

#

oh you wrapped the entire loop there in a div btw, that will make one div box that surrounds all your links. What you want is to surround <a> ... </a> with a div

#
<h1> Welcome to the Knowledge Articles page </h1>
 <p> these are the new articles for today </p>
  <div class="urls">
    <h3>
        {% for k, v in dict_to_be_passed.items() %}
        <div class="urls">
          <a class="updated_urls" href="{{ dict_to_be_passed[k] }}"> {{ v }} </a>
        </div>
        {% endfor %}
    </h3>
  </div>
#

@swift sky try that - dunno how your dictionary is structured though, or if this even works in a template

native tide
#

hi, how do i make a button with flask that when clicked it redirects to another def thepagename(): ?

swift sky
#

thanks @astral musk with that configuration it just shows the date which is the v

#

but I actually need both the url to show and the date

#

adding a ,

#

makes it so that there are '' around the values, and it also gives a 'datetime name before the datetime value

frozen spear
#

@versed python πŸ‹

versed python
#

what? @frozen spear

frozen spear
#

big confuses

versed python
#

Please don't ping me like this if you need help

#

others are just as likely to help you

frozen spear
#

mm okay sorry i was just bit of confused about yesterday but its okay

versed python
#

Yesterday?

#

timezone differences i guess

#

what do you need?

frozen spear
#

oh

#

the

#

detailview things and object and so

#

im literally

#

confused

versed python
#

about?

#

dm me

frozen spear
#

alright

dapper heath
#

I have made my website on Django and currently hosted on heroku but wish to host on my desktop-linux. I have bought my domain but having problem in hosting on laptop.

rough violet
#

You’ll need to set a static ip for that machine, probably need to set up port forwarding, and then you should be able to point the domain name to that ip

jaunty plover
#

hey, is there an "easy" way to interact with the discord API using d.py from django ?

eternal frigate
#

Is it possible to change flex direction based on how many flex items fit in a single row?

lavish prismBOT
#

Hey @royal musk!

Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:

β€’ If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)

β€’ If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:

https://paste.pythondiscord.com

royal musk
swift sky
#

so image src is not showing an image that I'm hosting locally

#

i think it's a pathing issue

frozen spear
maiden kraken
#

try changing order

#

put class GIveaway before Entry

frozen spear
#

yes done i changed somethings

#

now i need to see if there is any bugs

#

ah

maiden kraken
#

you have problem in Giveaway class, str method

#

you are passing id which is not defined i think

#

I think the same problem is in Entry class

frozen spear
#

oh fuck i guess i removed str metd by accident

maiden kraken
#

im no expert in this topic, but I think django creates hidden id column for your models, so maybe that's not a mistake there. Have you run makemigrations and migrate?

lethal orbit
#

Should just be entry.id no?

frozen spear
#

ok im kinda sick but i migrated now and i need to check if everything works fine

lethal orbit
#

or entry.entry.id

frozen spear
#

i reversed the

#

foreignkey

#

ok everythng is fine maybe

#

thanks solar and pat

swift sky
#

anyone have experience serving pdf files with flask

lethal orbit
#

anyone have experience serving pdf files with flask
@swift sky you're probably better off serving them with nginx

swift sky
#

but then how do I test if it works localllyyyy

#

halp

#

how would that even be accomplished though

#

like instead of the file path from my local host, i store it on the server and nginx does what with it?

#

do I just change the path in my flask app, to where it would be stored on the server? I'm confused

lethal orbit
#

Normally, you would store those in e.g. /media on your server and configure nginx to serve those directly, and route the rest to your wsgi server

frozen spear
#

can i check foreign key in template language

#

if a giveaway have a foreign key entries its gonna display the entries

#

if no

#

its gonan display a text

maiden kraken
#

I think you have to define related_name= into your Foreign key definition

night drum
#

@lethal orbit if you still have time, could you tell me if the send_from_directory function from flask has any significant disadvantages compared to a direct delivery by the NGINX?

maiden kraken
#

and then you can access it by this name

lethal orbit
#

@lethal orbit if you still have time, could you tell me if the send_from_directory function from flask has any significant disadvantages compared to a direct delivery by the NGINX?
@night drum performance.
Sending files and Performance
It is strongly recommended to activate either X-Sendfile support in your webserver or (if no authentication happens) to tell the webserver to serve files for the given path on its own without calling into the web application for improved performance.
https://flask.palletsprojects.com/en/1.1.x/api/#flask.send_from_directory

quick cargo
#

python is significantly slower than Nginx or a compiled server for sending files

night drum
#

ahhh i see, makes sense. Thank you!

swift sky
#

and where is the /media stored in the server? like what's the directory structure, or is that irrelevant? @lethal orbit

lethal orbit
#

Doesn't really matter. A subdirectory of /srv/http is common, as well as /var/www or /opt/my_app_title ...

#

Depends on your distro and other factors.

swift sky
#

my server is a mess

#

im looking at this

#

the only server {} i have is under the #mail settings

#

in the config file

lethal orbit
#

Look at tutorials, rather than forums (unless you have the same problem πŸ˜„ )

swift sky
#

i tried to google some tuts

#

how to use nginx to serve static files digitalocean

#

i mean it's not a static website just a page

lethal orbit
#

Configure the flask parts first... then just add a /media path that is served directly.

swift sky
#

im looking at one on medium now, I will take a look at that yours. I used that one previously.

#

I mean my site is up

#

this is my first attempt at putting some images up tho

#

so I don't touch the systemd file at all for this?

#

just nginx config and load the files to the directory I want

lethal orbit
#

What distro is your server running?

swift sky
#

ubuntu

lethal orbit
#

They usually have a sane default systemd file.

#

Just sudo systemctl enable --now nginx should be enough

#

(Or similar, typed the command off the top of my head)

#

All the configuration would be in nginx.conf

#

Normally, you define locations (location /media { ... settings ...}), and tell nginx to serve those.

#

Then you add another location (location /) and give it a proxy_pass option to route the requests it can't serve directly to a wsgi server that runs flask.

swift sky
#

i see

cunning birch
#

Hi everyone I made an ecommerce site with django / postgresql / redis / celery / rabbitmq and I configured nginx and uwsgi for deployment but can tell me if platform "paas" or "iaas" to deploy my app?

sly canyon
#

Can I access a FlaskForm object directly from JINJA2, without having to parse a form parameter to render_template('page.html', form=MyForm)?
Something like:

{% with form = get_here('route.forms.MyForm') %}
  {{ render_form(form) }}
{% endwith %}
topaz widget
#

Does anyone know how to get python manage.py loaddata to work properly (with Django)? I'm trying to migrate the contents of a database to a new one and keep getting the following error : DETAIL: Key (id)=(1) already exists.

cunning birch
#

hi @topaz widget you must first do dumpdata to store the file on a json file on your development server before exporting it to a json

topaz widget
#

Yes, the data is in a JSON file (produced from the following command: python manage.py dumpdata). The problem is when trying to loaddata, it gives a key error. The tables should be empty, as I also did python manage.py flush. @cunning birch

cunning birch
#

@topaz widget I believe I have already encountered a similar problem.
generally I try to delete the data base and activate the developer mode of the browser because often "Google Chrome" plays the tricks on us.

#

and you deploy on which platform?

topaz widget
#

@cunning birch It really shouldn't have anything to do with a browser. I am performing these operations on my server via ssh. Ubuntu server is the OS of my server.

#

Postgres is the database

lethal orbit
#

@topaz widget sounds like the DB isn't properly empty... try python manage.py shell, import your models, and see what Foo.objects.all() prints (for object Foo)

topaz widget
#

I already did that with the Users model. Let me try with the model it's barking about in the error message.

#

@lethal orbit Yeah, that returns an empty Queryset, too: <QuerySet []>

lethal orbit
#

Very strange. Any foreign relations?

topaz widget
#

If by that you mean does it have any foreign keys, then no, other than the OneToOneField that associates it with a User model.

#

which I have also checked and is also empty.

lethal orbit
#

Strange. Can you share more details? The JSON data itself (scrubbing anything private) and the full error output?

topaz widget
#

It would be difficult to scrub the JSON data of anything private, but I can show more of the error message.

#

django.db.utils.IntegrityError: Problem installing fixture 'db.json': Could not load auth.User(pk=1): duplicate key value violates unique constraint ``"users_userglobalstyles_user_id_key"
DETAIL: Key (user_id)=(1) already exists.

#

UserGlobalStyles is a model that lets users customize the style of certain aspects of the website.

#

Here's more of the traceback preceding that error:

File "/django_project/venv/lib/python3.7/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/django_project/venv/lib/python3.7/site-packages/django/db/models/query.py", line 1249, in _insert
    return query.get_compiler(using=using).execute_sql(returning_fields)
  File "/django_project/venv/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1395, in execute_sql
    cursor.execute(sql, params)
  File "/django_project/venv/lib/python3.7/site-packages/django/db/backends/utils.py", line 66, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "/django_project/venv/lib/python3.7/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "/django_project/venv/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "/django_project/venv/lib/python3.7/site-packages/django/db/utils.py", line 90, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/django_project/venv/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
quick cargo
#

you're trying to insert something with a identical Primary key instead of updating the existing value

#

Primary Keys must be unqiue

topaz widget
#

Except there isn't anything in the table

#

Or there shouldn't be at least.

#

The only thing that would have added table data is running python manage.py migrate before running python manage.py loaddata.

#

I tried reversing the order but run into the problem that the tables don't exist if I run loaddata first.

quick cargo
#

did you tell it to ignore the meta data when dumping the original data?

topaz widget
#

No, how do you do that?

quick cargo
#

Ngl i cannot remember off the top of my head

topaz widget
#

I saw something that vaguely seems like it might be the same thing when searching for the solution online.

quick cargo
#

Ive had these sorts of issues before where if you dont tell it to specifically ignore all the Metadata tables they break when you load them back because the migrations will auto create all the tables themselves

topaz widget
#

Right, yeah.

#

I assumed that was probably the issue. Unfortunately, the error messages don't clearly show the tables causing the problems.

quick cargo
#

tbf worse cause sanario you can just load the json file with a python script and just send it to a temp endpoint to insert the things you need

lethal orbit
#

I usually use data loading scripts and not fixtures.

topaz widget
#

Worst case scenario is I just load all the database info by hand, which is not that much right now but still a pain, and I should really learn how to do it properly for when my database has way more data than I could enter by hand.

quick cargo
#

Ive low key manually transfered a couple gigs worth of db before

#

dumped to json and just made a simple script that manually re did it

#

well i say manually

#

i just clicked play after coding it

topaz widget
#

The only things my database has in it right now are a superuser, a test user with regular permissions, and background images for about a dozen pages.

#

I could do this all manually, but I ran into this issue a few weeks ago and just did the manual approach. Eventually the database will require a script or doing it the proper way.

topaz widget
#

ty

lethal orbit
#

If you pass DJANGO_SUPERUSER_PASSWORD and DJANGO_SUPERUSER_USERNAME as env variables, they get populated automatically, IIRC

#

So you don't have too keep the data inside scripts.

#

Of course, you can also us os.environ.get inside said scripts...

topaz widget
#

Thanks, yeah, on my server, I typically keep such data in a JSON file and then just use json.load.

lethal orbit
#

That is theoretically better... but yeah, sometimes loaddata is fickle lol

topaz widget
#

Well, I just got it to work for one of my apps

#

I just need to figure out which tables I need to exclude.

lethal orbit
#

If you just json.load and pass it to a model, that should also work.

topaz widget
#

There is an --exclude flag, which lets you exclude tables when doing dumpdata from the old database.

#

The problem is I don't know which tables are the problem...

#

But you can also specify single apps to do dumpdata for, which I seem to have gotten to work ( need to query the database in shell now to find out ).

#

Yeah, it worked for the app I did it with. Just queried the database and it looks like the background images (or references thereto) got transferred over.

lethal orbit
#

Sweet

#

That's especially great because it's bedtime xD

zinc hill
#

is there away to use

@method decorator(require=login, must be a certain class model)?```
topaz widget
#

@lethal orbit You must live in the eastern hemisphere.

#

@zinc hill Your syntax is confusing me.

zinc hill
#

oh mybad

native tide
#

are u guys done

#

can i ask question or na

zinc hill
#

yeah

native tide
#

ok

#

this is my button

#

just look at the button

#

this is my js

#

this is the error

#

I have no idea why it is null

#

the id is my_Btn

zinc hill
#

maybe check if getelementbyid("my_btn") is not null first

noble star
#

If I have a website (flask) and I have a web app (golang), could I just throw the go app into my flask website and add a link/route to it, and the app works properly?

native tide
#

ok I will try

zinc hill
#

so like

var j = document.getsomethingid(mybtn)
if j:
   do someting
native tide
#

i console logged the value of the document.getbyidbtn

#

thing

#

it says null

#

but it the same id

zinc hill
#

that i dont have a clue

#

what if you do onclick instead of dom

#

onclick=somefunction

native tide
#

yea

topaz widget
#

@lethal orbit @quick cargo So I figured out what the problem was with the database migration. When I import my auth.user models, it also imports the data for models that use the user as a foreign key (OnetoOneField in this case). Then, when I try to import those models, it also tries to import the data for each instance of those models (for which the user is a foreign key), meaning there is a duplicate record.
The issue can be mitigated by simply running dumpdata for auth.user (python manage.py dumpdata auth.user > auth_user_db.json) and then doing python manage.py loaddata auth_user_db.json) and then not doing loaddata for any models that depend on the user as a foreign key.

topaz widget
#

@zinc hill Don't use onclick, onblur, onfocus, etc...
Instead, use <object>.addEventListener('click', () => { ... } ), etc...
The reason is that you can only use onclick , etc... once for whatever element you're calling it on, whereas you can set as many event listeners as you like.

zinc hill
#

@native tide

topaz widget
#

Also, @native tide , when you call document.getElementById(), make sure you are using the proper capitalization. Mixing cases will not call the getElementById method.

native tide
#

i used onclick

topaz widget
#

You should use element.addEventListener('click', function () { ... } );

#

It's better, trust me. @native tide

native tide
#

still doesn't work

sturdy pike
#

Hey does anybody know where i can find a whole list of all the attributes of the django generic based class views?

topaz widget
#

@native tide Paste your code including the part where you call the element by id.

native tide
#
var button1 = document.getElementById("my_Btn")

button1.addEventListener('click', function () {alert("hello");});
topaz widget
#

Not technically Python, but all us web devs need to struggle with javascript

vestal hound
#

TypeScript for me

#

which is a lot better πŸ˜‚

#

Hey does anybody know where i can find a whole list of all the attributes of the django generic based class views?
@sturdy pike do you mean dir()?

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

Same thing, essentially.

#

Don't forget the semicolon after the first statement.

vestal hound
#

type checking helps a lot

sturdy pike
#

@vestal hound I'm trying to figure out all the attributes that are associated with each generic base view

#

It this not important? I want to modify some things, however I suppose I can just always add them into the view

vestal hound
#

if you mean "attribute" in the generally understood sense, dir will do what you want

native tide
#

still same error

sturdy pike
#

Give me the anatomy of the DetailView for instance, I want to know what it contains

#

!!

topaz widget
#

Can I see how you call your script in your html @native tide

native tide
#

what script

topaz widget
#

The <script> tag

native tide
#

this one

topaz widget
#

No, that's not your code.

native tide
#

wait

#

my friend added code in that file too tho

#

and it works

topaz widget
#

The src attribute needs to point to your js file.

native tide
#

why does the other code in the file work

topaz widget
#

If that's the case, it's not a problem with your script tag. Let me take a look.

native tide
#

do you want to liveshare

#

so u can see everything

topaz widget
#

In a minute maybe.

native tide
#

okay

topaz widget
#

Instead of using getElementById use querySelector('#my_Btn') and see if that works.

native tide
#

alright

topaz widget
#

So that would be var button1 = document.querySelector('#my_Btn');

native tide
#

oh okay

#

same error

#

should i try adding the script using the tag

#

see if it works then

topaz widget
#

Okay, so do this now:

#

hold on

#

I'm going to write a bit of JS give me a sec.

native tide
#

okay

topaz widget
#

window.addEventListener('load', function () {
var button1 = document.getElementById('my_Btn');
button1.addEventListener('click', function () { alert('hello');});
});

native tide
#

woh

#

wait

#

how did u do that

#

how

#

it worked

#

why is it window

topaz widget
#

So, somehow, the button is not there before the DOM content loads.

#

Are you using a front-end framework?

native tide
#

idk

#

u have to ask my friend that

#

it is a google extension

topaz widget
#

It might have something to do with Jquery.

native tide
#

maybe that affects something

topaz widget
#

JQuery might go through and modify the DOM or something.

native tide
#

idk

#

he used bootstrap

#

if that affects anything

topaz widget
#

Anyway, yeah, if you're having a problem like that in the future, just try running whatever code you want to run after the window object's load event.

native tide
#

alright thanks

topaz widget
#

Just wrap it in that 'load' event listener like I did.

native tide
#

alright

#

in the load function can i add more listeners

topaz widget
#

You can get more granular about what event triggers it, too, but "load" is basically the last one so the surest to work.

native tide
#

alright

topaz widget
#

Yeah, you can do whatever you want.

#

Honestly, though, the code I wrote is not optimal.

#

You should probably do this instead:

vestal hound
#

incidentally, anyone here use Celery and have advice on how to run asynchronous tasks?

topaz widget
#

Actually, @native tide , try this instead, and let me know if it works, please:

native tide
#

alright

topaz widget
#

var button1 = document.getElementById('my_Btn');
window.addEventListener('load', function () {
button1.addEventListener('click', function () { alert('hello');});
});

#

Replace what you have with what I just wrote.

#

@native tide Did you try that?

native tide
#

doesn't work

topaz widget
#

Okay, weird.

#

Same error?

#

null?

native tide
#

yep

topaz widget
#

Okay, weird. Just revert to the first way then.

native tide
#

ok

zinc hill
#

if I have a path

path('', views.index, name='index')

and current url path is customer/profile

<a href={% url 'index'%}></a>

does it send me to localhost/ or localhost/customer/profile/index.html?

topaz widget
#

@zinc hill If that is your root URL conf on the top line, it should send you to localhost/

zinc hill
#

oh ok

#

thanjks

topaz widget
#

But I think you need a space between 'index' and %}. At the very least a space makes it more readable.

zinc hill
#

yeah it i was typing it in here and didnt bother with format mb

distant trout
#

someone know how to create infinite scrolling with data coming from api calls?

zinc hill
#

my ROOT_URLCONF = 'mainapps.urls'

but it keep adding on to the existing url

#

when i click on the link

topaz widget
#

Hey @native tide Try the second way I showed you, but this time, make button1 a const instead of a var.

distant trout
#

I already created a normal pagination but I'd rather have an infinite scroll

native tide
#

ok i will try

#

error

topaz widget
#

@distant trout You basically need to load a new page with JSONResponse on the 'scroll' event.

#

Okay @native tide nevermind then.

#

Was worth a try.

distant trout
#

@topaz widget so i can get the next page with my current pagination, do i need to pass that page into the scrol event?

native tide
#

ok

topaz widget
#

You need to set an event listener for the "scroll" event that uses AJAX to get another page.

#

The event is triggered when you get close to the bottom of the page.

distant trout
#

@topaz widget ok, i kinda tried that but here is a problem, whenever it hits the bottom of the page, it loads in the entire page

#

the entire second page

topaz widget
#

Actually, the event is triggered on scroll but doesn't execute unless you are near the bottom of the page.

distant trout
#

the entire page as in everything, including navbar and etc

topaz widget
#

You mean it replaces the page you have with the second page?

distant trout
#

it loads in the 2nd page under the first page

#

but a little smaller

topaz widget
#

Well, you need to create some sort of model to separate your content from your page then and just load in the content.

distant trout
#

i can do that with JSON right?

topaz widget
#

JSON is how you would load the content from your database.

#

The model would need to be created in a models.py file.

distant trout
#

ahhh

topaz widget
#

And you might want to use a template to create each block.

distant trout
#

is that the <template> tag?

topaz widget
#

I figured out how to do this a while back. Give me a sec and I'll try to find my code from the views.py file.

distant trout
#

ok sure

topaz widget
#

In answer to your last question, no.

distant trout
#

ahh okay

topaz widget
#
def post(self, request, *args, **kwargs):
        context = self.get_context_data()
        if context['form'].is_valid():
            if self.request.is_ajax:
                context['form'].send_email()
                data = context['form'].cleaned_data
                return JsonResponse({
                        'status': 'success',
                        'message': render(self.request, 
                            'main/contact_submit_message.html', 
                            {'site_name': 'My Website'}).content.decode()
                    })
#

So 'main/contact_submit_message.html' is the template I was talking about.

#

This is within a class-based view, too, btw.

frozen spear
#

ajax!

distant trout
#

ahh i see

#

im gonna try and play around with that

topaz widget
#

So you need to use render( ... ).content.decode() to use the Django template.

distant trout
#

wait so what this is doing is

#

sending back JSONResponse to the client?

topaz widget
#

And then on the front-end, you need something that takes the message and plugs it into the appropriate element on the site.

#

@ your last question .... yes

distant trout
#

got it! thank you so much

#

gonna get to coding

topaz widget
#

There is a bit of front-end work, too.

#

But I think the back-end is the hardest part in this case.

distant trout
#

ill use ajax

topaz widget
#

It took me a day to figure that one out.

distant trout
#

yeah the backend part confuses me the most

topaz widget
#

Yeah, so if you use fetch or XMLHttpRequest or jquery, just have it append the html to whatever element you need to put it into once it loads.

distant trout
#

got it! again, thank you

topaz widget
#

I have used parentElement.innerHTML += <content>; to good effect on this one.

frozen spear
#

@topaz widget your pretty good with ajax things

topaz widget
#

Thanks.

frozen spear
#

i really got bit confused at ajax and gave up cuz of status 403

#

when sending formdata

#

been days trying to learn ajax

topaz widget
#

AJAX takes a while.

#

It's critical for modern websites, though, so you just need to plow through.

frozen spear
#

yes i mean i figured out but then i gave up on last second when everything worked

#

with is status 403 (forbidden)

topaz widget
#

Yeah, 403 is a weird error. You must have needed some authentication or something.

frozen spear
#

i actually needed some cookie csrf_token thing

#

and i was confusing

#

confused*

topaz widget
#

Okay, that makes sense.

#

Yeah, definitely don't forget your {% csrf_token %} unless you want to get hacked.

frozen spear
#

yes lol

topaz widget
#

Do you create a new FormData object when you send ajax?

sturdy pike
#

Don't yell at us science

frozen spear
#

yes scince

topaz widget
#

Okay, good, because you can have issues with your data not being in the proper format if you don't.

#

@sturdy pike I'LL YELL IF I FEEL LIKE IT!

sturdy pike
#

mabad.

topaz widget
#

@distant trout Are you still around? because there's something you might need to know.

distant trout
#

yes m here

topaz widget
#

k, your view class should look like this (give a sec):

sturdy pike
zinc hill
#

30mns gone.... I realised that I hard code href = 'index.html' thats why it was adding on to the path

sturdy pike
#

fuck my ass

topaz widget
#
class HomeView(TemplateView):
    template_name = 'main/home.html'

    def get_context_data(self, *args, **kwargs):
        context = super(HomeView, self).get_context_data(**kwargs)
        context['form'] = ContactForm(self.request.POST or None)
        return context
    
    def post(self, request, *args, **kwargs):
        context = self.get_context_data()
        if context['form'].is_valid():
            if self.request.is_ajax:
                context['form'].send_email()
                data = context['form'].cleaned_data
                return JsonResponse({
                        'status': 'success',
                        'message': render(self.request, 
                            'main/contact_submit_message.html', 
                            {'site_name': 'My Website'}).content.decode()
                    })
            else:
                return JsonResponse({'status': 'failed'})
#

@distant trout That's zoomed out from the code I showed you last time

#

You also need some import statements at the top of the file, but I'll let you find those.

sturdy pike
#

f that

distant trout
#

ahh i see

#

yeah ill figure out the imports

sturdy pike
#

copy n paste that badboi and cross them fingers

distant trout
#

lol

#

i think most of my learning came from copy and pasting but also adding my own code in the mix

topaz widget
#

I think that's how most people learn.

distant trout
#

oh haha

#

thats good to know

topaz widget
#

I mean, there's a lot in the code I pasted that is useless to your example, though.

#

But it should give you some idea as to the structure.

distant trout
#

yes! im here to dissect it

topaz widget
#

This is for a contact form I have on my website.

distant trout
#

yeah i figured.. what was this website if you don't mind me asking

topaz widget
#

It sends back a rendered html template, though, which is what you're looking for.

#

Give me a sec. I need to change something real quick and I'll share the URL

distant trout
#

ok sure

topaz widget
#

Had to make user registration inactive.

#

lol

swift sky
#

how does gunicorn actually work? I have some code that works locally but when i run the docker image, the login function doesnt work

#

i suspect it has to do with how gunicorn serves things

distant trout
#

oh wow that looks really neat

topaz widget
#

Thanks.

distant trout
#

is it custom css or did u use a css framework for it

topaz widget
#

It's all made from scratch.

distant trout
#

oh wow

topaz widget
#

(Django on back end tho)

#

Yeah, there are about 1500 lines of CSS lol

#

about 1000 lines of JS

#

I need to rewrite some of the JS actually.

distant trout
#

css hurts my head, so i usually just throw up a bootstrap cdn

topaz widget
#

Yeah, I just wanted to actually make a whole website from scratch for the practice.

#

Well, one page at least

#

There is a form there that uses AJAX

swift sky
#

do either of you guys know about gunicorn

topaz widget
#

Only a little bit.

distant trout
#

@topaz widget oh thats nice, i dont know how to play sudoku though πŸ˜…

topaz widget
#

Oh, okay.

#

It solves sudoku puzzles

distant trout
#

i want to make a website from scratch now

#

since i always relied on other frameworks

topaz widget
#

Look at the script tag there, and you can see a big AJAX function I used.

#

It might actually help you out with your application.

distant trout
#

yeah thats large

topaz widget
#

Frameworks are probably better for most cases, but for educational purposes, doing it the hard way makes you learn more.

#

If you double click in browser it will format the JS

distant trout
#

yeah i opened it in debugger on firefox

#

im gonna look through it

topaz widget
#

Okay, if you want to use the site as reference, make sure to write down the url. I'm going to delete the messages that have the name.

distant trout
#

ok done, bookmarked it. thank you πŸ‘

topaz widget
#

Cool.

swift sky
#

i have no idea why I'm getting a you need to log in message

#

there seems to be a session active

#

so idk

#
sessionLogIn = []


# def login required decorator
def login_required(f):
    @wraps(f)
    def wrap(*args, **kwargs):
        if True in sessionLogIn:
            return f(*args, **kwargs)
        else:
            flash("You need to log in first!")
            return redirect(url_for("login"))

    return wrap


def routes(app: Flask):
    # login page and location logic
    @app.route("/login", methods=["GET", "POST"])
    def login():
        error = None
        if request.method == "POST":
            if (
                request.form["username"] != "admin"
                or request.form["password"] != "admin"
            ):
                error = "Invalid Credentials. Please try again."
            else:
                sessionLogIn.append(True)
                session["logged in"] = True
                flash("You were just logged in!")
                return redirect(url_for("staffdashboard"))
        return render_template("login.xhtml", error=error)
topaz widget
#

I only know very little about gunicorn.

#

Is this a Flask website?

swift sky
#

it's ok im venting hoping someone might comes along

#

yes it's flask

topaz widget
#

Hm, yeah, don't really know much about Flask either.

swift sky
#

this works when i run it locally

#

but when it runs through a gunicorn instance it doesnt seem to allow me to log in

topaz widget
#

Yeah, I haven't a clue. Sorry.

vestal hound
#

why are you using a local var @swift sky

swift sky
#

because i suck

#

but do you think that's why?

vestal hound
#

I'm going to hazard a guess that it's because of that

swift sky
#

yeah

#

that's probably why it persists when running locally

#

but with a gunicorn instance it probably wouldn't because of the way it servers it O.o

topaz widget
#

Have you ever used apache @swift sky ?

swift sky
#

no

topaz widget
#

It's a more popular server than gunicorn, I know that.

swift sky
#

im using nginx

#

and gunicorn

frozen spear
#

hmm

topaz widget
#

oh okay

swift sky
#

πŸ˜„

topaz widget
#

Maybe gunicorn is working under the hood with modwsgi then, idk

swift sky
#

it is

topaz widget
#

Yeah, as I said, I know very little about it.

#

I know how to get a Django site running with modwsgi and Apache, though.

swift sky
#

@vestal hound just to clarify you were talking about the sessionLogIn = [] variable?

vestal hound
#

yes

#

also snake case please

swift sky
#

xD

#

scared of snakes

candid jackal
#

Has anyone worked with PYJWT?

#

token_decoded = jwt.decode(token, 'secret', verify=True, algorithms=['HS256']) This is not working for me. ERROR : Not enough segments

frozen spear
#

I think you have to define related_name= into your Foreign key definition
@maiden kraken alrighty

opal fulcrum
#

iam having issues learning django can someone recommend me a tutorial or a way to learn it ?

topaz widget
#

@opal fulcrum Corey Schafer has some good tuts on Youtube.

vestal hound
#

is it the first thing you're trying to learn?

opal fulcrum
#

no i know about python basics - some object oriented stuff and kivy

versed python
#

I think they meant web development

topaz widget
#

Corey Schafer tutorials Youtube

opal fulcrum
#

i am having issues when things goes to .... Templates codes ... i am so confuses about it

#

@topaz widget is he good

topaz widget
#

yes

versed python
#

yeah very good

topaz widget
#

What kind of site are you trying to make?

candid jackal
#

token_decoded = jwt.decode(token, 'secret', verify=True, algorithms=['HS256']) This is not working for me. ERROR : Not enough segments
Anything on this error guys?

opal fulcrum
#

i was following a guy called Rafi Qazi .. but his tutorial is really hard

#

idk if i am dumb or he is bad

topaz widget
#

What kind of site @opal fulcrum ?

versed python
#

you'll probably also understand nothing the first time following corey schafer, but after a while you will get it

opal fulcrum
#

hmmm mmm tbh i don't really want to build specific site i just want to get good at it .. then idk study HTML - CSS for front end so i can get a job with it

vestal hound
#

IMO Django is not something one should start with

versed python
#

html css ain't enough to get you a job

candid jackal
#

@opal fulcrum Make something easy to learn.

vestal hound
#

level of abstraction is a bit too high

candid jackal
#

I'm trying to learn authentication

topaz widget
#

Okay, well, what IgnisDa said is probably true, but Corey goes step-by-step, so you can definitely get a site running using his tutorials.

vestal hound
#

@candid jackal your token is not valid.

candid jackal
#

How come?

vestal hound
#

well

#

I have no idea

candid jackal
#

I tried it

vestal hound
#

that would depend on how you're getting it

candid jackal
#

I'm getting it from another package

#

and it doesn't have decode

vestal hound
#

but basically

#

a JWT has three segments, right

versed python
#

@candid jackal what's the value of token?

candid jackal
#

its the token itself

vestal hound
#

separated by .s

opal fulcrum
#

but ... why are you saying i won't be able to get a job with it .. what skills i need to be able to get a job with django ?

candid jackal
versed python
#

does it have 3 segments like @vestal hound said?

vestal hound
#

okay

#

just do this

#

assert len(token.split('.')) == 3

topaz widget
#

@opal fulcrum Companies want to see JS and front-end frameworks.

candid jackal
#

why would i wanna split it?

versed python
#

@opal fulcrum html css is something every one knows and can learn in a few weeks. Doesn't prove anything

vestal hound
#

seeing camel case and snake case in the same line makes me feel ill

#

why would i wanna split it?
@candid jackal because the segments in a JWT are separated by .s.

topaz widget
#

@versed python Not entirely true.

candid jackal
#

@vestal hound It's just for me to learn, i know i should follow pep8

vestal hound
#

so if you split it and the length isn't 3

versed python
#

yeah Javascript sucks

#

all my homies hate Javascript

vestal hound
#

that means your token has the wrong number of segments.

opal fulcrum
#

can you give me a plan what i need to learn to be able to find a job with it ?

topaz widget
#

@versed python HTML and CSS can take a while to master.

opal fulcrum
#

in order

versed python
#

@versed python Not entirely true.
@topaz widget mostly true, though

vestal hound
versed python
#

yeah

topaz widget
#

There is quite a lot of depth to CSS

vestal hound
#

you can learn basic HTML and CSS, yes

candid jackal
vestal hound
#

in a few weeks

#

you can learn basic almost anything in a few weeks

#

or even less

#

but I wouldn't say that qualifies you as "knowing" CSS @ a level that would make you employable

topaz widget
#

Getting good with CSS takes longer than a few weeks, though.

vestal hound
#

except maybe as an intern or something.

topaz widget
#

Knowing all the combinators, etc... can take a while.

versed python
#

yeah especially since most frameworks can do what you spend hours doing using css files with a few minutes

#

css is essential knowledge, but it's not enough knowledge

topaz widget
#

Also, knowing how to structure your HTML to properly apply CSS is part of learning both HTML and CSS and can take some time.

vestal hound
#

that said, I also do think there is value in learning a framework first

opal fulcrum
#

hmmm this is getting complex to me ... cause sometimes when iam learning django they put some HTML codes in it which gets me confused ... should i learn HTML first before jumping into django ?

candid jackal
#

but there is no decrypt.

vestal hound
#

hmmm this is getting complex to me ... cause sometimes when iam learning django they put some HTML codes in it which gets me confused ... should i learn HTML first before jumping into django ?
@opal fulcrum it depends on what you want to use Django for.

#

you can build a website with only Django (in the sense that it can fill templates to create HTML pages which are served)

candid jackal
#

should i just use pyjwt only

vestal hound
#

beats me, I have never used JWT

#

everything I have told you I got from a quick Google search

#

but anyway