#web-development

2 messages ยท Page 172 of 1

rocky ferry
#

i have imported the module but still it says

#

module error epic thing is my app name is playground

#

so it is adding that as module not found error

inland oak
inland oak
#

line number 6

rocky ferry
#

i used it too

sick glacier
#

lemon_thinking Thanks it worked but in documentation is mentioned as one of the way to enable token authentication REST_FRAMEWORK = {}

inland oak
#

why this thing is superrior to standard debug?

rocky ferry
#

i don't know

inland oak
#

I thought there is no better debug than unit testing

rocky ferry
#

44:47

#

i'm watching his tutorial

inland oak
#

erm, ok. probably something I don't know then

sick glacier
#

@inland oak :in settings disable auth
REST_FRAMEWORK = {} disabling works but what if i want to test it using the authentication token enabled

inland oak
#

which uses django rest framework test api client

#

or you could even test with request library, if test api client will be bypassing authentication

#

testing in postman is highly unefficient, unproductive and slow method ๐Ÿ˜‰

#

it has its uses from time to time though

cursive vector
#

Ok I am working with django-admin and have a situation where I want to create Model A and Model B (which has a OtO relationship with Model A) using the same django-admin page. So I have a ModelAdmin for ModelA that has an inline for ModelB. But when I hit save Nothing is created for ModelB...

#

I dug around a bit, and it looks like I might have to overwrite save_formset but I am having trouble getting the data from the inline form from formset so I can actually use it.

inland copper
#

where can i learn django channels?

naive blaze
#

Hello guys, i kinda need a little help, i'm working on a tool with flask, and i splited my webpage into 2:
-nav bar and form
-datatable and search bar which i load via a javascript function
The probleme is i dont know how to send datafrom the form to flask without reloading the page, then i load the datatable ?
Or how can i also get data into my js script from the form before the page reload or redirect ?

warped heart
#

read the stream encode it to base64 then in the html use

<img src="data:image/png;base64, {{ encoded_image }}">
naive blaze
thorn igloo
#

yes

naive blaze
#

Thanks i'll check it out !

dapper lichen
#

@naive blaze something like this:

<form id="the_form">....</form>
<button onclick="update_view()">Update View</button>;``` ```js
function update_view(e){
  e.preventDefault();
  const form = new FormData(document.getElementById("the_form"));
  fetch("/update_view", { method: "POST", body: form })
    .then((response) => response.json())
    .then((data) => update_the_page_with(data));
}``` ```py
from flask import jsonify
@app.route("/update_view", methods=["POST"])
def update_view():
    new_data = do_something_with(request.form['param1'])
    return jsonify(new_data)```
naive blaze
#

@dapper lichen in your case the update_view() does not reload the page ?

#

or it will just show an empty page with the new data ?

dapper lichen
#

no, it just returns some json data (assuming new_data is a dict)

#

you update only what you want with some "update_the_page_with" JS function

naive blaze
#

Thats great ! i think i start getting it, i'm a need to try

#

Thank you !!

dapper lichen
#

@naive blaze updated above

naive blaze
#

The page i need to update the data in is loaded via javascript

#
function load_home() {
     document.getElementById("table_div").innerHTML='<object type="text/html" data="compact-table.html" style="width: 1810px;height: 1500px;" ></object>';
}```
dapper lichen
#

fair enoguh

sick glacier
#

Getting the following error
Access to XMLHttpRequest at 'http://127.0.0.1:8000/v1/Location/' from origin 'http://localhost:4200/' has been blocked by CORS policy: Request header field access-control-allow-methods is not allowed by Access-Control-Allow-Headers in preflight response.

#

Added the cors in django

opaque rivet
#

@sick glacier what have you done to solve this error?

sick glacier
#

CORS_ORIGIN_ALLOW_ALL = True i have added this

#

@opaque rivet : And also added this to middlewar

#

e

#

'corsheaders.middleware.CorsMiddleware',

opaque rivet
#

@sick glacier CORS_ALLOW_ALL_ORIGINS = True

#

Follow official docs, your variable isn't there at all, how'd you come across that?

ripe hazel
#

could somebody who is a little advanced in django help me out with a problem pls

native tide
#

uhh im not sure whats wrong here

#

it used to work but then i left it for a while and when i come back it doesnt work

#

the databases do exist and are registered

#

the database itself works it just keeps giving me the same warning

granite breach
#

Is this the right channel for noob setup questions for django?

native tide
#

if you are a begginer i suggest you watch a tutorial

#

tech with tim made a great one its 3 hours long but worth watching

granite breach
#

I did. Can't find what I did wrong

native tide
#

django is quite complex

granite breach
#

Im stuck on creating views

#

Lol

#

Well the tutorial I used was the Django docs. Is there a better tutorial?

ripe dirge
#

I am new to node .I have done some small projects in node but my company is using mysql as db.
Can anyone advice me any good project or resouce where I can learn about how to visualise and structure data in sql db and how sql db works like association and SP.we use sequelize ORM.
Need guidance.
Thanq so much.

ripe hazel
#

when I started it helped

#

you can find him on youtube as well

warped heart
#

Flask Code

import base64

@app.route('/', methods=['GET', 'POSTT'])
def index():
    if request.method == 'POST':
        files = ...
        transferable_files = map(lambda file: base64.b64encode(file.read()).decode(), files)
        return render_template('index.html', files=transferable_files)

HTML Code

{% for file in files %}
    <img src="data:image/png;base64, {{ file }}">
{% endfor %}
#

just a rough markup on how i did it

#

make sure your files are open with rb mode

arctic wedge
#

Anyone use Django on windows? I'm stuck on this django-admin not recognized command issue?

wooden ruin
arctic wedge
#

yeah

wooden ruin
arctic wedge
#

Yeah im not sure exactly what that means i went there but the stuff he says is already there

arctic wedge
#

yeah nothing

wooden ruin
#

check C:\Python39\Scripts

arctic wedge
#

its not there? Im so confused lol

calm plume
#

And make sure you're not in a venv

arctic wedge
#

ok

#

Ok seems to work now. That was really odd

#

Thank you guys

muted iris
#

ummm... i need help with some code, but it is in javascript. does anyone know the javascript discord server?

summer cairn
#

i have a webapp that uses selenium to open a web browser for users to authenticate a 3rd party app. everything works great locally, but obviously when i push to my Linode server (which is headless), the web browser doesn't open. does anyone have any pointers on how to properly implement this on a web server?

pallid spade
#

If have a api and a app folder where do I put the git repo locally?

jagged pollen
#

u can download github desktop

jagged pollen
pallid spade
#

hmm never used it

gleaming frigate
#

Does anyone know how to make a token without accessing a route
For example in my application of two types of user. Client user and admin user. both the client token and the ADM token are able to access all end-points
How do I make the client's token not be authorized in the user's route

inland oak
#

JWT tokens allow storing dicts jsons in it

#
{
  "admin": true
}
#

just store in it

#

and make a decorator that extracts this information and forbids non admins

@admin_only
gleaming frigate
#

I'm using Flask
I'm doing it like this: create_access_token(identity=cli.cli_id,fresh=False, expires_delta=timedelta(days=90))

#

@inland oak

inland oak
strong palm
#

Hi @humble vortex I just found your message I noticed that sergeyklay has made his own release, please let me know when you see this message. I'd like to prevent having too many "same packages". One of the options I can think of right now is to move your project under https://jazzband.co/

tough lintel
#

I'm trying to follow a Django tutorial that uses 2.0.7 (FreeCodeCamp/CFE) and I want to use the static files I already have. html, css and JS.

When following this tutorial https://www.youtube.com/watch?v=RhJIMUMJ_Do I can't seem to make it work.

Hey ninjas, in this django tutorial I'll explain how we can set up our django project to use static files such as images, css and JavaScript files.

DONATE :) - https://www.paypal.me/thenetninja

----- COURSE LINKS:

โ–ถ Play video
#

home.html
<link rel="stylesheet" href="/static/css/main_tailwindPost.css">

urls .py
urlpatterns += staticfiles_urlpatterns()

settings.py
STATIC_URL = '/public/'

NetNinja tut

STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'public'),
)

#

Chrome Console:
main_tailwindPost.css:1 Failed to load resource: the server responded with a status of 404 (Not Found)

But in Sources I can clearly see the correct file tree, static/css/ and .css files but they are blank.

#

I copied this text from another discord. Thought the formatting would persist. Can't seam to add the ticks on mobile easily. Sorry about that

cold estuary
#

have any one used python flask as backend for their javascript project?

proper hound
#

guys anyone have experience with AIORTC?

#

it has very less resources on the internet

#

i have a couple of questions to ask

versed python
#

I recommend changing STATICFILES_DIRS to "static" tho

tough lintel
tough lintel
tough lintel
#

Yeah I've read the docs for v2

#

They are much much easier to understand than python docs, but still not easy.

versed python
tough lintel
#

Yes as I mentioned at the top.

#

Am following a tutorial on YouTube

versed python
tough lintel
#

Yes

versed python
#

if youre learning django might as well learn a version thats gonna work

tough lintel
#

I prefer following a good tutorial.

Can't imagine everything about django changed from v2 to v3

#

Did run into a sqlite3 backwards compatability issue on my first attempt though. But managed to find a working solution on Stackoverflow

#

Have only had like two hours of sleep. Daughter kept having nightmares, so I might respond accordingly

versed python
#

django 2 has security vulnerabilities

ebon moat
#

Hi

#

I need Django Tutorial

ebon lava
#

how to upload images on server (django application ) which is hosted on heroku ?

dusk portal
#

Any knows how to make my website online from local host (Deployment)
Fast plz i have only some minutes

whole swallow
#

hi! anyone from front end here?

quiet ridge
whole swallow
#

thanks but I don't need any help just need to know if any

quiet ridge
#

oh alright

mellow prawn
#

yo

#

does any1 know how to us HTMl

calm plume
#

And I'm sure many others do too

mellow prawn
#

hmmm

gleaming frigate
inland oak
#

just store into identity more than just id, a whole dictionary of additional information

{
  "id": id,
  "admin": True
}
rotund minnow
#

In flask virtual environment, I am getting below error: from markupsafe import escape
ImportError: cannot import name 'escape'

gleaming frigate
rotund minnow
obtuse trout
#

Hello, I want to create user-specific bootstrap offcanvas in django, does anyone know how I can go about that?

inland oak
dense slate
#

@rotund minnow You're trying to import something that doesn't exist or is maybe misspelled?

obtuse trout
inland oak
#

no idea what you have there to help you more.

undone spruce
#

is it possible to run python scripts & display charts in wordpress? For example, I've got a short 18 liner that uses pymssql and matplotlib.pyplot and would like to display it on my wordpress page.

inland oak
undone spruce
inland oak
#

if yes, then just make ajax call to python api

#

for example...

#

hmm...

inland oak
#

to rqeuest display charts?

#

well, probably yes, nvm.

undone spruce
inland oak
#

make in python API web framework exposed API end point

#

which you can request with GET or POST request (whatever you need, the difference is little)

#

you will call it with javascript, while inputing necessary variables

undone spruce
#

i'd need to set-up a python API endpoint first

inland oak
#

it will activate python script to call your sql for server query

#

and as result, saving it into image

#

and give link to it in API answer ;b

undone spruce
#

sheesh that is way over my head, lol

inland oak
#

that's actually quite simple. it just sounds hard.

#

mm

#

you need some simple framework to get started like Flask

undone spruce
#

I have pycharm that I use for python dev

inland oak
#

any library to make sql server request, in raw SQL or ORM (whatever you prefer)

undone spruce
#

I need to set-up a python server, first, right?

rotund minnow
warped heart
#

np

umbral girder
#

hi guys

#

Someone has a Django group?

umbral girder
sly adder
#

I'm going through a secondary Django tutorial and I've been using Django to create a new app so I can follow a tutorial where the author is creating drop-down menus for a site.

However, I'm having trouble with a simple import statement

#

This is my directory structure

#

I created an app called testing within the project dropsite

#

within urls.py I'm trying to import the contents of dropsite.testing.views but I get errors when I try the python manage.py migrate command

#

My error is ModuleNotFoundError: No module named 'dropsite.testing'

#

This is how I'm trying to import my views, but I've clearly bungled it

#

This may not be web-development specific, but i'm using Django to create the app and I'm new to it. How would you guys recommend I fix my import command to get the classes within views

opaque rivet
sly adder
#

That was another issue

#

I have since figured it out, thankfully ๐Ÿ˜„

#

Sorry I didn't post here

#

I'm very new to web including Django and HTML

opaque rivet
#

nice, keep it up ๐Ÿ™‚

sly adder
#

My goal in the near-term (this week) is to create a very very basic site that I can run locally

#

all it will have is drop-down menus with selections, and then a button that says "run" so I can do some work behind the scenes and then display a graph

opaque rivet
#

sounds good

sly adder
#

But I also know zero HTML

#

Is there a resource that allows you to modularly build HTML?

#

For instance just stacking input forms or am I thinking down the wrong path with regard to creating the Django app?

opaque rivet
#

well, HTML modular-ly builds your page. I'd recommend you just learn it, it's quite simple and compared to python doesn't take long to learn.

sly adder
#

Gotcha

#

Aside from "Google: how to create input forms with HTML" is there a decent place to start?

#

I guess I also need to look more into Django forms to understand how they fit in with everything

#

Like if I can splice Django forms with other elements

opaque rivet
#

its different for everyone, but I prefer courses where you do projects and learn by doing... I recommend codecademy's html course and iirc it's free

sly adder
#

That sounds good

opaque rivet
#

and yeah you can also use django forms, it's just a way to produce HTML forms with python

sly adder
#

Ah

#

That would probably be easier to pick up

#

I was just looking at this example form


from django import forms
from .models import Person, City


class PersonForm(forms.ModelForm):
    class Meta:
        model = Person
        fields = ('name', 'birthdate', 'country', 'city')

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['city'].queryset = City.objects.none()

        if 'country' in self.data:
            try:
                country_id = int(self.data.get('country'))
                self.fields['city'].queryset = City.objects.filter(country_id=country_id).order_by('name')

            except (ValueError, TypeError):
                pass  # invalid input from the client; ignore and fallback to empty City queryset

        elif self.instance.pk:
            self.fields['city'].queryset = self.instance.country.city_set.order_by('name')

#

It seems relatively intuitive, but it has some database terminology that Django utilizes which is a little new to me

tough lintel
#

@sly adder netninja always has a great tutorial

sly adder
#

Awesome, I'll check it out

#

I think I kind of missed the point of Django forms though

tough lintel
#

Doesn't use any css framework IIRC

sly adder
#

I think I can do most of what I want with Django forms then I'll have to figure out a way to generate and display a graph based on data

tough lintel
#

I'm new to django too.

sly adder
#

Seems awesome tbh

#

Just a big learning curve

glossy arrow
#

yeah, Django has somewhat of a learning curve

sly adder
#

Well I've used sqlite databases in projects before

#

But I've done everything so manually that this just sort of blows my mind

#

@glossy arrow how long have you been using Django?

glossy arrow
#

I haven't done much Django really, I read through the tutorial, and I did a few stuff with it, but I prefer frameworks like FastAPI or Starlette

sly adder
#

Ah gotcha

heady quail
#

Anyone successfully deployed a JustPy web app? My impression has been that creating the app is easy but deploying it not so much.

native tide
#

Hi,

#

flask is not showing post request data

#
@app.route("/register", methods=["POST"])
def web_register():
    if request.method == "POST":
        print(request.data.decode('UTF-8')) 
        return "OK"```
#

prints nothing

balmy pilot
#
File ".\core\users\login.py", line 22, in login_user
    db_user = crud.get_Login(
  File ".\api\crud.py", line 39, in get_Login
    db_user.password.encode('utf-8'))
AttributeError: 'bytes' object has no attribute 'encode'

I got this error relate to Base64 on my crud

This is my core\users\login.py :

@router.post("/login")
def login_user(user: schemas.UserLogin, db: Session = Depends(get_db)):
    db_user = crud.get_Login(
        db, username=user.username, password=user.password)
    if db_user == False:
        raise HTTPException(status_code=400, detail="Wrong username/password")
    return {"message": "User found"}

and api\crud.py :

def get_Login(db: Session, username: str, password: str):
    db_user = db.query(models.UserInfo).filter(
        models.UserInfo.username == username).first()
    print(username, password)
    pwd = bcrypt.checkpw(password.encode('utf-8'),
                         db_user.password.encode('utf-8'))
    return pwd

I tried this solution and nothing work
https://stackoverflow.com/questions/36228117/attributeerror-bytes-object-has-no-attribute-encode-base64-encode-a-pdf-fi

vestal hound
vestal hound
native tide
#

`127.0.0.1 - - [14/Jul/2021 14:11:11] "POST /tasks HTTP/1.1" 500 -

127.0.0.1 - - [14/Jul/2021 14:11:11] "POST /register HTTP/1.1" 200 -`

sly adder
#

For displaying graphical data?

vestal hound
native tide
#

showing post request but not the data

sly adder
#

Good to know

vestal hound
#

I mean

#

it's doable with HTML

#

so if you want it to be static

#

that's fine too

sly adder
#

I still have other issues pre-graphical data display

#

Like right now I can't get my model choices to populate in a drop down menu

#

๐Ÿ˜ข

vestal hound
#

and verify that there actually is data in the body

vestal hound
sly adder
#

Yeah

vestal hound
#

are you using ModelForm

sly adder
#

I have all the choices defined in models

#

Yes

#

But quite honestly I don't understand the structure of ModelForm

vestal hound
#

you want a ChoiceField

sly adder
#

I'm trying to modify a tutorial for dynamic drop-down

#

Oh not forms.Select() ?

vestal hound
#

well

#

it depends

#

what are you trying to do exactly?

sly adder
#

Honestly just input some very basic personal data

#

Right now it's simply Name / Age / Race

#

Building off this HR input form example

vestal hound
#

then Select should be fine

sly adder
#

So I will say that I don't understand the structure and I'm not very knowledgeable on super().__init__() calls like this example used

#

So I tried something as simple as this

from django import forms
from .models import Person, Race, Age

class PersonForm(forms.ModelForm):
    model = Person
    fields = ('name', 'race', 'age')
    name = forms.CharField(max_length=100)
    race = forms.Select(choices=Age.AGE_RANGES)
    age = forms.ChoiceField(choices=Race.RACE_CHOICES)

#

Sorry, one moment.

#

This was my forms definition, but it didn't create anything because it says I have no model class defined

#

Then I converted it to this structure, though I can't say I know 100% what the def __init__() and accompanying super() call are accomplishing here.

from django import forms
from .models import Person, Race, Age


class PersonForm(forms.ModelForm):

    class Meta:
        model = Person
        fields = ('name', 'race', 'age')
        name = forms.CharField(max_length=100)
        race = forms.Select(choices=Age.AGE_RANGES)
        age = forms.Select(choices=Race.RACE_CHOICES)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
sly adder
#

nope, but this is my first foray into anything remotely web

vestal hound
#

what do you do normally

sly adder
#

Desktop engineering / numerical analysis automation

native tide
#

i made the program and using httpsendrequestW

opaque rivet
native tide
#

i printed the buffer before sending andit sends

vestal hound
#
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

this does nothing

opaque rivet
sly adder
#

Sorry I thought I had that commented out

#

That was from the example

#

from django import forms
from .models import Person, Race, Age


class PersonForm(forms.ModelForm):

    class Meta:
        model = Person
        fields = ('name', 'race', 'age')
        name = forms.CharField(max_length=100)
        race = forms.Select(choices=Age.AGE_RANGES)
        age = forms.Select(choices=Race.RACE_CHOICES)

#

This is what I had

#

I selected too much

#

And yes I deal with defining classes, class inheritance, and utilizing class structures to create separate modules, etc.

I'm certainly not an expert, most of my class definitions and program structures are probably relatively simple.

#

So this is what I get with this selected,

#

But my choices aren't being populated

#

It's just the initial placeholder value of "--------"

opaque rivet
sly adder
#

Sure

#

I'll just show you my models definitions

#

from django.db import models


# class for defining the race model as an input form with beginning set of limited choices
class Race(models.Model):
    RACE_CHOICES = (
        ("B", "Black"),
        ("H", "Hispanic"),
        ("W", "White"),
        ("O", "Other")
    )
    name = models.CharField(max_length=20)
    race = models.CharField(max_length=1, choices=RACE_CHOICES)

    def __str__(self):
        return self.name


# class for defining the age model as an input form with comprehensive age list
class Age(models.Model):
    AGE_RANGES = (
        ("1", 'Less than 21'),
        ("2", '21, 25'),
        ("3", '26-30'),
        ("4", '31-35'),
        ("5", '36-40'),
        ("6", '41-50'),
        ("7", 'Greater than 50')
    )
    name = models.CharField(max_length=20)
    age_range = models.CharField(max_length=1, choices=AGE_RANGES)

    def __str__(self):
        return self.name


# Person class defining a model comprised of the other models for the database relationship using
# Foreign Keys for Age and Race
# --> This section will be expanded as new variables are progressively added.
class Person(models.Model):
    name = models.CharField(max_length=100)
    race = models.ForeignKey(Race, on_delete=models.SET_NULL, null=True)
    age = models.ForeignKey(Age, on_delete=models.SET_NULL, null=True)

    def __str__(self):
        return self.name
sly adder
#

I don't quite understand the queryset " A QuerySet of model objects from which the choices for the field are derived and which is used to validate the userโ€™s selection. Itโ€™s evaluated when the form is rendered.
"

#

Or is that just the choices?

opaque rivet
#

Oh actually might be the wrong field, queryset is just a list of your database entries. I don't think that's what you want

#

hmm, everything looks right to me

sly adder
#

Yeah I also don't understand why ChoiceField isn't applicable here

#

Do you need to see my views at all?

#

or the HTML templates ?

opaque rivet
#

ChoiceField is applicable

sly adder
#

Right

#

But it still doesn't change the output of the dropdown

#

Which must mean that something else is incorrect with how I've defined views or templates, right?

opaque rivet
#

hmm, the only thing I'd say is that the fields you specify shouldn't be in the Meta class, not sure if that makes a difference though... Apart from that I don't know what could be the issue, I also don't know how django forms represents foreignkeys.

sly adder
#

Should it matter if they are foreignkeys though?

#

I can try to move my field definition elsewhere

opaque rivet
#

I may be wrong but yeah I think it would be an issue... the foreignkey just represents a relationship to another table, it doesn't really give any information about which column you want to mimic as a form field

#

maybe it would be easier scrapping the ModelForm and just building a normal form.

sly adder
#

This was the functional form in the example


from django import forms
from .models import Person, City

class PersonForm(forms.ModelForm):
    class Meta:
        model = Person
        fields = ('name', 'birthdate', 'country', 'city')

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['city'].queryset = City.objects.none()

        if 'country' in self.data:
            try:
                country_id = int(self.data.get('country'))
                self.fields['city'].queryset = City.objects.filter(country_id=country_id).order_by('name')
            except (ValueError, TypeError):
                pass  # invalid input from the client; ignore and fallback to empty City queryset
        elif self.instance.pk:
            self.fields['city'].queryset = self.instance.country.city_set.order_by('name')

Of course this accomplishes more on the city and country fields

#

And this gave functional dropdowns

#

But I've tried to modify the variables that I'm attempting to collect from the user and progressively redefine the models, views, forms, etc.

opaque rivet
#

do you have the source code for the Person model?

sly adder
#

The original?

#

Or mine?

opaque rivet
#

the one from that example

sly adder
#
class Person(models.Model):
    name = models.CharField(max_length=100)
    birthdate = models.DateField(null=True, blank=True)
    country = models.ForeignKey(Country, on_delete=models.SET_NULL, null=True)
    city = models.ForeignKey(City, on_delete=models.SET_NULL, null=True)

    def __str__(self):
        return self.name
#

So their dropdown selections were city and country which were both ForeignKey's

opaque rivet
#

Ok, so turns out Foreignkeys are represented by django.forms.ModelChoiceField so you can give them a queryset (a list of database entries) for the user to pick

#

but in your case you just want the user to pick a choice, right?

sly adder
#

Yes

#

I just wanted all selections to be available

#

And to select. I know it's dumb that I choice a more involved drop-down menu Django example and tried to manipulate it to suit my purposes

opaque rivet
#

if you're using a ModelForm you can also hop into the python terminal, initialize it and repr(form_object) to see its fields

#

Ok, so have you saved any db entries into your other models?

sly adder
#

Yes

#

two

#

Just have dummy names right now because after migrations I have not been able to get my fields displayed correctly and I stripped all of the existing fields that the example utilized

opaque rivet
#

hmm, so I don't think the ModelForm will suit you then. Person has Foreignkey fields which are django.forms.ModelChoiceField and you'll have to pass a queryset attribute to give it choices to pick from (but these are queryset - the user picks entries in the db which isn't your use-case)

#

Honestly I would just build a normal form with choicefields

sly adder
#

Ok

opaque rivet
#

nice and simple

sly adder
#

So scrap ModelForm all-together?

opaque rivet
#

yeah, I think the form should be simple enough to just use forms.Form

#

with a few choicefields

sly adder
#

Getting some errors after I redefined my forms to this

#
from django import forms
from .models import Person, Race, Age


class PersonForm(forms.Form):
    model = Person
    fields = ('name', 'race', 'age')
    name = forms.CharField(max_length=100)
    race = forms.ChoiceField(choices=Age.AGE_RANGES)
    age = forms.ChoiceField(choices=Race.RACE_CHOICES)

#

return form_class(**self.get_form_kwargs()) TypeError: __init__() got an unexpected keyword argument 'instance'

#

now I think it's my views

opaque rivet
#

yeah forms.Form doesn't take model or fields

#

you just define the fields

sly adder
#
from django.views.generic import ListView, CreateView, UpdateView
from django.urls import reverse_lazy

from .models import Person
from .forms import PersonForm


class PersonListView(ListView):
    model = Person
    context_object_name = 'people'


class PersonCreateView(CreateView):
    model = Person
    form_class = PersonForm
    success_url = reverse_lazy('person_changelist')


class PersonUpdateView(UpdateView):
    model = Person
    form_class = PersonForm
    success_url = reverse_lazy('person_changelist')

#

So you're saying remove model and form_class in each view class here?

opaque rivet
#

just remove:

model = Person
fields = ('name', 'race', 'age')

from the form

sly adder
#

oh nevermind

#

yeah

native tide
#

Hi,

#

it is working

#

but seems like it is kind of race condition

#
@app.route("/register", methods=["POST"])
def web_register_beacon():
    if request.method == "POST":
        print(request.data.decode('UTF-8')) 
        return "REGOK"

@app.route("/tasks", methods=["POST"])
def web_task_beacon():
    print(request.data.decode('UTF-8'))
    return "STL dir"```
sly adder
native tide
#

the program send data to register and receive response and then quickly send to /tasks

opaque rivet
native tide
#

but when i remove print(request.data.decode('UTF-8')) in web_task_beacon()

the first function doesn't print anything

sly adder
native tide
#

but when i dont remove it is printing perfectly

#

why so?

sly adder
native tide
#

i removed the print from second function and first function is not printing anyting, same happen with second function

#

if i remove print from first function, 2nd function doesn't print anything

#

because it is single-threaded?

#

it is printing when i add this line: jdata = request.get_json(force = True)

gleaming frigate
#

good evening

Someone help me. I recorded image in postgresql, in binary format. But I don't know how to return the user to the image format

versed python
#

Wdym "recorded image in postgresql"?

grim elk
#

Does anyone know what is a good way to host a flask server? I was interested in hostinger shared hosting, but their shared hosting doesnt support python. Does anyone know if their cloud hosting (https://www.hostinger.com/cloud-hosting) does? Or should I use something like digital ocean?

#

Im fine with using vps' I just want something powerful and scalable, with a nice UI (preferably)

proper hinge
#

I recently deployed a Flask app using AWS App Runner. It's a pretty stripped down version, so it's easier to use. It can deploy a container or create one for you from a GitHub repository. You can manage it from the AWS website. Probably also works through CLI but I never bothered setting that up.

A similar service would be Google Cloud Run. These work well if you only have one app you need to deploy and you don't need a lot of detailed configuration.

cerulean badge
#

a silly question but would you prefer mdbootstrap templates or from colorlib?
if you don't want to spend money.

grim elk
grim elk
#

What does CLI mean

#

Sorry like I said im new to web development

#

I know how flask and WSGI works but other then that I don't know much to do with deployment

proper hinge
#

CLI = command-line interface i.e. a tool you interact with through your terminal/command prompt as opposed to a GUI (graphical user interface, such as the AWS website)

#

Yes, AWS App Runner is managed. You just give it a container and it takes care of pretty much everything else. It can automatically deploy for you when your code changes. It performs health checks. It can automatically scale up the number of instances running. It load balances for you. There's probably more stuff I am missing.

#

If you didn't know, by container I mean like a Docker container.

#

And if you're daunted by Docker containers, they have an alternative where you just give them a GitHub repository and it will create a container for you.

grim elk
proper hinge
#

It also gives you a domain (though not a pretty one)

#

You can of course add your own domain if you have one

grim elk
proper hinge
#

I know Google Cloud Run is a similar service, so look into that too. Compare pricing, etc.

grim elk
#

Yeah

#

Thanks

proper hinge
#

I am not familiar with all the options out there. I'm sure there's a lot more competition.

grim elk
#

Google has pretty competitive pricing, but so does amazon so im sure its not a huge difference

cerulean badge
grim elk
#

Ah

#

Im not using a template?

fast charm
#

i cant delete from my django rest api, DELETE request give me response status 200 and the Cross-Origin Request Blocked error, but i already have it in my project, post and get works fine

proper hinge
grim elk
#

Im so sorry

#

Got confused

grim elk
#

Colorlib is good for wordpress

#

Thats sorta what it was made for

proper hinge
grim elk
proper hinge
grim elk
grim elk
#

But yeah those arent free

opal leaf
#

hi

#

I need help in django

surreal portal
#

Has anybody encountered issues with JWTs?

#

Auth-wise they work fine

#

With session it starts being a problem

#

I'm using Django Simple JWT to generate them

#

And NextJS + next-auth to store them

umbral girder
#

**{% for cat in category%} {% if cat.parent == None %} <li class="nav-item"> <a class="nav-link d-sm-inline-block" href="{% url 'category' cat.slug %}">{{cat.title}}</a> {% if cat.children.all %} <ul class="navbar-nav mr-auto"> {% for cat in cat.children.all %} <li class="nav-item"> <a class="nav-link d-sm-inline-block" href="{% url 'category' cat.slug %}">{{cat.title}}</a> </li> {% endfor %} </ul> {% endif %} </li> {% endif %} {% endfor %} **

tough lintel
# opal leaf ??

The title of link "Is anyone here good at Flask / Pygame / PyCharm?"

the text

There are two problems with this question:

This kind of question does not manage to pique anyone's interest, so you're less likely to get an answer overall. On the other hand, a question like "Is it possible to get PyCharm to automatically compile SCSS into CSS files" is much more likely to be interesting to someone. Sometimes, the best answers come from someone who does not already know the answer, but who finds the question interesting enough to go search for the answer on your behalf.
When you qualify your question by first asking if someone is good at something, you are filtering out potential answerers. Not only are people bad at judging their own skill at something, but the truth is that even someone who has zero experience with the framework you're having trouble with might still be of excellent help to you.
So instead of asking if someone is good at something, simply ask your question right away.

The point is that asking 1. Can I get help or Is someone good at X? is pointless. it takes time and attention. Like now I had to explain to you why you got the reply you got.

umbral girder
#

Hello everyone i have bug for show the children's category in page

tough lintel
surreal portal
#

#web-development message
Seems like there's a mismatch between the expiration date on the token on Django and the one I fixed on NextJS

#

Isn't there a way to communicate the expiration date in the response?

versed python
#

How are you generating the tokens?

surreal portal
#

Using Django Simple JWT. The original response is a JSON with the access and refresh tokens.

#
curl \
  -X POST \
  -H "Content-Type: application/json" \
  -d '{"username": "davidattenborough", "password": "boatymcboatface"}' \
  http://localhost:8000/api/token/

...
{
  "access":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX3BrIjoxLCJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiY29sZF9zdHVmZiI6IuKYgyIsImV4cCI6MTIzNDU2LCJqdGkiOiJmZDJmOWQ1ZTFhN2M0MmU4OTQ5MzVlMzYyYmNhOGJjYSJ9.NHlztMGER7UADHZJlxNG0WSi22a2KaYSfd1S-AuT7lU",
  "refresh":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX3BrIjoxLCJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImNvbGRfc3R1ZmYiOiLimIMiLCJleHAiOjIzNDU2NywianRpIjoiZGUxMmY0ZTY3MDY4NDI3ODg5ZjE1YWMyNzcwZGEwNTEifQ.aEoAYkSJjoWH1boshQAaTkf8G3yn0kapko6HFRt7Rh4"
}
hushed parrot
#

can someone guide me on how to get started with building web applications in python..? the only modules I know to use are tkinter and pyautogui as of now

versed python
surreal portal
versed python
#

It looks incorrect to me

#

Maybe there's some additional Django simple jwt setting to configure time

surreal portal
#

There's something in the settings yeah

surreal portal
#

Ok seems like it is inside the token

#

But how can I extract that from the JWT?

warped heart
#

decode and use json.loads ig

foggy bramble
#

Hello
Im getting this error while trying to dockerize my project:

Is the server running on host "localhost" (127.0.0.1) and accepting
app_1     |     TCP/IP connections on port 5432?
app_1     | could not connect to server: Cannot assign requested address
app_1     |     Is the server running on host "localhost" (::1) and accepting
app_1     |     TCP/IP connections on port 5432?
#
version: '3'
 
services:
  app:
    build:
      context: .
    ports:
      - "8000:8000"
    volumes:
      - .:/app
    command: >
      sh -c "python3 manage.py migrate &&
             python3 manage.py runserver"
 
    env_file:
      - ./.env
    depends_on:
      - db
 
  db:
    image: postgres:10-alpine
    env_file:
      - ./.env
    volumes: 
      - pgdata:/var/lib/postgresql/data
  redis:
    image: redis:alpine
  celery:
    restart: always
    build:
      context: .
    command: celery -A todo worker -l info
    volumes:
      - .:/app
    env_file:
      - ./.env
    depends_on:
      - db
      - redis
      - app
volumes:
  pgdata:

This is my docker-compose.yml file

#

and here is my database config in settings.py

DATABASES = {
    'default': {        
        'ENGINE': 'django.db.backends.postgresql',
        'HOST': config('DB_HOST'),
        'NAME': config('DB_NAME'),
        'USER': config('DB_USER'),
        'PASSWORD': config('DB_PASS'),
    }
}
#

any ideas?

dusk portal
#

i have learned django from docs then made some proj like todo app contact page app blog app auth system img system and some stuff what should i do now how can i go to more advanced in django, should i learn django rest framework or should i learn more stuff in django like google maps api system payment system

elder nebula
dusk portal
#

someone told me

#

making these payment api

#

google maps api

#

and stuff

#

is ez in django rest framework

elder nebula
#

If you want to, then do it

dusk portal
dusk portal
#

that if payment ==done

#

then only

#

add info to db

#

or then only pass to form

#

that would be trouble and hard

#

and maps seems insane lvl hard

elder nebula
#

There's a lot of tutorials for that on youtube, blogs, documentations ect

tepid jolt
#

hi , can any one help me with email sending from django issue ?

elder nebula
dusk portal
#

hmm

#

it will take time for sure but

#

i can do ig

elder nebula
#

I can't do most advanced stuff but I am getting there

dusk portal
#

ok so tell me who structure how and what i am making so ill write it somewhere and pin

dusk portal
elder nebula
#

Only way to learn is to get going and trying to make stuff

elder nebula
#

I think you are at the point where you should design and make your own app.

tepid jolt
#

i have project where email need to be send to activate account for new user and another email is for requests , all work on development , but when i uploaded to server contabo , the activation email is giving Reject for policy reason but the send request email is working normal

tepid jolt
#

no

elder nebula
#

What do you use

tepid jolt
#

eurodns

elder nebula
#

try different email provider and check if it works

dusk portal
#

u learned from

#

i have a doubt

tepid jolt
dusk portal
#

like for example i am making my own app and idk to add payement method how i learn it then

elder nebula
tepid jolt
#

and why is all working on development but not on the server ?

dusk portal
#

^^ plz tell u both pro ppls

elder nebula
dusk portal
#

ohh

elder nebula
tepid jolt
#

yes

heady quail
#

What would be a good way to deploy a large number of tiny independent single-page web apps? Essentially just single page forms doing API calls.

elder nebula
heady quail
tepid jolt
#

@elder nebula

ok, the email what im sending is :

{% autoescape off %}
Hi {{ user.username }},
Please click on the link to confirm your registration,

http://{{ domain }}{% url 'activate' uidb64=uid token=token %}

{% endautoescape %}

and thats all works on development but not on production server

but if i remove the link

{% autoescape off %}
Hi {{ user.username }},
Please click on the link to confirm your registration,


{% endautoescape %}

then all is good

#

hmmm , looks like i cant include the link to the emaill message

elder nebula
#

maybe remove just the {{ domain }} and then try

#

or did you find the cause?

elder nebula
#

they will guide you there I am sure

#

@tepid jolt Did you find out where the issue is?

tepid jolt
#

no, looks like i can send everything but no links

#

i cant send examlpe.com even

elder nebula
#

can you send the error message?

tepid jolt
#
Traceback (most recent call last):
  File "/home/mar24n/val/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "/home/mar24n/val/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/mar24n/val/users/views.py", line 63, in register
    email.send()
  File "/home/mar24n/val/venv/lib/python3.8/site-packages/django/core/mail/message.py", line 284, in send
    return self.get_connection(fail_silently).send_messages([self])
  File "/home/mar24n/val/venv/lib/python3.8/site-packages/django/core/mail/backends/smtp.py", line 109, in send_messages
    sent = self._send(message)
  File "/home/mar24n/val/venv/lib/python3.8/site-packages/django/core/mail/backends/smtp.py", line 125, in _send
    self.connection.sendmail(from_email, recipients, message.as_bytes(linesep='\r\n'))
  File "/usr/lib/python3.8/smtplib.py", line 901, in sendmail
    raise SMTPDataError(code, resp)
smtplib.SMTPDataError: (550, b'5.7.1  Reject for policy reason')
elder nebula
#

maybe try adding http://

#

@tepid jolt

tepid jolt
#

i did

#

this is what im getting from send()

                email.send() โ€ฆ
โ–ผ Local vars
Variable    Value
current_site    
<Site: hostnodes.online>
email    
<django.core.mail.message.EmailMessage object at 0x7f3c5cc3c340>
form    
<RegistrationForm bound=True, valid=True, fields=(username;email;password1;password2)>
mail_subject    
'Activate your Hosting account.'
message    
('\n'
 'Hi test21,\n'
 'Please click on the link to confirm your registration,\n'
 '\n'
 'https://testweb.net/users/activate/NTE/aptq61-82d00bd6adbdfbadc963bea3dbce21cd/\n'
 '\n'
 '\n')
request    
<WSGIRequest: POST '/users/register/'>
to_email    
'test@gmail.com'
user    
<User: test21>
username    
'test21'
elder nebula
#

Can you send any link?

#

Have you also allowed less secure apps on you email?

fleet narwhal
#

How do I host a django (with db, static as well as media uploads) project using the simplest way? How to access it using 0.0.0.0?? We just need to be able to run a project on our machine and show it to a friend and don't want to go through the hassle of a proper setup just yet

vast saffron
#

hello. does anyone know, how to get a full url_for in flask? i mean for example url_for('hello') returns /hello, but i want it to return https://domain.com/hello. is there a way to do this in flask?

inland oak
vast saffron
vast saffron
#

ok

#

thanks

tepid jolt
#

@elder nebula thank for your help

elder nebula
#

Np

boreal knot
#

How do I run a python function from js using cefpython? The documentation is very unclear

past lion
#

Hello guys i have a question about flask sqlalchemy

#

Is there any difference in the syntax of Flask Sqlalchemy when working with the different databases like Postgresql and Sqlite?

#

Or the syntax is always same

past lion
#

thank you bro

desert estuary
#
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
``` what does \ in the return do and mean
paper pier
desert estuary
#

oh okay uhh

upload_files=db.Column(db.LargeBinary())
``` which coluln type i should chose for uploading files in these extensions
UPLOAD_FOLDER='C:/Users/Hamza/Desktop/PFA/Flaskiproject/Filesuploaded'
app.config["UPLOAD_FOLDER"]=UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 10 * 1024 * 1024
#

app.config['UPLOAD_EXTENSIONS'] = {'jpg', 'png', 'pdf','txt'}

spark granite
#

is this c

bronze palm
#

hey does anyone have an django api project their working on? I'm curious to get into a community project of one if anyone is

leaden carbon
#

guys, can any one help me in a silly django problem

#

how can i pass a view as url inside a <a> tag at my tamplate?

#

like i have the :8000/home
that renders a simple html called home.html

#

but i want some buttons inside that redirect to my other pages

#

by now i need to type :8000/other_page to go there

#

thank

#

Nvm i just found i can pass the /directory of my html file inside the href lol

#

hope helps someone

pliant nymph
#

will helps both of us, my dude

bronze palm
#

usually when you load from an href you do something like <a href = "{% url 'appname.views.Function' %}"> and load from that

#

and make the functions inside your view for the different pages you want to load

half patrol
#

hey guys I need help in a flask-socketio issue

#

so basically my server is flask and my client is javascript, the connection is happening correctly, but messages sent from the server are not being recieved by the client

#

anybody can help with this issue?

rigid turret
#

Django devs, anyone have experience modeling a list of lists in a Django model?
I have a fixture with the key-value pair (precursor, list[ list[str] ], and ideally would like to have it modeled in a single field of its parent class.

cunning dagger
#

what is the best ide for python development?

cunning dagger
sharp basin
#

Hello does anybody here know how to pen test?

#

if so can you teach me?

azure kestrel
#

I've been asking about this question nonstop - is there anybody that can help me a bit with flask? I am running into an extremely frustrating yet simple issue

thorn igloo
half patrol
desert estuary
#

btw me myself im having an issue

@app.route('/user',methods=["GET","POST"])
def user():
   if "student" in session:
      current_student=Students.query.get(session['student'])
      form=Uploading()
      if form.validate_on_submit():
         file=request.files['uploadfile']
         if file.split('.')[1].lower() in {'.jpg', '.png', '.pdf','.txt'}:
            filename=secure_filename(file.filename)
            file.save(path.join(app.config['UPLOAD_FOLDER'], filename))
         else:
            flash(" we don't allow this file extension ")
         return redirect(url_for('user'))
   else:
      return redirect(url_for("login"))
   return render_template("User/Homepage.html",student=current_student,form=form)

but the file doesn't upload in the directory

UPLOAD_FOLDER='Flaskiproject/filesupload'
app.config["UPLOAD_FOLDER"]=UPLOAD_FOLDER
naive rock
#

Is there a way to tell if an API is REST or GraphQL?

#

And my understanding is that an API built on GrpahQL allows the user to pass in complexed queries?

wooden ruin
naive rock
#

We can query nested objects?

wooden ruin
#

yep

#

it works awesome with both sql and non-sql db's

naive rock
#

I havent used it yet, but definitely can see how it would be beneficial. Because I'm working with some api, that returns a lot more than what I need.

So is there a way to tell if something is REST or GraphQL?

sonic crater
#

Anyone use flask?

bright mason
#

Yeah

sonic crater
#

I'm not even sure how to ask my question so I'm just going to delete everything and try again haha sorry for bothering you. I may be back when I have a better idea

wooden ruin
wooden ruin
vestal hound
#

literally that

#

I mean

#

generally a /graphql endpoint is a sign

#

also, most APIs have some kind of documentation

#

e.g. OpenAPI spec

#

which you can consult

lime mist
#

is it possible to manually configure the value of sid from client side instead of it randomly getting generated with socket.io Python ?

vernal valve
#

ahh i am newto python from where i should start

grim elk
#

If ur new to python I would start by learning it using someone like TechwithTim's beginner guide

#

If ur new to python web development then I would start by watching a basic flask guide

half patrol
lime mist
#

can you share some code so I can see what's happening?

half patrol
#
clients=[]

@socketio.on('connect')
def handleclient():
    print("connection")
    clients.append(request.sid) ``` so I did this to store the client's sid when he connects
#

socketio.emit('output',{'data':"hello world".encode("utf-8")},to=clients[-1]) then this to send this client a message using the sid

#
var socket = io().connect('http://127.0.0.1:5000/stockcurve/{{ id | safe }}/50d/1d');
            
            
            socket.on('output', function bruhhha(msg) {
               console.log('Received message');
            }); ``` and this for the client side
#

the connection is working, but the message is not being recieved by the client

lime mist
half patrol
#

ok I will, but can you find anything wrong with my code?

lime mist
#

no, not really

half patrol
#

no

#

I will try the code on your github thanks alot

half patrol
lime mist
#

yeah, I also have a server made in python that works with it but it's made with socketio and I see you are using flask socketio

lime mist
half patrol
lime mist
half patrol
#

yea it's alright I appreciate your help

lime mist
half patrol
#

alright I was confused abit haha

lime mist
#

I realised XD

#

Good Luck ๐Ÿค›

half patrol
#

thanks

#

oh my god man it works thanks ALOT

surreal portal
#

Trying to understand how Steamlit works

#

Looking at the source code, Python calls JS, right?

#

Here's an example

#
        text_proto = TextProto()
        text_proto.body = clean_text(body)
        return self.dg._enqueue("text", text_proto)

And TextProto is a component:

export default function Text({ width, element }: TextProps): ReactElement {
  const styleProp = { width }

  return (
    <StyledText data-testid="stText" style={styleProp}>
      {element.body}
    </StyledText>
  )
}
#

It's imported like that:

#
from streamlit.proto.Text_pb2 import Text as TextProto
stark tartan
#

Is storing a user actions log in database or Any log file Which Is good for social media website

stark tartan
#

Should I make UUID field for my post model or integer is okay

primal thorn
#

for django, can anyone recommend a way to get the user data like username, email with react (function based components)

sturdy rapids
#

Hi

#

So I am using an api to get stock prices in python

#

Now I want to use socket.io to use a web socket client

#

So how do I send my json file that I received to my JavaScript server

limpid nacelle
#

can i ask a css question in here too?

#

if yes

#

This should animate it so that the text changes every 10 seconds


#home .content h1::after{
    content: "cool";
    animation: textanim 10s infinite linear;
}

@keyframes textanim{
    25%{
        content: "A developer";
    }
    50%{
        content: "A programmer";
    }
    75%{
        content: "A student";
    }
}



altho it doesn't do that it just stays static at the "cool", any fix on this?

#

this doesn't work

#

it doesn't animate anything

dusty arch
#
CORS(app, origins=[base_origin])

@app.route("/api", methods=["GET", "POST"])
def api():
    if request.method == "POST":
        print(request.get_json()) # this still gets execvuted even if the request came from somewhere other than base origin. Any way to fix that ?

#

base_origin = "http://localhost:3000"

#

fetch("http://127.0.0.1:5000/api", {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify({"name": "xx"})
  })
#

and this is the fetch

versed python
limpid nacelle
#

what should i add in the 0% keyframe?

inland oak
limpid nacelle
#

for some reason

rose marsh
#

Hi , I am building a reminder app and I am stuck at how I can take date from user input (as a user selects date from a calender) and store it in mongo and then schedule an email which will get send when that user selected date/time comes .

Cant solve this as I am beginner . Need help thank you

versed python
versed python
dapper raft
#

if anyone knows plz ping me i want to give custom url to my fastapi api

#

i want to run locally though , i want to make 2 api with different url so they wont confict with each other

quaint dew
#

Not really a web dev question but if I have a lot of different routes in a flask-app and I want to move them to a different script, what's the best approch? Import them to my main script and then use app.add_url_rule Or maybe first create the app=Flask() and then import so the app.route can be used accordingly. Both just seem very messy to me and keeping it all in one script isn't any better either

native tide
#

I'm building a server using HTML, and anyone is good at creating community login screens?
I need the help of a pro to help clear my doubts

#

Login page?

#

Only the frontend?

#

I made a login page but I want it to work

#

like being really logged in

#

U using django?

#

This might not be expert level but I might help๐Ÿค”

native tide
#

im newbie๐Ÿ˜ตโ€๐Ÿ’ซ

native tide
#

Are u trying to make your project look good?

native tide
dusty arch
cinder sequoia
#

Hello. Is there any project ideas using html and css?

native tide
#

i studied about linux

calm plume
#

Uh

#

Linux has nothing to do with how websites work

native tide
#

a

#

๐Ÿ˜ข

calm plume
native tide
#

I am learning computer programming as a hobby.

#

I started studying html by myself two weeks ago, and I am studying with the goal of making a website with html.

#

linux and db sever

#

๐Ÿ˜ข

calm plume
native tide
#

I have no idea how to implement sign up and save it to log in.

calm plume
calm plume
#

Check out the Django tutorial, it's great to get started with backend

native tide
#

ok thanks ๐Ÿ˜Š

#

I don't know what Django is, but I'll master it and comeโค๏ธโ€๐Ÿ”ฅ

calm plume
native tide
calm plume
#

Flask is a backend web framework, and you can extend it to work with your database, process user data, etc

native tide
#

ohh

#

ok ok thanks

#

helped a lot

#

โค๏ธโ€๐Ÿ”ฅ

native tide
#

If u going to learn html css js one by one it's gonna be taking more time

dusk portal
#

anyone's up

gentle jasper
#

hello! i'm learning Django and if anyone wants help on a project i'm available.

quaint dew
safe narwhal
#

can someone help me, I can't startproject on django, path incorrect somehow. I am using vsc

meager anchor
#

this is with django, right? can you paste your view definition? feel free to use our paste service if it's bigger

safe narwhal
#

django-admin startproject new django-admin : The term 'django-admin' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if
a path was included, verify that the path is correct and try again.

meager anchor
#

how did you install django?

safe narwhal
#

At line:1 char:1

  • django-admin startproject new
  •   + CategoryInfo          : ObjectNotFound: (django-admin:String) [], CommandNotFoundException
      + FullyQualifiedErrorId : CommandNotFoundException
safe narwhal
meager anchor
safe narwhal
#

how do I sett path for django?

dusk portal
safe narwhal
#

I need to set path for django-admin but I don't know how to do it. I am a begginer sorry

dusk portal
#

Ohh

gentle jasper
lethal mango
#

how is nodeexpress

calm plume
#

It's part of the pallets project

autumn hedge
#

@charred sphinx by installing it via the command line. cli commands may vary

spark granite
#

lel

#

ty

calm plume
#

It's not bad

autumn hedge
#
  1. install python ( if not already installed)
  2. install pip ( if not already installed )
  3. run pip install flask ( read the docs and follow steps )
sudden inlet
#

I wanna host a flask socket io script. can it be used with any frontend like say flutter app with websocket library or do I have to use some specific socketio library for compatibility?

pine torrent
#

how to display datetime as a parameter in django url pattern

wooden ruin
#

from there you can format that string into a url

stark tartan
#

how to make tagged by"#" in description field of my post model

royal cloak
#

hello guys, has anyone ever used google cloud?, i tried to install google cloud sdk on windows 10 but it doesn't work, do you guys have any suggestions?, thanks

sharp basin
#

Hello, does anybody have any suggestion to what makes a website intelligent

#

and also how do you test the following:

#
  1. anti malware software
#
  1. website application firewall
#
  1. DDos protection
#
  1. A CMS platform
#

and does anybody have any ideas to what makes a website secure

#

i am currently web testing someone's website

#

now do not worry i have permission

#

from the owner

#

so does anybody have any suggestions?

storm estuary
#

Why doesn't the footer go down?

#

footer

#

base.html

wintry dome
#

I need to get a token with oauth2 + python client application. Everything I'm finding is server side. I need to be able to launch our backends login page, log the user in and on success return a token back to the python application. The backend is completely working and finished but I just can't seem to find any info for doing this client side in python

#

nvm looks like oauth2-client might be what I need

bright mason
#

Couldn't really see the photo well

rough breach
#

hi

#

how are you iยดm new programmmer

sly adder
#

any django people online?

#

I'm having some difficulties with forms

split steeple
sly adder
#

Linking functions to buttons

#

Right now I have a very simple app

#

I have race / age / name entry

#

I have code behind the scenes that will calculate a prediction when it receives the race / age values supplied through this form based on statistical data, etc.

#

I would ideally like the "Predict" button to retrieve the current values input into the form and then execute my code for calculating the prediction and then update the form "Prediction" as shown in the picture above

#

@split steeple

split steeple
#

Can I see some of the code you're using?

sly adder
#

Sure, what would you like to see?

split steeple
#

Also if I may ask, what sort of predictions is this app meant to make?

sly adder
#

It's applying a machine learning model based on statistics

#

The prediction isn't relevant to the problem I'm experiencing

#

I can already successfully generate the predictions based on the ML model

#

I just can't tie it all together

#

It's based on publicly available data

#

What code you do want to see?

#

Forms ? Models? HTML templates?

#

Views?

split steeple
#

Views

#

Please

sly adder
#

So this is where I tried to define my function

lavish prismBOT
sly adder
split steeple
#

Alright the views look fine

sly adder
#

Ok

split steeple
#

When you say "can't tie it all together", do you mean it won't display what a user inputs?

sly adder
#

I'm trying to attach that gather_data function

#

to the "Predict" button

#

And then generate the value

#

Based on the current form input

sly adder
#

So I want to press "Predict", then I want to execute the gather_data function, then I will complete my calcs and subsequently send the result back to update the prediction field of the form

#

If it's easier to create another simplistic HTML template to display the result that's also fine for the time being

split steeple
#

Could I see the form?

sly adder
#

the HTML template responsible for the form or the forms.py content?

#
from django import forms
from .models import Person


class PersonForm(forms.ModelForm):
    class Meta:
        model = Person
        fields = ['name', 'race', 'age', 'prediction']

        name = forms.CharField(max_length=100)
        prediction = forms.CharField(max_length=50, required=False)
#

Here's what I have defined as my PersonForm

split steeple
#

HTML form

sly adder
#
{% extends 'base.html' %}

{% block content %}

<h2>Personal Information Form</h2>

<form method="post" id="personForm">
    {% csrf_token %}
    <table>
        {{ form.as_table }}
    </table>
        <button name="predict" type="submit">Predict</button>
        <button name="save" type="submit">Save</button>
        <button name="reset" type="reset">Reset</button>
        <a href="{% url 'person_changelist' %}">Return to Previous Page</a>
</form>

{% endblock %}
#

So

#

Based on the help from another user, I believe I need to have some action="" definition within the <form method="post" id="personForm"> opening to the form

#

I just don't know how to define the action specifically to the button

#

And if I need to redefine this form template in order to improve the quality of things I have no issue with that

split steeple
#

Yeah, I'm trying to figure it out myself and I'm coming up a bit short

sly adder
#

no worries

#

I think the easiest route is to direct everything to a new URL

#

something called results.html

#

That just displays a number which is the value

#

But I still don't fully understand the form action

split steeple
#

Yeah, go ahead and try that

#

although

sly adder
#

Yeah I'm just confused lol

split steeple
#

as far as the HTML you posted goes, only thing I notice wrong is that "post" isn't in all caps, unless that doesn't matter(never did it without using all caps)

sly adder
#

Idk if I would need to update urlpattersn

split steeple
#

if you're going ahead and adding the results.html template then yes

sly adder
# split steeple if you're going ahead and adding the results.html template then yes

So don't know if you're still interested, but I achieved the functionality imperfectly.

(1) I had to define the action attribute for the form and direct that to a URL
(2) I had to create the simple results.html template to display the value
(3) I had to update the url patterns for the new add/results/ page
(4) had to fix a lot of my data gathering from the forms within my gather_data function

and probably a few more things lol

split steeple
#

I'm glad to know it's starting to work for you

#

Wish I could have been more help than I was

dusk portal
#

i need help

dusk portal
#

how can i render my image here

#

of model

#
MEDIA_ROOT=Path(BASE_DIR,'media')
MEDIA_URL='/media/' ``` added this too in settings
#

and its working fine

#

sending images to path

#

added ```py
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL,
document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)

#
class Product(models.Model):
    title=models.CharField(max_length=50)
    price=models.IntegerField(default=0)
    pic=models.ImageField(default='default.jpg',upload_to='images')
    desc=models.TextField()
    published_date=models.DateTimeField(default=datetime.now())
    slug=models.SlugField(max_length=35)

    def __str__(self):
        return self.title```
#

what's the issue

#

i cant get

sudden gulch
#

hey i am learning rest_framwork of django but its hell confusing there are many things that i m not understanding like serealizers hyperlinkModelseriralizer models.auth. what should i do is there any pererequsit before learning the rest_framework

dusk portal
#

umm

#

for displaying we dont need pillow

#

to resize we need pillow

#

and play with img

split steeple
arctic wraith
#

did you put ".url" at your variable image in the end (Html form) ?

dusk portal
#

Wait I'll show my html

#

Is this backend correct

#

Wait sending html

arctic wraith
#

ah okey

dusk portal
#

Lemme on py lapi

#
{% extends "index/base.html" %}
{% block title %}E-COMMERCE {% endblock title %}

{% block content %}
<section class="text-gray-600 body-font">
    <div class="container px-5 py-24 mx-auto">
      <div class="flex flex-wrap -m-4">
        <div class="lg:w-1/4 md:w-1/2 p-4 w-full">
          {% for items in n1 %}
          <a class="block relative h-48 rounded overflow-hidden">
            <img alt="ecommerce" class="object-cover object-center w-full h-full block" src="items.pic.url">
          </a>
          <div class="mt-4">
            <h2 class="text-gray-900 title-font text-lg font-medium">{{items.title}}</h2>
            <p class="mt-1">{{items.price}}</p>
          </div>
          <div>
            <div class="flex justify-corner items-corner">
                <div class="flex">
                    <a href="{% url 'index:detail' items.slug %}"><button type="button"  class="bg-blue-500 text-white px-6 py-2 rounded font-medium mx-3 hover:bg-blue-600 transition duration-200 each-in-out">Order</button> </a>
                    <button type="button" class="bg-gray-700 text-white px-6 py-2 rounded font-medium mx-3 hover:bg-gray-800 transition duration-200 each-in-out">+ to Cart</button>
                </div>
                {% endfor %}
            </div>
          </div>
        </div>
      </div>
    </div>
  </section>
{% endblock content %}```
#

@arctic wraith

#

and u can see settings urls views and models ^^

arctic wraith
#

okey i see

#

and can you show me the view function or class ?

#

try to put src="" at the beginning of <img ...

dusk portal
#

<img alt="ecommerce" class="object-cover object-center w-full h-full block" src="items.pic.url">

#

instead of this

#

what i have to put

#

give me ill copy paste

#

pic=models.ImageField(default='default.jpg',upload_to='images')

#

thats why i used pic

#

and items == the for loop ^^

#

umm

subtle hamlet
#

hi i tried implementing a countdown timer, im not done yet jus to input the start time limit but im not sure why it gives wrong output

#
<script>

document.addEventListener('DOMContentLoaded', function() {
  let start = document.querySelector('#start');
  start.addEventListener('click', function() {
    let timeleft = document.querySelector('#timeleft');
    let hours = document.querySelector('#hours').value;
    let minutes = document.querySelector('#minutes').value;
    let seconds = document.querySelector('#seconds').value;
    let timelimit = (hours * 3600) + (minutes * 60) + seconds;
    let shownhours = Math.floor(timelimit/3600);
    let shownminutes = Math.floor((timelimit - (shownhours * 3600))/60)
    let shownseconds = (timelimit - (shownhours * 3600)) % 60
    if (shownhours < 10) {
      shownhours = `0${shownhours}`;
    }

    if (shownminutes < 10) {
      shownminutes = `0${shownminutes}`;
    }

    if (shownseconds < 10) {
      shownseconds = `0${shownseconds}`;
    }
    timeleft.innerHTML = `${shownhours}: ${shownminutes}: ${shownseconds}`;
  })

})

</script>

<body>
<input type = "text" placeholder = "hours" id = "hours">
<input type = "text" placeholder = "minutes" id = "minutes">
<input type = "text" placeholder = "seconds" id = "seconds">
<input type = "submit" id = "start" value = "Start">

<div class="base-timer">
  <svg class="base-timer__svg" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
    <g class="base-timer__circle">
      <circle class="base-timer__path-elapsed" cx="50" cy="50" r="45" />
    </g>
  </svg>
  <span id="base-timer-label" class="base-timer__label">
      <p id = "timeleft">00:00:00</p>
    <!-- Remaining time label -->
  </span>
</div>
</body>```
#

first text is hours, second text is minutes, third text is seconds

native tide
#

can someone help me with css positioning ?

native tide
# native tide can someone help me with css positioning ?

position: static position accoring to the website
position: relative relative to the normal position
position: fixed always in the same place; even if the page is moved
position: absolute positioned to its ancestor; moves along with page movement
position: sticky stays on top, or the same place even when scrolled
width: x changes the width of an element
height: y changes the height of an element
padding-left/right... creates space around elements
float: left/right brings an image to the left/right/top...

#

that are the most common ones

#

you've also got margin top left bottom display

native tide
#

TY

inland copper
#

guyz can u pls give me feedback on my website?

violet briar
#

is flask good enough for large-scale chat apps or do I need something heavily async like express (nodejs) or phoenix (elixir)

quick cargo
# violet briar is flask good enough for large-scale chat apps or do I need something heavily as...

Well Discord's api is built on Flask so the answer is yes, its fine.

Virtually all modern frameworks will give you more performance than you will ever need / never be the bottle neck.
Yes some frameworks are faster than others but generally this is completely overruled by things like waiting on IO, databases etc... as soon as you get to any sort of large scale or ever small scale the framework is generally never the bottleneck

violet briar
quick cargo
#

no lol

#

The only NodeJS stuff iirc is just the electron runtime the app uses

violet briar
#

oh, okay

#

wait, apparently, they use a modified version of flask, not a normal version

#

I wonder what they modified exactly

#

also, do they use flask for the websockets part as well?

quick cargo
#

no websockets are mix of elixer / erlang and rust i imagine.

#

the 'modified' is using the gevent monkey patching iirc

#

basically monkey patches the existing python setup to act asynchronously without having to really change anything

#

generally very popular in flask setups because it works so well

#

although the recent Flask 2 changes are probably gonna end that

violet briar
violet briar
quick cargo
#
from gevent import monkey
monkey.patch_all()```
#

thats about all it takes to patch it and make it async

quick cargo
#

Large systems generally dont use one framework or language

#

tends to be alot of micro services

#

websockets are a bitch to scale really so something like erlang or rust with work stealing schedulers make it much easier to scale

violet briar
#

ok, so where do they use flask exactly? do they use it for only some stuff like requesting server info?

quick cargo
#

all of the REST API

#

aka everything you use to make changes to the api, the websocket is generally only receive other than presence so all of the things like messages, reactions, etc.... are all done via the REST api with flask

violet briar
#

oh, so the messages served to me when I visit a channel are requested through the flask API, when the websocket is using elixir?

quick cargo
#

generally the setups are you send stuff to the server via REST

#

and receive stuff via ws

native tide
#

sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: students

even after dbcreate cmd

PS C:\Users\hp\newproj> db.create_all()
At line:1 char:15

  • db.create_all()
  •           ~
    

An expression was expected after '('.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : ExpectedExpression

violet briar
# quick cargo and receive stuff via ws

hmmm, I don't really understand what's happening here
does the websocket notify the client and send the new message info to it, or does it notify the client to just make a new request to the API to refresh messages?

quick cargo
#

it sends the messages to the client via the websocket

#

you -> discord = REST
discord -> you = WS

violet briar
quick cargo
#

no

#

well

#

you can think of it like that yeah

violet briar
quick cargo
#

its pretty reliable yeah, keeps it pretty simple as well

violet briar
#

can't find the page in the api docs that documents how the chat works exactly

quick cargo
#

its complicated

#

but you can summarise it like that

violet briar
#

also, does the discord client listen on one websocket for every task (e.g private messages, notifications) or does it listen on one websocket that sends it everything?

quick cargo
#

the one connection sends everything

violet briar
#

and, would it be better to use a graphql API for the chat app?

quick cargo
#

you can use it, but probably a little overkill

violet briar
#

I mean, discord didn't adopt graphql because they don't want to maintain 2 APIs, but here I am just starting out so I can choose graphql without any issues, the question is, does it scale better with chat apps

quick cargo
#

discord dont use graphql

violet briar
quick cargo
#

and graphql is just alot of extra work

#

for something that doesnt need it

#

the REST api overall is very simple, there isnt a large amount of dynamic things you can change as part of the query

#

Graphql is great for large complicated apis where you can change and filter many many things

#

but using it on a simple structure tends to be overkill / needlessly add the requirement for clients to use it

violet briar
quick cargo
#

I dont see how graphql helps that at all

#

other than use unnecessary bandwidth

violet briar
#

I think it'd help with that as the client will be able to get everything it wants in one request instead of making many requests to many endpoints

quick cargo
#

sure but then what you're doing is increasing the time it takes to send one request massively

#

rather than having several smaller requests which can be done asynchronously of each other

violet briar
#

hmmm, so graphQL won't really help that much, but, can I also use it just for the sake of gaining experience with it?

quick cargo
#

sure

violet briar
#

I think I've never built a real graphQL api before

#

hm, okay, I think I got the tech stack for the project laid out
flask with graphene for the API
nodejs with socket.io for the websockets
react for the front end with relay
mongodb for the database

native tide
#

How can I just make a thing where it redirects you to a website.

thorn igloo
#

can't you do that where you bought the domain?

native tide
#

idk

surreal portal
#

Hello! What's the point of Redis, Celery and Flower altogether in a Python web app?

#

Allow better services?

opaque rivet
#

@native tide you can return a 301 response and include the Location header with the url to redirect to

#

@surreal portal
Redis - noSQL db in memory, fast reads/writes
Celery - async scheduled tasks, replacement to cronjobs

surreal portal
#

Interesting

desert estuary
#

hey everyone hope you're doing fine

TypeError
TypeError: normalize() argument 2 must be str, not FileStorage

Traceback (most recent call last)
File "C:\Users\Hamza\Desktop\PFA\FLASKPROJ\Lib\site-packages\flask\app.py", line 2088, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\Hamza\Desktop\PFA\FLASKPROJ\Lib\site-packages\flask\app.py", line 2073, in wsgi_app
response = self.handle_exception(e)
File "C:\Users\Hamza\Desktop\PFA\FLASKPROJ\Lib\site-packages\flask\app.py", line 2070, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\Hamza\Desktop\PFA\FLASKPROJ\Lib\site-packages\flask\app.py", line 1515, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\Hamza\Desktop\PFA\FLASKPROJ\Lib\site-packages\flask\app.py", line 1513, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\Hamza\Desktop\PFA\FLASKPROJ\Lib\site-packages\flask\app.py", line 1499, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
File "C:\Users\Hamza\Desktop\PFA\Flaskiproject\routes.py", line 45, in user
file=secure_filename(form.uploadfile.data)
File "C:\Users\Hamza\Desktop\PFA\FLASKPROJ\Lib\site-packages\werkzeug\utils.py", line 456, in secure_filename
filename = unicodedata.normalize("NFKD", filename)
TypeError: normalize() argument 2 must be str, not FileStorage
#
@app.route('/user',methods=["GET","POST"])
def user():
   if "student" in session:
      current_student=Students.query.get(session['student'])
      form=Uploading()
      if form.validate_on_submit():
         file=secure_filename(form.uploadfile.data)
         if pathlib.Path(file).suffix.lower() in {'.jpg', '.png', '.pdf','.txt'}:
            uploaded_file=secure_filename(file.filename)
            print("hhhhhh")
            uploaded_file.save(os.path.join(app.config["UPLOAD_FOLDER"],uploaded_file))
         else:
            flash(" we don't allow this file extension ")
         return redirect(url_for('user'))
   else:
      return redirect(url_for("login"))
   return render_template("User/Homepage.html",student=current_student,form=form)
#

i twisted it a little bit it seems he has a prob with the filestorage thing but i can't turn a file into a string either

desert estuary
#
@app.route('/user',methods=["GET","POST"])
def user():
   if "student" in session:
      current_student=Students.query.get(session['student'])
      form=Uploading()
      ext={'jpg', 'png', 'pdf','txt'}
      if form.validate_on_submit() and request.method=="POST":
         file=request.files['uploadfile']
         if pathlib.Path(file).suffix.lower() in ext :
            print("hhhhhh")
            uploaded_file=secure_filename(file.ext)
            uploaded_file.save(os.path.join(app.config["UPLOAD_FOLDER"],uploaded_file))
         else:
            flash(" we don't allow this file extension ")
         return redirect(url_for('user'))
   else:
      return redirect(url_for("login"))
   return render_template("User/Homepage.html",student=current_student,form=form)

updated the code

desert estuary
#

i'm really sorry to bother you but here i guess im a little bit closer HHH

@app.route('/user',methods=["GET","POST"])
def user():
   if "student" in session:
      current_student=Students.query.get(session['student'])
      form=Uploading()
      ext={'.jpg', '.png', '.pdf','.txt'}
      if form.validate_on_submit() and request.method=="POST":
         file=request.files['uploadfile']
         if pathlib.Path(file.filename).suffix.lower() in ext :
            print("hhhh")
            uploaded_file=secure_filename(file.filename)
            file.save(os.path.join(app.config["UPLOAD_FOLDER"],uploaded_file))
         else:
            flash(" we don't allow this file extension ")
         return redirect(url_for('user'))
   else:
      return redirect(url_for("login"))
   return render_template("User/Homepage.html",student=current_student,form=form)

error
FileNotFoundError
FileNotFoundError: [Errno 2] No such file or directory: 'C:/Flaskiproject/fileupload\CV.pdf'
File "C:\Users\Hamza\Desktop\PFA\Flaskiproject\routes.py", line 50, in user
file.save(os.path.join(app.config["UPLOAD_FOLDER"],uploaded_file))

versed lotus
#

make sure the folder also exists

edgy anvil
#

in django how do i make it so some pages can't be accessed once the user has logged in

desert estuary
#

fileupload is in thee

versed lotus
#

the one it mentions in the error message: C:/Flaskiproject/fileupload\CV.pdf

desert estuary
#

idk how to do it ahahah im following the tutorial form the flask docs and still a pain in ass

versed lotus
#

make sure C:/Flaskiproject/fileupload exists, and is written exactly like that

desert estuary
#

C:\Users\Hamza\Desktop\PFA\Flaskiproject\fileupload
actually that's the absolutepath but i don't wanna do it that way since if i gave it the absolute path how it would do in a server

#

since in a server C:/Users/Hamza doesn't exist

versed lotus
#

well that doesn't work then of course

#

you can figure out where the path is, or what's more common: have different configuration files for local testing and on the server

#

usually you wouldn't even have uploads be stored in the project folder, but somewhere outside. perhaps, depending on if it should be downloadable later, in a directory the webserver is going to have access to

desert estuary
#

wait i kinda get it idk if this will work on the server as well

from flask import Flask
from secrets import token_hex
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
import os

app=Flask(__name__)
xa=token_hex(16)
app.config['SECRET_KEY']=xa
app.config['SQLALCHEMY_DATABASE_URI']='sqlite:///PFA_DB.db'
path = os.getcwd()
UPLOAD_FOLDER = os.path.join(path+'/Flaskiproject/fileupload')
app.config["UPLOAD_FOLDER"]=UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 10 * 1024 * 1024
db=SQLAlchemy(app)

login_manag=LoginManager(app)

import Flaskiproject.routes
``` and im talking abou tthis part exactly
```py
path = os.getcwd()
UPLOAD_FOLDER = os.path.join(path+'/Flaskiproject/fileupload')
app.config["UPLOAD_FOLDER"]=UPLOAD_FOLDER
compact glacier
#

Hello guys, working on simple django project, but have a trouble.

Im parsing data from API, then store it to DB, and from DB i must send it to template.

But i must send 50 objects so even in JSON it sends as LIST of DICTs, and im really confused by it.

def read_db(offset):
    conn = None
    try:
        conn = psycopg2.connect(host="localhost", database="crypto", user="postgres", password="admin")
        cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)

        cur.execute(f'SELECT * FROM main_block OFFSET {offset} LIMIT 50;')
        fetch = cur.fetchall()
        dic = {}
        data = []
        for i in fetch:
            dic['hash'] = i['hash']
            dic['height'] = i['height']
            dic['timestamp'] = i['timestamp']
            dic['miner'] = i['miner']
            dic['transactioncount'] = i['transactioncount']
            data.append(dic.copy())

        return json.dumps(data, separators=(',', ':'))

    except (Exception, psycopg2.DatabaseError) as error:
        print(error)
    finally:
        if conn is not None:
            conn.close()```
#

thats how i get data from DB

example of Data that i got:

[{"hash":"384f3e42b8e26443bc1087a0387827146a41f9d3ef663a7d7eda82c927e78bf2","height":"315012","timestamp":"1624372128","miner":"BTJi34JG4dmL5GbTYgDdp8Nyb7Mhpsd1az","tr
ansactioncount":"2"},{"hash":"bcf54ece598e7def8fedfea23c2f4cce7bd2d1ec35351fe9f4d8523ac2fa26de","height":"315011","timestamp":"1624372016","miner":"BTJi34JG4dmL5GbTYgD
dp8Nyb7Mhpsd1az","transactioncount":"2"},{"hash":"aef7e142303e54c08f885965877199f6af6ee4da8687eed8505e6a4fb41ef446","height":"315010","timestamp":"1624371920","miner":
"BTJi34JG4dmL5GbTYgDdp8Nyb7Mhpsd1az","transactioncount":"2"},{"hash":"50ca063a86f434ce08e7e8537808662a0e782935eb5e72bdb506c5e32b5a3391","height":"315009","timestamp":"
1624371808","miner":"BTJi34JG4dmL5GbTYgDdp8Nyb7Mhpsd1az","transactioncount":"2"},{"hash":"f592d181a1bec34566509152d1e0e5ac8531ae23b5a91e6bec27ade3001e69bf","height":"3
15008","timestamp":"1624371648","miner":"BTJi34JG4dmL5GbTYgDdp8Nyb7Mhpsd1az","transactioncount":"2"}]```

and strange thing that it type is STR
```<class 'str'>```
#

some ideas how to send it to Template?

rotund harness
#

Is the data type string?

opaque rivet
#

you can just deserialize your data:

data_array = json.loads(json_string)

Then you can loop through data_array in your template

#

also, what's your project about? data is interesting.

compact glacier
opaque rivet
#

dont want to talk atm, looks like a blockchain project which is interesting

compact glacier
#

sadly (

compact glacier
opaque rivet
#

at the moment

compact glacier
edgy anvil
#

wait guys i deployed my django app on aws ec2 instance but none of the css is working any solutions?

compact glacier
opaque rivet
gentle kestrel
#

hello evryone i want just to ask what is best framwork to be front_end_dev with python .

opaque rivet
edgy anvil
#

wait guys i deployed my django app on aws ec2 instance but none of the css is working any solutions?

gentle kestrel
#

without back_end

median quartz
# gentle kestrel hello evryone i want just to ask what is best framwork to be front_end_dev with ...

Transcrypt (https://www.transcrypt.org/) translates Python to Javascript for use in the browser

#

It has it's quirks though, be warned ^^

edgy anvil
#

wait guys i deployed my django app on aws ec2 instance but none of the css is working any solutions?