#web-development

2 messages ยท Page 121 of 1

formal gull
#

?

native tide
#

how to check if a value exist ?

views.py

def put(self, request, format=None): 
        print("DATA ",request.data)
        instance = Car.objects.get(id=request.data["id"])
        new_color = []
        if (request.data.pop('new_color')):
            new_color = request.data["new_color"]

Error:
File "D:\Dev\Django\template\default\views.py", line 36, in put
if (request.data.pop('new_color')):
KeyError: 'new_color'

fast frigate
native tide
#

should I move to django, or stay at flask?

acoustic oyster
acoustic oyster
native tide
#

is it possible to use Array data types with Flask-SQLAlchemy?

swift sky
#

are you supposed to test view functions if it's static content that is being served

haughty bone
#

Hi ALl

#

Can you please take look at this question,

#

With Django am unable to lazy loaded module

onyx crane
#

Django
Im trying to play audio in my template but it doesn't load the file properly.
I've added a FileField, defined medai_root and url and successfully uploaded a mp3 file that got saved in the specified directory.
Now im trying to reference it like this in the template but it doesn't find the file even though it does look in the correct directory.

page.html

<audio src="{{ story.upload.url }}"></audio>

JS Console:

localhost/:22 GET http://localhost:8000/media/audio/Testmusic.mp3 404 (Not Found)

Feel free to @me :)

trail vapor
#

jinja2 or brython ,which one do you recommend?

#

I use flask and I would like to link it to brython to make my site interactive (adding one or more pop-up windows) is it possible thanks

gaunt marlin
#

@trail vapor jinja is a template engine and brython is just an api to convert python code to javascript, those are 2 different things

#

if you want the site to be interactive, i think javascript is enough

tacit kernel
#

what HTTP response code should i use for a API endpoint that requires a auth token, but no token has been generated yet?

#

would the normal 403 work fine, or is there something that would be more specific?

trail vapor
#

jijinja2 serves me at the back but I would like with brython create pop_up windows for all which alert message such successful authentication or other

trail vapor
frozen python
#

Does anyone like using Django with React? What stack do you use? Also... do you use Next.JS?

near bison
#

Is creating a new app in django for authentication the right way to do it ?

#

I mean the signup and login views and the profile view etc

nova nacelle
#

avoid using the default auth user models and views @near bison

near bison
#

Why? @nova nacelle

#

I might not use the default user views. but why not the default User Model ? @nova nacelle

nova nacelle
#

first thing it is not practical to make changes to them, and like if u want the user to log in with the email address, or u wanna change the max length of username and all...
i faced such things and decided to create a custom user model for my project

#

also i can have it anyway i want

nova nacelle
near bison
#

first thing it is not practical to make changes to them, and like if u want the user to log in with the email address, or u wanna change the max length of username and all...
i faced such things and decided to create a custom user model for my project
@nova nacelle if i make the model myself , will i have to write code to manage sessions , authorisations, permissions etc?

#

Isn't there a way to customise the default user model?

obsidian hedge
#

!accept

nova nacelle
#

it disturbs the whole system

hazy birch
#

Hello , I am coming from a java-springboot rest api background, im trying to set up APIs using flask, how does the whole models and dtos work in python
how should i structure my application ?

indigo kettle
#

@near bison I like to not touch the User model directly but if there is extra information I want for the user I will sometimes tack on another model with a onetoone field

rotund token
#

tag me if u can help me with css

surreal harness
#

not a specific questino but more generic: What are some standard ways / checkboxes to tick for API logging? I'm not entirely sure that I'm properly capturing all the possible errors that could happen when someone hits my API and I would like to log them in the server.

An example: If I have a basic GET API which returns an Object, I do basic checking for whether the object exists or doesn't, then I send back an appropriate response. But I want to be able to

  1. Record that call and the response given somewhere, perhaps a database or logging module (database is probably better for obvious reasons)
  2. Catch other exceptions out of the scobe of object retrieval, for example bad headers or server errors or something like that

I feel a bit out of my depth in understanding all the things I need to track to make sure I'm properly handling all of the possible ways an API can get messed up

near bison
full sedge
#

how to save form data when user leave page?
like if i close browser by mistake while filling form
so i want old data that i fill in the form

nova nacelle
native tide
#

I keep getting SMTP errors, and I'm clueless what should I do to debug

near bison
#

How do i make a new one ? @nova nacelle

nova nacelle
#

search videos for a "custom user model django"

#

@near bison

native tide
#

why did my app sent the raw html instead of the styled page on email?

full sedge
native tide
#

but it didn't in .env

#
EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER')
EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD')
``` this is my `settings.py`
#
export EMAIL_HOST_USER = xxxxx@xxxx.xxx
export EMAIL_HOST_PASSWORD = xxxxxxxx``` this is .env
#

am I not doing right? @full sedge

full sedge
#

yes it is right

#

by the way which password are you using>'?

native tide
#

wdym?

#

@full sedge btw, that sent the confirmation email but it sent the raw html message lol

#

why did that happen?

zinc hill
#

I am trying to learn how to use the django_rest_framwork and react. But currently, I am stuck at the CSRFTOKEN.

Currently, I have a button which get which trigger a fetch POST, but everytime i triggered it I get 403 forbidden. Does anyone know how to fix this?

#
handleDocument = () => {
axios(
            {
                method: 'post',
                url: url,
                data: {
                    "test": "test"
                },
            }
        ).then(function (response) {
            console.log(response)
        }).catch(function (error) {
            console.log(error)
        });
<button className="buttons" onClick={this.handleDocument}>something</div>
native tide
#

In My Python Flask App I want To Make Some Custom Stuff In HTML Template

#
{% if session['loggedin'] %}<a href="{{ url_for('dashboard') }}" class="cta"><button>My Account</button></a>{% endif %}
        {% if not session['loggedin'] %}<a href="{{ url_for('login') }}" class="cta"><button>Login</button></a>{% endif %}
#

this is my code inside of the flask app

#

what im trying to do is if session['loggedin'] is true it will display my account

#

otherwise it will show login

native tide
#

i fixed it thanks anyways

native tide
#

@zinc hill have you download django-cors-headers

#

And allowed requests from your react frontend

fluid dawn
#

django-cors-headers for rest api

near bison
#

In django, Is it possible to validate a normal html form submission. which isn't made from a forms.ModelForm against a forms.ModelForm ?

#

How do i validate a normal html form which isn't made as a forms.ModelForm instance ?

#

How do i add a phoneNumber field to django

native tide
#
<a  href="http://{{domain}}{% url 'activate' uidb64=user_id token=token %}"
                    target="_blank"
                    >http://{{domain}}{% url 'activate' uidb64=user_id
                    token=token %}</a>
``` when I do this, the link is generated but the text displays the href same (without the exact syntax). how do I solve?
indigo kettle
#

@near bison you can write a forms.Form and tell it what fields you want and write your own validation methods on it. A phone field often will use some regex to validate that it is the format you are expecting.

near bison
#

@indigo kettle and then can i use it validate any form ?

#

i mean a form which is not created with that using it in the template

somber fable
#

i have a doubt with data bases

#

i'm creating a todo list

#

and i wanna make it a personal todo list

#

i've been researching and watching videos about this

#

but they only show how to create they never show how to create for each every user

#

if i create one todo list in one acc

#

i see the same todo list created in the second acc is see the todo list created in first acc

#

pls DM me

indigo kettle
#

You're saying you're rendering a template that isn't going to use the forms.Form class but you still want to validate it using the Form? I suppose you can but it's a little strange

native tide
#

@somber fable I've answered this for you already, your program has to differentiate between users. You need authentication.

somber fable
#

yea its u again

#

i did

#

it aint working for me

#

it ends up giving an error

native tide
#

And what is that error

somber fable
#

i dont know

#

i didnt undertsand wat happened

#

so i just removed the the todo list and started fresh

native tide
#

Well the error should've told you what happened...

#

Then we could've troubleshooted and continued

somber fable
#

it says line 2000+ and stuff whereas i didnt write any code above 100 lines

native tide
#

yep, because you're using Django, which includes its own files which has thousands of lines of code.

#

So if you are using a feature incorrectly of one of them files, there will be an error

somber fable
#

so i came back looking for anyone to do it and explain how it works

#

i use flask

native tide
#

Or flask, since you're importing modules

somber fable
#

i'm just a rookie, started 2 months ago

native tide
#

You should read through a tutorial which explains it

somber fable
#

but currently trying web dev

native tide
#

I think it's called werkzeug-security for auth

somber fable
#

i did

#

umm

#

i think this would be shameless if i ask

#

can u do this and explain me

#

i really dont get it

native tide
#

do what?

somber fable
#

i mean creating database which carry a todo list for each and every individual

native tide
#

Well, it's not really a database problem. You will have one table in your database which contains all the todos for users. It's an authentication/account issue

somber fable
#

i really dont understand wat u r tryna say me

#

but i'm very rookie to this web dev

#

just started like 6-7 days ago

#

@native tide

#

u there?

#

umm..

#

i might have been troubling u

#

sorry then

somber fable
#

i completed remaking the app again

#

just need to do this

native tide
#

What I'm trying to say is, you need to store your notes within a table in your database, and then you need some form of authentication to link a logged-in user's notes to their account

somber fable
#

okay

#

shall i send my code as a zip?

#

@native tide

sonic ferry
near warren
#

um... How do you use Django?

#

is it like use index.html?

#

and link it with .py?

hoary marlin
#

Hey guys!
Ideally We use Table to show the data we fetched from a sql database right?
we do that by using jinja templates and mysql cursor.
we execute a select * query and store the info in some variable and pass that variable to html page.

but what to do in case of this
if the html page is already made and it contains fields to display specific data values.

ex: if I have a student table with columns:- ID, NAME, SUBJECT
the table will look like this
| Id | Name | Subject |
| 01 | John | Biology |
| 02 |Fred | Economics|

and I write this query:

sid=02;
Sdetail=cur.execute(" Select * from student where id=%d",(sid))
return render_template('data.html', studentDetails=Sdetail)

and data.html will be like this:

ID:__________________
Name:_______________
SUBJECT:______________

how will I display those specific cell data to the specific fields?

snow sierra
#

hey all ...

any chances to show time live format?? without ajax or js..

#

i have this in template {% now "d/m/y" %} {% now "H:i:s" %} but it is frozen of course..

native tide
#

"live" is ajax

snow sierra
#

ok then..

#

ty.

tired venture
#

hi I am working with flask and i have this function ```python
@app.route("/", methods=["POST"])
def filterUpdate():
if request.method == 'POST':
filter = request.form['filter']
return redirect(url_for('index'))

dense slate
#

"filter" isn't returned

#

What are you trying to return back to the code?

#

You need to pass the filter variable back to whatever code called the function.

tired venture
#

so i have filter defined outside the function as a global

upper perch
#

doesn't that overwrite create a new filter object the global definiton? (I don't use FLASK, just python)

dense slate
#

I don't think so, because filter is local to the function.

tacit granite
# near warren um... How do you use Django?

Django follows the MVT structure: Model, View, Template. Your Template is your html file, View is written in python and in the view you tell it how to interact with the web app or the database. Model is the foundation of the database.

dense slate
#

"To access a global variable inside a function there is no need to use global keyword. If we need to assign a new value to a global variable then we can do that by declaring the variable as global. This output is an error because we are trying to assign a value to a variable in an outer scope.May 31, 2020"

#

@tired venture I'm also not sure why you wouldn't just return "filter" back to the original function?

#

Doesn't seem like much else is going on there.

upper perch
#

you can reference but not assign to a global in a function, unless you define the global inside the function, makes sense

tired venture
#

When I first tried it it was messing with my redirect for the webpage so I was trying to see if I could bypass that but that could have been another issue

#

The other thing is this event is triggered by a button on the web page

dense slate
#

if request.method == 'POST':
Why aren't you using this in the function that handles the form?

#

Oh I see, you press a button and that activate this function.

tired venture
#
@app.route("/", methods=["POST"])
def filterUpdate():
    global filter
    if request.method == 'POST':
        filter = request.form['filter']
    return redirect(url_for('index'))
``` adding ```global filter``` like this fixed my issue
wintry edge
#

Hi everyone, I'm trying to upload images from TinyMCE's textarea to Django's server side and call them back as a list. Anyone tried to struggle with it before?

fluid dawn
#

Yeah I have ,

#

Moved to Amazon s3

#

Instead

wintry edge
#

@fluid dawn I'm trying to hold with a postAcceptor.php script as docs says. Did you use it to make it work?

formal gull
#

how would i go about sending a request to run a python function in a running python script? im essentially wanting my web page to take in a few user inputs then run them in my running selenium script.

#

what would i research for this is mostly what im asking

#

im trying to use django and js. not sure what else i need

native tide
#

@formal gull Have some API endpoints using django-rest-framework

#

You can make request to those endpoints containing data from your frontend, to run a specific function

formal gull
#

okay. im still quite confused on what that completely means right now but im on the right path to learning i think

#

thanks

native tide
#

Okay, if you have any questions feel free to ask ๐Ÿ‘ It's very similar to how you have your routes in urls.py and a view that runs whenever you visit a route - it's just that the API endpoints handle requests from your frontend which are not designed to be user-facing

formal gull
#

thanks! im currently just watching the tech with tim videos that he has out now and will kind of break away when the stuff is different then what i am looking for

naive shard
#

kindly suggest anyone to me, how to send bulk email in background or schedule through djanog. thanks

native tide
#

What's up ya'll. I have open source code for a Hero Slider I am trying to incorporate into my site. I have all the code for js, html, css, but cannot get it to work. Can anyone take a quick look and helpme out?

#

Thanks

gaunt marlin
#

@naive shard take a look at Celery of python, it work well with django for scheduling tasks

near bison
#

anyone who is familiar with aws ?

#

how much do you usually pay for a django app ? average. i know it depends on how much it's being used. is aws the cheapest option out there ?

gusty hedge
#

@near bison also depends on your traffic and application complexity. It could be from less than $5/m to thousands/m. You might want to be more specific

#

generally is not only serving just Django but also implies database, cache, background task services, etc

near bison
#

I am having trouble extending the default django user model
i need the user to have

phone_number(pk)
registration_id(optional)
first_name
last_name
password
Address -- (has more fields) (i am thinking about making address a different table and having a one to one relationship)
      Street
      District
      State
      Country
      Pincode
#

But i don't want the superusers to have all the properies. superuser needs only first_name, last_name, password.

native tide
#

@near bison you could use AbstractBaseUser to make your own User model with all of its properties. On saving an object to the model, you can check if is_superuser is True. And, if so, you can restrict the data to the columns you want.

native tide
#

@limber edge could you have your dest_address and from_address fields as a part of your Address model?

Then you can setup a relationship between Orders and Adress, and then access both of those fields from one relationship instead of multiple.

mental lodge
#

how can i overcome this error?

#

django web app deployment in heroku

#

wait a minute i'll send that too

native tide
#

@limber edge Yes, that would work if you want to specify if an address is dest or from.

I've not that familiar with SQLAlchemy, but like any ORM you can just access the tables fields through the foreign key.

proven wedge
#

can anyone helpme? my django manage.py file isnt working

native tide
#

If you find any better ways about it let me know, I'd be interested :)

#

@proven wedge what's the issue?

proven wedge
#

its saying : Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases.

native tide
#

Have you downloaded Python onto your PC?

proven wedge
#

yes

mental lodge
#

im getting this error in log

native tide
#

@proven wedge and upon installation, did you tick the box about PATH variables?

mental lodge
#

just go to the manage.py directory and give the command

proven wedge
#

yes

#

๐Ÿ˜ซ

native tide
#

Iirc I had a similar issue with python not found. I reinstalled python and made sure to tick the PATH variable box and it worked after

#

For windows 10

proven wedge
#

ok i'm gonna do that

rancid oak
#

Hey so I have a react express server with frontend and backend. In my backend Im storing data about Books in the actual localhost site when i open localhost:3000/Books all of the data shows up there, but Im checking if I can see the data in my Postman and when i try to enter localhost:3000/Books or localhost:5000 it just says Cannot Get /

#

What could the problem be

hoary marlin
#

Hey guys! how would I take date type input in flask?

date=datetime.strptime(request.form['startdate'],%Y-%m-%d)
should it be like this?

proven wedge
#

yeah thanks that worked!

mental lodge
#

@mental lodge It's a general rule that you should spend at least 20 minutes trying to solve something before you ask for help I believe
@limber edge been trying since yesterday

#

Can't find a lead

slim ether
#

hello

#

i have this .html file here

#

but when i opened it in the webbrowsewr

#

it returns a blank page

#

it flashes the content of the file for a second but suddenly it became like this

left jungle
#

Could you provide is with the html file please? @slim ether

native tide
#

should i start learning javascript because I'm decent with python(flask),html,css

marsh canyon
#

sure, it can be helpful in the frontend as you already know flask.

#

the fetch API or ajax is quite helpful for interacting with backends (flask)

native tide
#

i have worked with apis

#

alot

marsh canyon
#

making the UI smooth, example: not refreshing when you hit the like button (only possible with JS)

#

cool

native tide
#

should i learn python gui and js together

marsh canyon
#

flask can render web pages, you can sprinkle in some javascript to make the website more fluid and better

#

well it depends

native tide
#

like in different time period

marsh canyon
#

its totally upto you

native tide
#

I will do that because I know what i'm capable ..

#

@marsh canyon thanks

marsh canyon
#

๐Ÿ‘

steep fiber
#

Hey guys, I built the backend of an app now i'm really hating building the GUI
would you guys have any nocode solutions for this?
just to turn it into an app/ webapp
I see some nocode solutions online, wondering if anyone has any experience with them?

near bison
#

Can a field be not null and blank at the same time in django

#

Models

split steeple
#

Could you give me an example?

#

@near bison Cause django will throw an error at you if a field is blank

dense slate
#

@near bison Perhaps if you override the null or blank in forms.py, but I'm not 100%.

#

If you don't, then no.

#

You could have a default, which could just be {} or whatever as a placeholder.

#

I'm not 100% if you can use the front end to connect to your own private API but I'm pretty sure you can.

steep fiber
native tide
#

@split steeple @near bison blank=True on a field only affects forms iirc. That means that the field will be required if you render that form within your template. You can also have null=False in this scenario too. If it's a Charfield and nothing is passed and null=Falsedefaults to an empty string being saved in the model, so you can submit that form and not run into an errors (I think). Or you can have a field like this which will be based on the value of another field within the form.

split steeple
#

Ah ok

runic heart
#

i need help whit flask t-t

copper patrol
#

How do I clean a table in Django? I need to perform it just once, so I don't want to write python files for it

dense slate
#

Meaning remove all the entries?

#

You can create a function that simple loops through and deletes all the entries. I am trying to remembers.. I think they're called manager functions?

#

Or you can do it manually of course with db commands on the server.

quick schooner
#

hello how to install requests in my jupyter notebook please ?

copper patrol
#

How? I removed a column from my table and there are some errors connected to it

copper patrol
#

@quick schooner "!pip install"

quick schooner
#

ok but where to do that in my jupyter notebook ?

#

i have my .iypnb file

copper patrol
#

In a cell

#

Create a cell and type in there

#

"!pip install any-package"

quick schooner
#

ohhhh

copper patrol
quick schooner
#

working thanks !

#

in your terminal use python3 manage.py dbshell

#

from models import yourmodel

#

Model.objects.all().delete()

#

this will delete all entries for this model

copper patrol
#

Em, but isn't it sql shell?

#

@quick schooner

quick schooner
#

i think dbshell works

copper patrol
#

I mean, it seems to be not accepting python

quick schooner
#

let me try

#

ok it is just shell not nbshell

#

sorry

copper patrol
#

Ah

#

Should I save it now?

quick schooner
#

you want to delete all entries from a model right ?

copper patrol
#

Yeah

quick schooner
#

so this should work yes

copper patrol
#

Aha, thanks

quick schooner
#

yourmodel.objects.all() loads all the entries

#

add .delete() and it deletes all entries

copper patrol
#

Makes sense

quick schooner
#

make sure u import your model first with from models import yourmodel and you are good to go

copper patrol
#

Yeah I did it all, now they all are deleted, cool. But it didn't help my initial problem ๐Ÿ˜ฆ

#

So the problem I'm talking about is that after I removed a column from a table, in the admin's panel I can't access the table

#

Neither I can add, nor remove elements

#

I get an error "OperationalError at /admin/..."
And "no such column: my_column_mycolumn.price_range_from"

#

Don't you know the issue?

#

The thing is, it works just fine on my local machine, just doesn't work in the production for some reason

native tide
#

hi
im trying to show an PDF in my browser with flask..my problem...my route only starts the download... is this possible? without something like pdfjs?

rotund token
#

#discord.js

hoary marlin
#

Hey guys!
suppose In a flask project I have an event.html form where the user enters his details i.e. Username and Phone no.
now if I need those username and phone no. in another page what should I do?

in my case the Student enters STUDENTID and SportsID and gets redirected to the Sdata page.
Sdata page will display all the details about student with the help of above parameters. How would I pass those StudentID and SportsID which I have taken as an input in event.html form to Sdata page?

warm igloo
# native tide hi im trying to show an PDF in my browser with flask..my problem...my route only...

You actually don't have much control over this, as it will vary browser to browser and machine to machine for your clients. They may have PDF readers set up or they may not. They may have Acrobat Reader as a full app or plugin or Chrome may say "I'll open everything in a window and never start a download until requested".

Now, of course, it also matters how you're sending it. Are you just redirecting to a static PDF file that is on your server, a dynamic one that you're generating on the fly and you're just streaming to the user, or what? If this is the case, you may just have the wrong headers being sent.

swift sky
#

not sure where to ask this

#

but i have some string data stored in mysql

#

I would like to preserve its formatting

#

like indentations

#

someone is copy pasting a word document into a text box in my webpage, and that data is then stored in a mysql

#

db

#

but id like to preserve formatting

dense slate
#

You would need something to indicate the markup.

#

Like, strings throughout the text that specifically render spaces or other indentation (spaces not so much but other more specific stuff)

#

And then probably render that with javascript on the front-end.

swift sky
#

interesting

#

any particular libs to look at?

dense slate
#

Not off the top of my head. Maybe look at how escaping works in javascript, or look up libraries for markdown.

swift sky
native tide
#

Could anybody who has gotten a career in web-dev shed some light on when you should start applying to jobs? Atm I've only done one project (Django + React note-taking app) and I'm working on another project which would integrate with an eBay/Amazon seller's account and calculate their tax returns from their business stats and spreadsheets.

These projects take a long amount of time and I'm torn up with imposter syndrome whether it's viable to apply to jobs or not with only 2 projects.

gaunt yarrow
#

Hi guys! Is there any solution to run a task with timer? Not exactly a cron job, for example when I create a payment instance, I want to set a timer say 24hrs, and after 24hrs will run a task to expire that payment, like a set timeout callback, not sure how to do it. Im using Django BTW.

blissful crest
#

Hey, does anyone know of a resource to use CPython with beautiful soup? My boss is about to have me working on a webscraping project and I want to try to optimize with cpython

#

Is the data returned a string?

odd swallow
#

hi , how do i deploy backend to heroku if my github repository has a structure like so

root
---backend(flask)
---frontend(react)

From what i m reading, heroku needs the app in the root directory
error i'm getting ! [remote rejected] main -> main (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/anagramcheck.git'
repo: https://github.com/Leeoku/anagram

native tide
#

Hi, does anyone know how to add these 3 python dictionaries to a list? I have tried but I can only get the last one in a list. I see they are not separated by a comma. Any help would be great!

gaunt marlin
#

@native tide you can use python append()

your_list = []
your_list.append(your_dictionary)
native tide
gaunt marlin
native tide
gaunt marlin
#

!codes

lavish prismBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

native tide
gaunt marlin
native tide
thin dome
#

how to use our created tables in psql with django

#

???

gaunt marlin
#

the for loop loops 3 times right?

thin dome
#

@gaunt marlin can you answer me?

gaunt marlin
thin dome
#

thanks

native tide
gaunt marlin
native tide
primal kernel
#

Hey guys quick question!

I'm using the django library django-maintenance-mode. This library is used to put the page in maintenance mode (thank you Angel).
The thing is that it has a config param called:

MAINTENANCE_MODE_IGNORE_URLS = (HERE IS WHERE I NEED HELP)

The docs says this

list of urls that will not be affected by the maintenance-mode
urls will be used to compile regular expressions objects
MAINTENANCE_MODE_IGNORE_URLS = ()

The only page that I don't want to be in maintetance mode in the login page because the admins will need to log in and the maintenance won't affect them.

That param is in the settings.py file. My problem is that I don't know what I have to write in the parenthesis to avoid the login page to be in maintenance mode.

This is my folder strucutre

core
โ”ฃ settings.py
authentication
โ”ฃ urls.py

And this is my urls.py file:

urlpatterns = [
path('login/', login_view, name="login"),
path('register/', register_user, name="register"),
path("logout/", LogoutView.as_view(), name="logout")
]

thank you guys ๐Ÿ™

naive phoenix
#

hi

devout coral
#

Anyone here have some experience with Traefik?

harsh marlin
#

can you make a professional website using django?

dapper tusk
#

instagram is a lot of django, so yeah

summer egret
#

Hi

#

Someone working in some open source project using django?

#

I have a little exp of DJango

#

And want to level up by contributing to open source projects

dapper tusk
#

you could look into contributing to our website, I think we have some good first issues, though I am not 100% sure.

native tide
#

hello

#

My Question Is :

#

in below script
def create_app(test_config=None):

what is test_test config Explain why it's used here

#

import os

from flask import Flask

def create_app(test_config=None):
# create and configure the app
app = Flask(name, instance_relative_config=True)
app.config.from_mapping(
SECRET_KEY='dev',
DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'),
)

if test_config is None:
    # load the instance config, if it exists, when not testing
    app.config.from_pyfile('config.py', silent=True)
else:
    # load the test config if passed in
    app.config.from_mapping(test_config)

# ensure the instance folder exists
try:
    os.makedirs(app.instance_path)
except OSError:
    pass

# a simple page that says hello
@app.route('/hello')
def hello():
    return 'Hello, World!'

return app
native tide
#

!code

lavish prismBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

worthy quest
#

hey everyone

#

I have a question

granite loom
#

ask away

spiral blaze
#

is flask backend??

#

do i have to learn JS or something

worthy quest
#

I have done a website by HTML,CSS, and JS and I have uploaded it at my domain at one.com
unfortunately the line will be %%%.com\index.html

#

are they anyway to make it at a home page that doesn't says
%%%.com\index.html but only be %%%.com

compact flicker
#

Is there a way to get the client's mac address using django backend...?

worthy quest
#

I hope one day someone will answer me

tender gust
#

@compact flicker MAC addresses are used in ethernet, so only in local network range, all you can get is MAC address of your gateway (ip router)

compact flicker
#

Ok...
then is there a way to get IPv6

tender gust
#

try request.META['REMOTE_ADDR']

past cipher
#

connection to a remote mysql database times out when doing a post request. How can I capture the exception and get flask to redirect else where when this happens?

#
@main_bp.route('/record/update', methods=['POST'])
def update_record():
    try:
        ## some code here to check if the record has already updated
        ## some code here to update record if it hasn't
    except Exception:
        ## some code here to check if the record has already updated
        ## some code here to update record if it hasn't
#

Not catching the exception

#
2020-12-10T16:54:01.517184+00:00 app[web.1]: [2020-12-10 16:54:01,500] ERROR in app: Exception on /db/update/record [POST]
2020-12-10T16:54:01.517195+00:00 app[web.1]: Traceback (most recent call last):
native tide
#

i need help with django

past cipher
#

Anyone used WTForms with Flask

#

I am trying to get the validation error

#
if not AdminRegister().validate_on_submit():
        print(AdminRegister().email.errors)

returns empty dict

#
if not AdminRegister().validate_on_submit():
        print(AdminRegister().errors)

returns empty dict

#
if not AdminRegister().validate_on_submit():
        print(AdminRegister().errors.items())

returns empty dict

#

why config.update

#

and not app.run

#

yeah I use that too for my projects, but never had to use config.update

#

Normally setup app name in init, and then have a run file if I'm using it locally with debug set to true

#

Honestly I'm not sure

quick schooner
#

hello

#

is there a better way to do this please ?

#
    e_home = e.filter(Q(home_team__abbreviation=team))
    e_away = e.filter(Q(visitor_team__abbreviation=team))
            
            odd_array = []
            for event in e_away:
                try:
                    odd = event.bet.all().first().home_opener_odd
                
                    if odd != None: 
                        odd_array.append(odd)
                except : 
                    pass
                
            print(odd_array)
            print(np.mean(odd_array)) ```
#

trying to get the average of a field of a model which is linked to another model with a foreignkey

rare oar
#

Hey all, if I wanted to use Rank() I can annotate it into a queryset and display it

#
def leaderboard_queryset() -> QuerySet:
    rank_window = Window(expression=Rank(),
                         order_by=F('elo').desc())
    board = (
        Leaderboard
        .objects
        .select_related('profile')
        .order_by('-elo')
            .annotate(name=F("profile__name"))
            .annotate(rank=rank_window)
            .annotate(win_rate=Case(
            When(games=0, then=0),
            default=(Decimal('1.0') * F("wins") / F("games")) * 100,
            output_field=DecimalField(),
        )
        )
        # How can I preserve Rank if I was to do something like this?
        .filter(profile__name__icontains="Drac")
    )
    return board
#

However now I have quite a few entries where I'm adding in server side pagination and a search. Is there a way to preserve the rank from the entire dataset rather than the filtered data set?

gaunt marlin
#

hello, can you be more specify? are you talking about django form validation or custom error message?

gaunt marlin
#

actually that is html feature, when you set blank=Flase the html input will rendered with required in the form, for example it will render like so <input type="text" required>. If you rendered with django form then the validator will still kick in, you can see the validation error with {{ form.your_field_name.errors }} in the template, but it will show after you submitted the form.

#

also the validation only kick in for forms.ModelForm, not forms.Form

stable kite
#

I have an custom authentication for user. But also I want authentication for developers who are using my API. So how to implement two authentication in DRF.

nova vortex
#

Jwt

gaunt marlin
#

and yes you can have multi authentication with adding those custom class in settings.py:

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ]
}
stable kite
gaunt marlin
stable kite
#

i have created as per drf documentation

#

@gaunt marlin My problem is if the first is for User & the second one for developer than drf runs user only & not developer one

gaunt marlin
stable kite
gaunt marlin
# stable kite that's what my question is how to do that?

i took a look at the docs and at this part

The method should return a two-tuple of (user, auth) if authentication succeeds, or None otherwise.

In some circumstances instead of returning None, you may want to raise an AuthenticationFailed exception from the .authenticate() method.

Typically the approach you should take is:

If authentication is not attempted, return None. Any other authentication schemes also in use will still be checked.
If authentication is attempted but fails, raise a AuthenticationFailed exception. An error response will be returned immediately, regardless of any permissions checks, and without checking any other authentication schemes.

you need to return None on your User authentication class so it can run the other

stable kite
#

as user is not None after running user authentication

gaunt marlin
#

i don't have my pc with me so i can't test but it's what the docs described

stable kite
#

@gaunt marlin My first authentication (User) returns (User,None) & second authentication(developer) returns (None,Developer).But drf only runs the next class when both are None. Which is not possible in my case

gaunt marlin
#

@stable kite i think you supposed to return None, not the tuple of (User, None) (if the authentication failed on it)

#

@stable kite this is what i mean

first_authentication_class():
    if ok:
        return (User, None) # this will stop the flow
    else:
        return None #so it run to the second authentication class

second_authentication_class():
    if ok:
         return (Developer/User, None) # this will stop the flow
    else:
        return AuthenticationFailed() # now we done with checking
#

The method should return a two-tuple of (user, auth) if authentication succeeds, or None otherwise.

stable kite
gaunt marlin
dreamy seal
#

hi is there any free design tool for front end develop. I am not that intrested in design stuff but is there any tool that can be used?

glacial orchid
#

@dense slate
1.I want to change the text-decoration of a link inside a div in my article.
2.there is this called 'user style sheet' which has default text-decoration : underline.
3.I wish to make text-decoration:none. But my change is not executed.
4.help me ๐Ÿ™

native tide
#

@glacial orchid refresh your browsers cache to manually update any CSS changes if it doesn't do it for you. If it's not as desired then theres an issue within your CSS

echo mesa
#

I'm having trouble using Flask and Jinja2 forms

#

I'm creating a site for school which has a SelectField of the grade and then I have a selectfield of the class number I want the select fields options to be for example
B'5
where B is the grade and 5 is the class number but I don't know how to do some

class whosTableForm(FlaskForm):
    classesPerGrade = {'ื˜': genNumbers(16), 'ื™': genNumbers(17), 'ื™ื': genNumbers(18), 'ื™ื‘': genNumbers(17)}
    Grade = SelectField("ืฉื›ื‘ื”", choices=['ื˜', 'ื™', 'ื™ื', 'ื™ื‘'])
    Class = SelectField("ื›ื™ืชื”", choices=classesPerGrade['ื˜'])
    Capsule = SelectField("ืงืคืกื•ืœื”", choices=["ื’ื•ืฉ ื'", "ื’ื•ืฉ ื‘'", "ื›ื™ืชืชื™"])
    Submit = SubmitField("ChooseClass")

This is my Form class but I don't know how to change the choices for Class according to the value selected by Grade

glacial orchid
#

@native tide

haughty turtle
#

How are you implementing the changes? Show a snippet of your code, and for you to change text decoration its in your CSS, press CTRL + F5 after any changes to clear your cache @glacial orchid

formal gull
#
class Room(models.Model):
    partOneDes = models.CharField(max_length=30, blank=True)
    partOne = models.CharField(max_length=30, blank=True)``````py
class RoomSerializer(serializers.ModelSerializer):
    class Meta:
        model = Room
        fields = ('id', 'partOneDes', 'partOne')``````py
class RoomView(generics.ListAPIView):
    queryset = Room.objects.all()
    serializer_class = RoomSerializer```could someone explain why this ends up saving all of my entries in the api? i am looking to not have them saved since i do not need to store all of this data. i just need to use it once and then it can be gone essentially. (worried about future storage) https://gyazo.com/2dcb149782f3affed190d18a750ec025
#

would deleting it after it is done being used just be the way to go here?

near bison
#

How do i store phone number with django model with a validation

#

do i have to use Charfield and write a regex myself

near bison
#

Why am i able to create two entries in a table with same primary key during testing

near bison
#

and some of the field specific validations also seems to be not working during testing

past cipher
#

show code

native tide
#

@near bison Charfield w/ RegexValidator or import a module for a phone field

near bison
#

The model ?

versed python
#

There's a package called Django phone number field. It works pretty well.

balmy spruce
#

Having trouble finding something simple. I'm trying to demonstrate how variables work within templates.

I have this example:

<p>
For instance, "Hello {{request.user}}!"
</p>
<p>The above username was rendered out by inserting <code>{{request.user}}</code>.  

I want the display to show {{resquest.user}} as the raw code {{request.user}}.

I'm just having trouble finding info on how to do that.

#

I thought it would be something as simple as a filter

slim night
#

maybe by sending this string {{request.user}} as a value argument to the template

balmy spruce
#

Sorry, I just realized I forgot to say I'm using Django

slim night
#

in the render function

balmy spruce
#

@slim night yeah, that works but I want to do it on the fly

dense slate
#

<p>"{% templatetag openvariable %} some text {% templatetag closevariable %}"</p>

frozen python
#

Does anyone use Django and Strapi.js?

balmy spruce
#

@indigo kettle perfect! exactly what I was looking for.

#

follow up question. I can get away with

{% verbatim %}
  {{request.user}}
{% endverbatim %}

as opposed to

{% verbatim someblock %}
  {{request.user}}
{% endverbatim someblock %}

Is that bad practice?

indigo kettle
#

no

#

it's fine

#

you just have the ability to name the block in case you want to write the verbatim tag inside of the block

native tide
haughty turtle
#

@native tide Wrong server?

near bison
#

If i use PhoneNumberField as the primary key and i try to delete multiple users from the admin panel. i get the error that '<' is not supported between two PhoneNumber instances (in django)

#

And why does python test let me create non valid phone numbers in phone number fields

stable kite
stable kite
boreal drum
#

when hosting a aiohttp thing on heroku what should i put in as the address

boreal drum
#

rn im just throwing in "localhost" as the address and port 5000 and I just get the application error message from heroku

nova vortex
#

perhaps it is misconfigured

dreamy seal
#

hoes google web designer?

#

is there any software for front end dev?

nova vortex
#

?

dreamy seal
# nova vortex ?

i am not that intrested in designing web site. is there any software i can use that could help me with this?

nova vortex
#

design how

#

structurally?

naive crater
#

hey anyone know why I'm getting this error:

Application object must be callable.
2020-12-12T05:20:22.909496+00:00 app[web.1]: [2020-12-12 05:20:22 +0000] [9] [INFO] Worker exiting (pid: 9)
2020-12-12T05:20:26.000000+00:00 app[api]: Build succeeded
2020-12-12T05:20:52.999760+00:00 app[web.1]: [2020-12-12 05:20:52 +0000] [4] [INFO] Shutting down: Master
2020-12-12T05:20:52.999851+00:00 app[web.1]: [2020-12-12 05:20:52 +0000] [4] [INFO] Reason: App failed to load.
2020-12-12T05:20:53.069213+00:00 heroku[web.1]: Process exited with status 4
2020-12-12T05:20:53.111871+00:00 heroku[web.1]: State changed from up to crashed
2020-12-12T05:22:26.435188+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=hurbapi.herokuapp.com request_id=3783bd56-c1f7-4c93-91b3-0c29754418d1 fwd="69.181.8.147" dyno= connect= service= status=503 bytes= protocol=https
2020-12-12T05:22:26.567586+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=hurbapi.herokuapp.com request_id=1323c415-8459-437e-830f-ed787077e82c fwd="69.181.8.147" dyno= connect= service= status=503 bytes= protocol=https
2020-12-12T05:22:30.253251+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/settings" host=hurbapi.herokuapp.com request_id=91995d00-c400-4bb9-8732-513336cd07a9 fwd="69.181.8.147" dyno= connect= service= status=503 bytes= protocol=https```

from this simple code:
```py
import json
from flask import Flask, make_response, jsonify

app = Flask(__name__)


@app.route('/settings', methods=['GET'])
def settings():
    with open("servers copy.json") as f:
        storage = json.load(f)
    return jsonify(storage), 200




if __name__ == "__main__":
    app.run(host='0.0.0.0', port=port, debug=True, use_reloader=True)```
true scroll
#
task = logs.query.filter_by(typeVA='V').first()
#

flasksqlalchemy i wanna add secondary filter

#

id == request.form['id_client']

nova vortex
#

perhaps you forgot to set env variable for flask

limpid salmon
#

Are there any plug and play mongodb backends for django?

#

I could find djongo(www.djongomapper.com) but several features like transaction, text search, etc are paid.

#

django-mongoengine is opensource, but looks outdated

rose phoenix
#

hello

#

i want to make an online pdf to docx converter with Django is there any project or online resources from which i can start learning?

rose phoenix
#

yes

#

i had make todo list

#

so not too much

#

but i can learn

halcyon lion
#

Eyo boys, can someone give me a hand here. I have form that creates recipes and i have a creator field which should display the user that created it

#

i have a user = models.ForeignKey(UserProfile, on_delete=models.CASCADE) in the model

#

but on the creation page it gives me the choice to pick every user i have registered ๐Ÿ˜„

#

i want to be limited to just anonymous or the current logged in user

cosmic aspen
halcyon lion
#

yeah but idk ๐Ÿ˜„

#

i want to add some dependencies based on this author field

cosmic aspen
#

then some if statements in the view and some in the template html and you can have some customised logic runnig

halcyon lion
#

my play apparently is to overwrite the validation

#

so it sets the user before it validate

halcyon lion
#

Cannot assign "<SimpleLazyObject: <User: stefan>>": "Recipe.author" must be a "UserProfile" instance.

#

def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)

#

i am lost ๐Ÿ˜„

twilit needle
#

django help pls

#

So this is my custom manager class and model

#

however,when I try to make migrations I get the following error

#
  File "C:\Users\iyapp\OneDrive\Desktop\python projects\DataSheet-ledger\backend\models\__init__.py", line 2, in <module>
    from .data_sheets import DataSheetsCluster, DataSheetsCategory, DataSheet, DataSheetField, ForeignKeyField, FieldData
  File "C:\Users\iyapp\OneDrive\Desktop\python projects\DataSheet-ledger\backend\models\data_sheets.py", line 233, in <module>
    class FieldData(models.Model):
  File "C:\Python39\lib\site-packages\django\db\models\base.py", line 161, in __new__
    new_class.add_to_class(obj_name, obj)
  File "C:\Python39\lib\site-packages\django\db\models\base.py", line 326, in add_to_class
    value.contribute_to_class(cls, name)
  File "C:\Python39\lib\site-packages\django\db\models\manager.py", line 113, in contribute_to_class
    self.name = self.name or name
AttributeError: 'RecordDataManager' object has no attribute 'name'
#

Why?

#

Can someone pls help me?

#

Pls ping me when help!

#

thanks!

stable kite
stable kite
# twilit needle ```py File "C:\Users\iyapp\OneDrive\Desktop\python projects\DataSheet-ledger\b...

it should be like

class RecordDataManager(models.Manager):
    """
    A manager class to deal with Cluster Size Limits,
    Field DataType Validation and JSON.dumping raw data.
    """
    def __init__(self):
        self.data_type_validators = {
            'BOOLEAN': BooleanValidator,
            'INTEGER': IntegerValidator,
            'FLOAT': FloatValidator,
            'CHAR': CharValidator,
            'DATE_TIME': DateTimeValidator
        }
        self.max_record_kilobyte_size = 2500
        return super().__init__()

    def validate_data_type(self, data, field_id: int):
        """
        Checks if the provided data suits the dataType
        of the given field. Raises a ValueError if the requested field doesn't exist.
        """
        ref_field = DataSheetField.objects.get(id=field_id)
        return self.data_type_validators.get(ref_field).validate(data)```
scenic dove
#

โ˜๏ธGreat books for learning Django
@native tide
Thanks

echo mesa
#

Is there a way to disable request timeout?

#

specificly in Flask

halcyon lion
#

no idea ๐Ÿ˜„

twin finch
jade salmon
#

Hey I finished learning basic web scraping wid Python.

#

I wanna try out django or flask now

#

Which one should I learn and from what are the best rss?

high sable
#

How to connect python django communication between .net core web project??

nova sparrow
#
def register():

    """Register user"""
    # Forget any user_id
    session.clear()

    # User reached route via POST (as by submitting a form via POST)
    if request.method == "POST":

        # Ensure username was submitted
        if not request.form.get("username"):
            return apology("Enter a Username Or Username already exists", 403)

        # Ensure password was submitted
        elif not request.form.get("password"):
            return apology("Password does not match", 403)

        password = request.form.get("password")
        confirm_password = request.form.get("confirm_password")

        elif password != confirm_password:
            return apology("Passwords does not match!", 403)
#

after running flask

#

i get this error

#

how is it invaid pls help me

quick cargo
nova sparrow
#

ok

drifting furnace
#

!code

lavish prismBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

native tide
#

@nova sparrow Also if you're using WTForms you should have validation done within your form model, instead of the view. Such as ensuring that the fields are not empty.

marble gate
#

hey guys has anyone else ever had errors installing scrypt

limber laurel
#

Hello, I currently have an application where you can monitor your calorie intake and it also suggests plans, I am wondering maybe someone could recommend features I could implement, that would make me learn more about web dev in general and django.

glacial orchid
#

@native tide @dense slate
look at the 'user agent stylesheet'
look at the body of html
and look at the css
I did the same thing for two ancher tag but one is working and other is not
please help
default value of Blog link is changed but not of title link although I did same thing for both of them.

#

above user agent stylesheet is for author

#

this one is for blog link

#

and here is the template in action

#

I hope its enough explanation for anyone to understand

true scroll
#
werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.
KeyError: 'item'
#
    elif request.method == 'POST' and request.form['type'] == 'remove':
        db.session.delete(stock(name=request.form['item']))
        db.session.commit()
#
        {% for task in task %}
        <tr>
            <td> {{ task.name }} </td>
            <td> {{ task.quantity }} </td>
            <td>
                 <form action="/makhzon/" method="post">
                <input type="hidden" name="type" value="remove">
                <button>
                    ุญุฐู
                    <input type="submit" name="item" value='{{ task.name }}' style="background: none; color: white; cursor: pointer; outline: none; border: none" />
                </button>
            </form>
         </td>
        </tr>
        {% endfor %}
#

help pls

zinc hill
#

what is a good practice to get a new access_token? should i just do call getNewToken every 5 mns? or ....?

coral raven
#

@glacial orchid why is the selector so long?

.profile a, .title a{
    text-decoration: none;
}```
glacial orchid
coral raven
#

Something is overriding your style

#

Try adding inline style with !important @glacial orchid

sudden grail
#

hey hey, I'm interested in a question what you guys think.

#

is django a good career option?

#

because somebody said me it's not 2010 anymore, so..

glacial orchid
glacial orchid
coral raven
#

Inline styles

#

In the HTML file

#

In the a tag
<a style="text-decoration:none !important" href="#">Home</a>
@glacial orchid

glacial orchid
coral raven
#

@native tide include segoe UI's font link in your html or css file

final sequoia
#

yo can someone check out my project? https://github.com/hanyuone/kanban i'm trying to do put requests (in frontend/index.js) with django but it doesn't seem to update the database

wild junco
stable kite
final sequoia
#

uh react's on localhost:3000 and django's on :8000

glacial orchid
#

thank You

coral raven
#

You know why it worked?

native tide
#

where should I put json file in django project to get that in app's views.py?

final sequoia
#

@stable kite didn't get an error, the put request returns 200 but it doesn't actually update the values in the db

haughty turtle
#

@native tide you want to store a JSON file on your server and grab it later on directly ?

native tide
#

what's the best practice?

haughty turtle
#

but where are your obtaining this data from? are you obtaining it from the client and sending it through fetch? is this something that you can save under a model there is a JSONField model.

native tide
#

nah I have the json file

buoyant willow
#

What's the proper way to let Users create shareable content in Django? For example "User A" create a "Project" and lets "User B" and "User C" as admins (read and write rights) and "User D" as member (read rights) and all others users can only see the name of the project.

near bison
#

Why is get_user_model() function used in django ?

#

why can't i just import the User model myself

glacial orchid
mental prawn
#

do you guys have any suggestions on where i can learn web developmnet using python ONLY

quick cargo
mental prawn
quick cargo
#

django is just a backend

#

you still got frontend

random lava
#

Hi, is flow the go to py module for web development?

native tide
#

well

#

depends on what you want

#

ngl

quick cargo
native tide
#

Quart/Flask is a great starter framework

#

for security, use DJango

#

for advanced, use aiohttp

quick cargo
#

meh security in Django is no better than any other

native tide
#

if your a show off...create your own framework

native tide
quick cargo
#

sync frameworks:

  • Django
  • Flask
  • Bottle
  • some others

async frameworks:

  • FastAPI
  • Quart
  • Sanic
  • AioHTTP
  • Starlette
  • Japronto (no longer maintained)
  • flacon
  • some others
quick cargo
native tide
#

its only what I have heard tbh

#

ive never been able to get the jist of it

native tide
#
@app.route("/images/<variable>")
def main_page(variable):
    return (f'<img src="C:/Users/scorz/Desktop/images/{variable}">')

why doesnt this work?

#

i get this

#

yes the path is right

noble smelt
#

It's generally not good practice to use full path for an image

#

Try using a relative path

#

Try using alt attribute as well for testing

native tide
#

either wont work @noble smelt

maiden tulip
#

starting with web developing with the goal of becoming a fullstack dev, I guess I should use Django. Question is: I heard that Django is not the best choice for frontend. Do you recommend using another frontend framework and which one, or should I first learn frontend in django and later swap to another framework like react?
Do react and django combine well or how is it done?

native tide
#

Well backends that pair well with react would be the ones that are also in JS, so node.js (specifically express).

#

I'm using a Django backend with a React frontend and actually it's not too hard to combine them together

#

I have django render one page when the user visits the site and the rest is handled with React (technically as an SPA) and with react-router

#

can anyone tell me on how to configure/setup selenium grid 5 for threading/multiproccesseding

stable kite
lime flower
#

Having some trouble getting this JS script to work, any suggestions? ```const img = document.getElementsByClassName('clickpet');
const textBox = document.getElementById('textBox');

img.onclick = popup(){
console.log('clicked on');
};```

#

At line 4 (the { key), I get an error, ';' expected.

next pelican
#

hey guys I am Shaish Guni And I have a question how should I start web development on python using django and flask

native tide
#

flask is easier to learn

#

DJango is a bit more complex but also a good learning curve

wide plume
polar aurora
#

how can i get a personal url?

proper hinge
#

What's a personal URL?

polar aurora
#

i want a url for the website designed by me.......with html

proper hinge
#

You mean you want to know how to host your website on the internet?

polar aurora
#

yah something like that!

#

because my code is running on local host

proper hinge
#

Hosting usually costs money, but there are some free hosting options.

#

Do you have a web server already?

polar aurora
#

like?

#

nope!

#

what is that?

polar aurora
proper hinge
#

Check out "pythonanywhere". If I remember correctly, they're targeted mainly towards hosting websites in Python. A different option is "GitHub Pages", which can host static web pages.

#

A web server is a computer connected to the internet that will host your website and allow people to connect to it.

polar aurora
#

ohhh i see

#

so is it is basically a computer right from where i'm writing my xml?

#

huh? @proper hinge

proper hinge
#

No. Where you write the code and where it's hosted aren't necessarily the same.

light gale
#

Hey guys, I have an old website just using basic html/css/js on a lamp stack, but I want to make the webpage more dynamic with a django backend. I'm trying to figure out if I can re-used the old frontend (css/html basic layout) while still using django, but I can't really find any resources.

#

I'm comfortable with python/html/css/js by the way, just not with the specific implementation/django. Does anyone know a straightforward way/resource to achieve this?

zinc hill
#

@light gale i think u can look up literally any youtube vids on django project it would show you how to do that

light gale
#

Most existing projects create or use a 'template', I would like to re-use as much of my frontend as possible.

#

or am I thinking weirdly? Maybe it is easier than it seems to me

zinc hill
#

ohhh I think u need to look into Django rest_framework

#

i am assuming you want ur Django only as backend right?

#

so this way ur front-end can just http request stuff to django back-end right?

light gale
#

Yes exactly

#

I have a 'website' set up using html/css/js, and I just want to connect some nice things using Django

zinc hill
#

yeah rest_framework django would be the way to go

light gale
#

for instance, grab my twitter feed autoamtically and update divs accordingly etc.

#

let me take a look, thanks

gaunt marlin
#

@light gale if you want your webpage to be dynamic, Ajax work nicely with Django Rest Framework API

rough tulip
#

When I am trying to send mail in django it shows "No connection could be made because the target machine actively refused it"

gaunt marlin
#

@rough tulip you probably didn't set up email backend config in your settings.py

rough tulip
#

I did

#

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_USE_TLS = True
EMAIL_PORT = 587
EMAIL_HOST_USER =''
EMAIL_HOST_PASSWORD = ''

mint folio
#

Does anyone know if it's possible to override the from address in an office 365 email? In one of applications I can get it working with a different provider, but with o365 i get a load of errors.

light gale
#

so in Django, I created a post class which contains information about what I want to display on my index.html. loading 'posts' on index is working, but I now manually define my posts here (views.py):


# Create your views here.
def index(request):
    #return HttpResponse('createpost/index.html')
    post1 = Newpost()
    post1.desc = 'test'
    post1.url = 'https://www.google.com'
    post1.date = '20 JAN'
    post1.target = '_blank'

    posts = [post1]

    return render(request, 'createpost/index.html', {'posts': posts})
#

I'm using the default sqlite3 database, I'm guessing I want to store the posts in there and pull it? I'm not sure where to find info on how to do this though, can someone send me in the right direction?

#

I probably need to do that in models.py then, for reference, this is the code there:

#
from django.db import models

# Create your models here.


class Newpost:
    url : str
    date : str
    desc : str
    target : str
native tide
crimson hornet
#

Hello I'm Will

native tide
#

Hello

crimson hornet
#

Can I do web Dev in python without using any framework?

echo mesa
#

Since the help channels are off I'll try my luck here...

#

I need help with Flask and WTForms
I'm trying to create a table which each <td> contains a select
and on POST I want it return the data of the entries, I'm trying to do so using WTForms FieldList

                <tbody>
                    {% for hour in range(1, 12) %}
                        <tr>
                            <td>{{ hour }}</td>
                            {% for day in range(6) %}
                            <td>
                                {{ template_form['schedule'].TwoDTable[6 * (hour - 1) + day].form.Lesson() }}
                            </td>
                            {% endfor %}
                        </tr>
                    {% endfor %}
                </tbody>

This isn't working but I don't know how to make it work...
This is my Form.py:

class lessonForm(FlaskForm):
    Lesson = SelectField('lesson', choices=args.Lessons, render_kw={"Class" : "lesson"})

class scheduleTableForm(FlaskForm):
    TwoDTable = FieldList(FormField(lessonForm), min_entries=1)
    submit = SubmitField('Submit', render_kw={'value': 'ืขื“ื›ืŸ'})

and how do I pull the data in app.py

gray wraith
#

what are the best resources to learn gevent ?

steel reef
#

How can I add pagination to tables in Django?

open owl
#

Hello guys, am kinda free and need to work on someone's Django project. If you feel needing help, kindly DM me. Its free!

echo mesa
#

Anyone here familiar with Flask and WTForms?

#

I really need help :/

open owl
echo mesa
#

for some reason when I place my Field it also places a label is there a way to disable it?

echo mesa
#
            <table>
                <thead>
                    <tr>
                        {% for day in range(8) %}
                        <th>
                            {{ days[day] }}
                        </th>
                        {% endfor %}
                    </tr>
                </thead>
                <tbody>
                    {% for hour in range(1, 12) %}
                        <tr>
                            <td>{{ hour }}</td>
                            {% for day in range(6) %}
                            <td>
                                {{ template_form['schedule'].TwoDTable[6 * (hour - 1) + day] }}
                            </td>
                            {% endfor %}
                        </tr>
                    {% endfor %}
                </tbody>

            </table>

This is the table part, for my understanding I only place the object that is contained in the FieldList TwoDTable

#
class lessonForm(Form):
    Lesson = SelectField('lesson', choices=args.Lessons, render_kw={"Class" : "lesson"})

class scheduleTableForm(FlaskForm):
    TwoDTable = FieldList(FormField(lessonForm), min_entries=66, max_entries=66)
    submit = SubmitField('Submit', render_kw={'value': 'ืขื“ื›ืŸ'})

#

I do not understand why it adds a label

echo mesa
#

Also Is there a way to pass it a parameter?

#

I want it to have an ID of which Select field it is

open owl
#

class NoLabelClass(object):
    def __init__(self, *args, **kwargs):
        super(NoLabelClass, self).__init__(*args, **kwargs)
        for field_name in self._fields:
            field_property = getattr(self, field_name)
            field_property.label = None


class lessonForm(Form):
    Lesson = SelectField('lesson', choices=args.Lessons, 
render_kw={"Class" : "lesson"})

class scheduleTableForm(FlaskForm):
    TwoDTable = FieldList(FormField(lessonForm), min_entries=66, max_entries=66)
    submit = SubmitField('Submit', render_kw={'value': 'ืขื“ื›ืŸ'})

class NoLabelForm(NoLabelClass, scheduleTableForm):
    pass

my_no_label_form = NoLabelForm()

keen acorn
#

Hey guys, I am still "new" to Django and I was trying to make a website that was integrated with discord. I already have everything built up so that if someone is given a role in our discord server, that roles gets associated with the "Member" model

#

I also figured out how to implement my own user models so I could use exclusively discord login

#

The last part I cant seem to find a solution or docs on how I would so that is the "Groups"

#

I want so that the "Roles" are the "Groups"

#

But I am not really sure how to reimplement that feature like I did with the Users model

#

If anyone had to do this in the past or knows something that could help me x)

native tide
#

@keen acorn you can link the Roles and the Groups models together with a OnetoOne field

vast locust
#

hello, in flask or builtin have something like "readfile" from php? I want download files directly from url, with headers in php it is possible. In python i can use urllib for that reason. But then i need first download file to server.

swift sky
#

im so confused by all these flask wrappers

#

like why do flask_user and flask_login both contain a login_required function

#

all im trying to do is manage user access based on roles

#

i have no clue what best practices are with all this overlap

deep mason
#

hey guys, does anyone here have experience with flask? Because I have a module, and I dont want to pass it every time as an argument in every render_template() func, wanted to ask here how I can set it as an environment variable or something so it will be automatically passed in every template in flask

#

Something like the current_user object. I dont have to pass that every time as an argument in my render_template function, but can access it in my templates

light gale
#

Hey guys, I'm doing the following stupid thing:

#

which is: ```html
<div class="grid-container-2">
<div class="Date-2"><p>Dec '20</p></div>
<div class="Text-2"><p>Today, the 14th of december 2020, I decided not to invest $5000 in BTC, and instead spend it on more worthwhile things. At the current rate, this means I have lost out on ${{price}} in profit.</p></div>
</div>

#

but when I try to implement it within my 'news' posts:

#
                    {% for new in news %}
                    <div class="grid-container-2">
                        <div class="Date-2"><p>{{new.date}}</p></div>
                        <div class="Text-2"><p><a href={{new.url}} target={{new.target}}>{{new.desc}}</a></p></div>
                    </div>
                    {% endfor %}
``` - > the new.desc contains the {{price}} as a string. is there a straightforward way to let it grab the price variable?
#

This is django by the way

native tide
#

@light gale new.desc is a string, and you have {{price}} within that string. You will need to pass that price from your view.

proper hinge
#

I don't think Django will parse the output of a variable and render anything inside that

native tide
#

So, what you could do is:

In your view, retrieve the price, then pass it into your template as a variable (such as price) to then be shown.

light gale
#
def index(request):
    #return HttpResponse('createpost/index.html')
    # post1 = Newpost()
    # post1.desc = 'test'
    # post1.url = 'https://www.google.com'
    # post1.date = '20 JAN'
    # post1.target = '_blank'
    # post1.save()

    posts = list(Newpost.objects.all())[::-1]
    news = list(Newnews.objects.all())[::-1]
    btc = btcresult

    context = {'posts': posts, 'price':btc, 'news' : news}
    return render(request, 'createpost/index.html', context)

def btcresult():
    url = "https://api.coindesk.com/v1/bpi/currentprice.json"
    response = requests.get(url).json()
    price = response['bpi']['USD']['rate']
    result = round((float(str(price).replace(',',"")) - 19065.72) * 5000/19065.72, 2)
    return result
``` this is my view
proper hinge
#

So you have to manually render it

light gale
#

I pass price using the view, but then the text gets loaded as a string

proper hinge
#

Create a template object from the description and render it manually

#

then pass the rendered output to your "real" template

light gale
#
class Newnews(models.Model):
    url = models.CharField(max_length=100,default=None, blank=True, null=True)
    date = models.CharField(max_length=100,default=None, blank=True, null=True)
    desc = models.CharField(max_length=300,default=None, blank=True, null=True)
    target = models.CharField(max_length=100,default='_blank', blank=True, null=True)
``` this is my news template, right?
#

from models

proper hinge
#

That's a model not a template

light gale
#

I just started with Django today, so it's quite fuzzy still.

proper hinge
#

Let me write up an example for you

light gale
#

Nice, that would work!

native tide
#

                     <div class="grid-container-2">
                        <div class="Date-2"><p>Dec '20</p></div>
                        <div class="Text-2"><p>Today, the 14th of december 2020, I decided not to invest $5000 in BTC, and instead spend it on more worthwhile things. At the current rate, this means I have lost out on ${{price}} in profit.</p></div>
                    </div>

Here you are passing price into your template (from your context). Good.

Here:

{% for new in news %}
                    <div class="grid-container-2">
                        <div class="Date-2"><p>{{new.date}}</p></div>
                        <div class="Text-2"><p><a href={{new.url}} target={{new.target}}>{{new.desc}}</a></p></div>
                    </div>
                    {% endfor %}

You are not passing the price. You are passing {{new.desc}} which is a string, and it will be rendered as one.

light gale
#

Thanks Nut, I thought as much, but it is unclear to me how to fix.

#

Mark is suggesting a template

#

so the only template I am using now is the index.html, which is basically the webpage.

#

(and some static entities such as css/js/media)

proper hinge
#
template = Template(desc)
ctx = Context(dict(price="123456"))
rendered_desc = template.render(ctx)

...
context = {'desc ': rendered_desc }
return render(..., context)
light gale
#

I guess this should be added to view.py?

proper hinge
#

If you don't render the description manually, Django just interprets the price in your variable as a literal string, not as template syntax that should be rendered. Hence you were seeing literally {{ price }} in your web browser.

light gale
#

wait, I am stupid. I can just do it muchu easier I think.

proper hinge
#

๐Ÿคท okay

#

But yes, that would go in your view

#

I didn't use the exact variable names you have but hopefully you get the idea

light gale
#

    posts = list(Newpost.objects.all())[::-1]
    news = list(Newnews.objects.all())[::-1]
    btc = btcresult
    news.replace('{{price}}', btc)
#

that would work.

native tide
#

What do you guys think about this landing page? I feel like I'm missing something.

I'm going to add an animated scroll prompt for the user. But if you guys have any additions kindly let me know!

proper hinge
#

Yes it would work but it's not really proper

light gale
#

This is monkeypatched together, but it works.

#

Golden rule of programming, that means it is not stupid.

#

It is clean but too much whitespace

#

or I guess bluespace

#

like look at it 'from afar' -> it is mostly nothing. Maybe go a bit bigger on the text?

native tide
#

Thanks ๐Ÿ‘ I'll go with that, some bigger text and I'll have small interactive trinkets to fill in the whitespace

#

Appreciated

light gale
#

No problem. I'm by no means good at design, so take it with a grain of salt

#

looking sleek so far, gj.

#

new django question:

#
class Meta:
        db_table="Newpost_db"
        db_table="Newnews_db"

class Newpost(models.Model):
    url = models.CharField(max_length=100,default=None, blank=True, null=True)
    date = models.CharField(max_length=100,default=None, blank=True, null=True)
    desc = models.CharField(max_length=300,default=None, blank=True, null=True)
    target = models.CharField(max_length=100,default='_blank', blank=True, null=True)

class Newnews(models.Model):
    url = models.CharField(max_length=100,default=None, blank=True, null=True)
    date = models.CharField(max_length=100,default=None, blank=True, null=True)
    desc = models.CharField(max_length=300,default=None, blank=True, null=True)
    target = models.CharField(max_length=100,default='_blank', blank=True, null=True)

So I just created a new db table newnews, migrated, but it does not seem to work?

#

for some reason, all my newnews items seem to be added to the newpost database.

fossil thicket
#

anyone know what the easiest approach to creating and displaying the following would be:

df = pd.read_csv(
    "https://raw.githubusercontent.com/allisonhorst/palmerpenguins/master/inst/extdata/penguins.csv"
)

mask = (
    (df["species"].isin(["Adelie", "Chinstrap"])) & (df["body_mass_g"].le(3600))
) | df["sex"].eq("female") & df["year"].eq(2007)

df[mask]

so - here I want to be able to display a dataframe on a webpage (or the first 15 rows / something like that), and enable the user to create the mask, i'm not sure how I'd take input of something like that though - I think something like django would be overkill, but as I never touch web stuff I don't know what words to search for in order to find what other tooling enables this sort of thing.

light gale
#

my rest api seems to work, but then it just gets added to the newpost table instead. I probably just missed something, anyone have an idea?

light gale
fossil thicket
#

dynamic - the mask here is created by the user and they kinda need to see how it looks

light gale
#

If it were static I'd just hardcode it if you want a quick fix, seeing that it is dynamic, perhaps django is the way to go. You can probably find a mask alternative in JavaScript, but I'm guessing you want to keep using pandas?

fossil thicket
#

i want to use pandas yeah, if it's django i won't bother tbh, too heavy

light gale
#

I'm not sure, if I were you I'd go the django route, but others might have an easier suggestion.

fossil thicket
#

yeah bc you know django XD

light gale
#

Exactly, I'm biased ๐Ÿ˜‰

fossil thicket
#

but i don't want to learn a framework, i want to make a few buttons or some shit (presumably) and filter on them... hrm, i will leave it

native tide
#

@light gale what is your view for that API endpoint? are you using a modelSerializer?

native tide
#

@fossil thicket Using JS wouldn't be a bad idea. But also, if you use Django, if you are just rendering to a page it really won't take long to learn. You could do it in a day

rancid owl
#

I cry when cpanel default python version is 2.7 and I spent 2 hours trouble shooting why my code wont work haha

vestal hound
#

what are you trying to do

karmic egret
#

Hello, does anyone has any idea why my navbar for webpage shows like this

lavish prismBOT
#

Hey @karmic egret!

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

strong vault
#

is anyone good with flask and jinga. will literally pay u to help lol

oblique snow
#

bro

#

help

#

my authenticate function is always pritning none

#

when i try to implement authenticate in login fucntion

zinc hill
#

you should show us some code or something

mortal lark
#

Hello guys , can anybody here help me with a problem in webpy ?

rose fulcrum
#

Dear all, I'm writing a view that needs to open two links. How should I do that? thanks

past cipher
gaunt marlin
primal kernel
#

Hey guys,

I'm trying to get a response of a webservice. I'm using the suds library.
My problem is that the response that I get is an "object" <Text, len() = 174>

I know that the response is there but I don't know how to get it!

Any help? ๐Ÿ˜ฆ

final sequoia
#

hey guys, can someone have a look at my react/django project? i'm trying to do put requests in frontend/index.js, the request goes through but the database itself doesn't update when i drag an element (it snaps back immediately): https://github.com/hanyuone/kanban

#

frontend is on localhost:3000, backend is localhost:8000 rn

rose fulcrum
#

I've done this from JS before but now need to initiate it from the view

#

the mailto link is meant to use the default mailing client to create a email draft from a template which the use then finishes before sending

#

...so I can simply send the email from within the view

manic ravine
#
class Job(models.Model): # Create table
    title = models.CharField(max_length=100) # Create column # Create Title Field (small text field)
    # location =
    job_type = models.CharField(max_length=15,choices=JOB_TYPE)
    description = models.TextField(max_length=750)
    pub_date = models.DateTimeField(auto_now=True)
    Vacancy = models.IntegerField(default=1)
    salary = models.IntegerField(default=500)
    # ctaegory = 
    expirience_years = models.IntegerField(default=1) 

error

raise exceptions.ValidationError(
django.core.exceptions.ValidationError: ['โ€œโ€ value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.']
#

any idea?

#

error from pub_date

native tide
#

@final sequoia so your API request is successful but it's not being saved to the database?

golden pollen
jagged lark
#

This would be the right channel for webscraping, yeah lemon_pleased

golden pollen
#

alright, well im simply just testing now, but I ran into a problem "object of type 'Response' has no len()" does it refer to the links im scraping which needs a limit?

#

line 19-20 does nothing for now

final sequoia
full cradle
#

hi all

#

i just wanna know

#

how can i check if a mail idactually exists

#

without sending a mail to the mail iD

#

anyone can help me on this ???

#

or stepto verfiy the Mail addres

#

Any module for it ?

#

id actually *

full cradle
native tide
#

@final sequoia can you send some code

wild echo
#

hello

#

this gives me a 400 Bad Request

#

spent 50 mins debugging - help

#

backend

#

y'all this is a beginners level error please have a look at it idk why im getting a bad request ples halp

swift sky
#

im having issues using flask migrate

#

for some reason my app isnt being imported correctly

native tide
#

@wild echo We need a bit more info, what is the error explicitly saying?

wild echo
native tide
#

Ok, so let's start with KeyError: 'name'.

I'd print request.form to the console to see what it is and see whether it has the attribute name or not.

wild echo
#

i did

#

dump() shows all variables in the frame

#

and it says request is nothing

#

but why though look at my backend and front end, I submitted the form as a POST request

native tide
#

can you show us the complete view (function) for that URL

#

Ok, so you are rendering your form on a separate view and using that as an API for handling the form?

wild echo
#

rendering form on separate view

#

yes

#

this is the view of the form

drifting furnace
#

!code

lavish prismBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

native tide
#

hmm, okay, that's strange. I'd suggest you use url_for in the action of your form to redirect the request to that view. Try to see whether that helps, as it sometimes does.

wild echo
wild echo
native tide
#

Looks right to me. I'm more of a Django person so take it with a grain of salt

wild echo
#

yeah shalt try wait up

tacit granite
#

Hello everyone, I'm having an issue and was hoping for some assistance. I'm building a quiz application in Django, where we ask a question and the user has 4 multiple choices they can choose from. Once they make their selection, it would take them to the results page which show them if the answer was correct of not with an explanation. The problem is that I'm unable to bring up the User's selection, the section just stays blank with no errors and no database entry. I have enclosed my code here @https://gist.github.com/RemeoLong/eb05b2a28df7d98f649fa20af4f00049 . Any help would be appreciated

Gist

GitHub Gist: instantly share code, notes, and snippets.

wild echo
#

nope

#

didnt work

wild echo
native tide
#

Ok, and in your console, it's making POST requests to that URL correct? Or is the error before the request is made?

wild echo
#

the error is after the request has been received, it visits the POST URL and then comes the Bad Request error

#

127.0.0.1 - - [15/Dec/2020 19:28:34] "โ†[35mโ†[1mPOST /fan/profile/settings/update HTTP/1.1โ†[0m" 500 - POST request

native tide
#

Okay, do you know what line is bringing the error:
KeyError: 'name'?

Is it from retrieving the data from the field or setting data to the session?

wild echo
#
newname = request.form['name']```
#

this is the line where the error happens according to my debugger

native tide
#

Okay. Correct me if I'm wrong but I don't believe that buttons have an action attribute:

<button class="btn primary" name="add_elem" action="submit">Update Profile</button>

They should have the type="submit".

<button class="btn primary" name="add_elem" type="submit">Update Profile</button>
wild echo
#

haha I thought the same, did the same change, and still saw the same error, and btw yes i believe you're right

polar trellis
#

your inputs are also missing the type parameter

native tide
#

Also set the type of your inputs

#

Yeah ^^

wild echo
#

ohhhh thanks will try now

#

still giving the same Bad Request error

#

OMG

#

FIXED IT

#

THE ERROR WAS - the HTML never rendered the updated HTML, it was always loaded from cache and hence the old version of the HTML without names was rendered

wild echo
native tide
#

yeah, I was looking over the code and I didn't see anything wrong. I was so confused haha

wild echo
#

thank you so much y'all really appreciate all of you taking interest to assist me, thank you so so much! โค๏ธ

native tide
#

all good ๐Ÿ™‚

steel geode
#

Guys, I will open a hosting company. I need a theme for this. I need help.

hybrid bobcat
#

hello, so i encountered this issue where when i called a file outside of the folder, that called file throws import error (the error file is importing another file), but when i instead, just run the error file and not from the file outside of the folder, the import error disappears
here's my folder structure for brief

(file)main.py
(folder)app--
            |--(file)app.py
            |--(file)views.py
            |--(file)__init__.py

so app.py import views.py and perform some tasks, when i call app.py, everything works fine, but when i call app.py from main.py, it throws an import error at the place where app.py imports views.py

slow shale
hybrid bobcat
#

ok

rain bison
#

hi

#

does anyone have experience with threejs

native tide
#

@hybrid bobcat are you using flask

hybrid bobcat
#

yea

#

might that be the issue?

native tide
#

seems like you need to use Blueprints

#

you're getting the circular import error?

hybrid bobcat
#

no

#

just a traceback "no module named blahblahblah"

native tide
#

can you show us the imports

hybrid bobcat
#

and not just when importing view, i tried it for other files that are not even importing flask, still import error

hybrid bobcat
#

so this is my folder structure for other stuff

main.py
app ---
      |-views.py
      |-utils---
               |---form_handle.py

so in the main.py, i call views.py, and views.py imports utils/form_handle.py's class liek this from utils.form_handle import RegistrationForm and then the no module named utils occurs after i execute main.py

#

but when i just execute views.py directly instead of calling it from main.py, the error doesnt happen

native tide
#

and what's the import in main.py?

hybrid bobcat
#
from app import app, views
app.app.register_blueprint(views.pageS)
app.app.run()
#

so i called app.py, added views as blueprints, and then in views. i import utils/form_handle.py, this is where the error occurs

native tide
#

So, in the file you want to import, did you create a Blueprint object? Did you then import that Blueprint object within the main.py and register it?

#

Because that is what has to be registered.

gray stone
#

how to get a moving background like YAGPDA website

hybrid bobcat
steel geode
#

Does anyone sell themes for my hosting company?

native tide
#

Can I see what you defined as blueprint?
app.app.register_blueprint(views.pageS) doesn't look like you're registering the actual blueprint, but your views.

gray stone
#

how to get a moving background like YAGPDA website

hybrid bobcat
#

and app.app is the Flask()

native tide
#

I'd rather see some code.

gray stone
#

@formal vault

hybrid bobcat
#

this is app.py ```
from flask import Flask
app = Flask(name)

#

and in main.py

from app import app, views
app.app.register_blueprint(views.pageS)
app.app.run()
rain bison
#

i am sooooo anoyed

#

three js wont work with javascript when it is meant to uhhhhhhhhhhhhhhhhhh

native tide
#

@hybrid bobcat I'm not too sure on those imports. To simplify it, couldn't you register the blueprint in app.py?

halcyon lion
#

boys, how do i make it so when i click my dropdown menu the buttons below are not showing ๐Ÿ˜„

native tide
#

and where did you initialize your blueprint object?

hybrid bobcat
native tide
#

@halcyon lion using JS?

gray stone
#

@shadow hornet

native tide
#

@hybrid bobcat That's not how you set blueprints though, unless I am missing something. Where did you initialize your blueprint object?

native tide
gray stone
hybrid bobcat
gray stone
#

@sharp tusk

native tide
#

@hybrid bobcat looks to me like you're using blueprints wrong.

#

@gray stone that's not how it works

hybrid bobcat
#

except the import is not

gray stone
hybrid bobcat
native tide
#

so it's not working

hybrid bobcat
gray stone
native tide
#

Well, you're meant to firstly initialize your Blueprint object:
example_blueprint = Blueprint('example_blueprint', __name__)

Then in your app.py (wherever you Flask object is), you have to register that blueprint.

hybrid bobcat
hybrid bobcat
native tide
#

This is a good channel for HTML / CSS help, but pinging everyone under the sun so they drop what they're doing to help you isn't good. If no one here can help I suggest you do some more research on your problem while waiting for a reply@gray stone

gray stone
#

ohhh backend dang srry but the YAGPDA web site still cool tho..

hybrid bobcat
native tide
hybrid bobcat
gray stone
#

ohh ok ok how to get a moving background like the one in YAGPDA web page

hybrid bobcat
gray stone
#

u mean learn it or copy paste ?

native tide
#

๐Ÿคฆโ€โ™‚๏ธ

gray stone
#

what?!

hybrid bobcat
#

bootstrap have like some css stuff that can prolly help you animate your backgroudns

gray stone
#

damn u r profesh man

hybrid bobcat
gray stone
#

anyways last question

gray stone
hybrid bobcat
#

i cant even import a file

native tide
#

Can't you just set a video for your background

gray stone
#

do u think web development will last for like the next 5-10 years?

native tide
#

Also it's unclear what you mean by a "moving background"

gray stone
gray stone
hybrid bobcat
native tide
#

That's a JS problem, bootstrap won't do that. Bootstrap doesn't really do animations, just CSS styling. There's some JS libraries for what you're talking about

hybrid bobcat
#

and btw Nut, i did define blueprint and add views to it in views.py

native tide
#

can you show the code?

hybrid bobcat
hybrid bobcat
#

pageS = Blueprint('pageS', __name__) and then i access route() from pageS

gray stone
#

bc i heard web industry is dying

hybrid bobcat
native tide
#

and who did you hear that from? ๐Ÿ˜„

gray stone
hybrid bobcat
native tide
#

it's even less than 20 years, haha ๐Ÿ˜„

#

as a developer you should be learning what's new

#

keep in the loop and stay trendy

gray stone
hybrid bobcat
#

and also clients dont even know how to use GPT-3 so we're good for now

native tide
#

That will never replace web-dev

hybrid bobcat
#

and all GPT-3 does is frontend, it can't help you build more complex stuff

gray stone
native tide
#

There's wix, there's wordpress, there's shopify. How come web-devs are still getting salaries > $100K? Because they can create intricate and personalized solutions. You can't do that without coding.

gray stone
#

im sure after at least 2 years everything will change lol look at wix

hybrid bobcat
native tide
#

Web-dev isn't getting anywhere any time soon.

#

But some technologies will.

gray stone
native tide
#

I could probably have better chances learning node.js over django

#

but I don't know

gray stone
#

bc im asking is it worth learning its stuff

hybrid bobcat
native tide
#

yes it is

#

if anything it's growing

hybrid bobcat
native tide
#

not really

hybrid bobcat
#

like express.js and django?

native tide
#

yep

hybrid bobcat
#

then django better

#

express.js is kinda similar to flask

native tide
#

more opportunities with node.js technologies

hybrid bobcat
#

the way you use it

native tide
#

but yeah django is better

gray stone
#

sorry i mean app dev and ml maybe

native tide
#

unless you like math ML won't be enjoyable

hybrid bobcat
native tide
#

but always give it a try ๐Ÿ™‚

gray stone
hybrid bobcat
#

web dev is also a form of app dev i think, if you actually apply some backend stuff

gray stone
#

even tho it doesnt need that much math but still

hybrid bobcat
gray stone
hybrid bobcat
#

ML is more related to Computer Science comparing to web dev and shit

hybrid bobcat
gray stone
gray stone
# hybrid bobcat ML

im talking abt SQL its kinda not that much maths in it but its kinda tough still (

hybrid bobcat
hybrid bobcat