#web-development

2 messages Β· Page 63 of 1

late gale
#

a new admin is created

#

ik

native root
#

This creates a lot of things, the database, some migrations, and a new admin user

#

right

#

later, you add code that tells django "whenever a user is edited or created make sure they have a profile"

late gale
#

yup that what i am trying to do

native root
#

Right, and you've done so successfully

#

there's one little hole

#

that first user has not been created or edited since, it already exists

#

and it never had a profile assigned

late gale
#

and how to fix that

native root
#

Simplest way is probably to just edit the user in the admin screen

late gale
#

so i make him the super user?

native root
#

He already is?

late gale
#

nope he is just active

native root
#

request.user is the current logged in user

#

what user are you logged in as?

late gale
#

I'm loggedin as the active user not the super one

native root
#

did you create that user before adding the post_save code?

late gale
#

nope

#

I create the user after i add it

native root
#

You can log into django admin right?

#

try something for me?

late gale
#

sure

#

what do u want me to try?

native root
#

Logging out and back in, I guess

late gale
#

that won't change anything

native root
#

Since User stores last login time, logging out and in should call User.save()

#

That should call your post_save handler

#

and fix things

late gale
#

why should i add User.save() when django saved the user once registered

native root
#

You shouldn't

#

Internally django will call user.save() for the logging in user whenever you do a login

#

ah, I missed a thing

#
@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)
late gale
#

so anyways can't i make the profile be made for any user who just registered I don't want all of my users have the access to admin page plus I won't have the time to do a profile for more than 50 users

native root
#

Yes, lets do that

#

whenever a user logs in, django calls user.save() to record their last login time

#

that calls this code here that you've attached to the post_save signal

#

However, some users appear to have been created without a profile attached

late gale
#

true

native root
#

so created is True, but you still need to add a profile

#

You need to ensure that the user object has a profile attached

late gale
#

so do u mean is i need to check if the user have a profile if not create one for this user

#

but isn't this code do the same?

native root
#

No, it checks if the user is being created, and if so adds a profile

late gale
#

ooh

native root
#

Actually I'm going to give you an easier solution, sorry about not thinking about it earlier

late gale
#

np

native root
#

you're presumably running manage.py with python manage.py runserver [whatever] right?

late gale
#

ofc

native root
#

you can enter a django shell via python manage.py shell

#

Inside there you can manually clean up all the users that don't have profiles yet

#

You wont have to do so for any new users, thankfully

late gale
#

can't i just remove them from the admin page?

native root
#

You could, but the original admin user is one of them

#

and that could get awkward

late gale
#

i wont delete the admin user

#

just the others

native root
#
from appname.models import Model
from django.core.exceptions import ObjectDoesNotExist
for model in Model.objects.all():
  try:
    u = model.profile
  except ObjectDoesNotExist:
    model.profile = Profile.objects.create(user=model)
#

something like this, if you get it?

late gale
#

i can add this to the views

native root
#

You could, but it's written to apply to all models of course

late gale
#

so i can say

try:
profile = user.profile
except ObjectDoesNotExit:
profile = Profile.objects.create(user=user)
#

Do u mean like this?

#

oh wait

#

i got it

#

let me try

#

wait u are saying for model in Model.objects.all or do u mean from?

#

oh srry i got what u are trying to say

native root
#

πŸ‘

late gale
#

OMG!!

#

DUde i am literally crying happily

#

xDDDDDDDDDD

#

THANK YOUUUU

#

MWAAAAH!!

severe mica
#

hey all, was wondering if anybody could help me with an issue im having trying to autogenerate urls from url mappings (Link Building)

#

evrything shows up besides the links which I am trying to generate in the list titles scheduled meetings

native root
#

Well, first thing I notice is that the template is only given one meeting, but you're looping ove ra nonexistant variable Meetings

#

I'd also suggest djangos {% url %} template tag:

#
{% url 'view_name' arg %}
severe mica
#

what do you mean by the template is only given one meeting?

#

sorry I am very new to django

native root
#

return render(request, 'template_name_snip', {'meeting': meeting})

#

the {'meeting': meeting} is the variables passed to the templates

severe mica
#

yes but can wouldnt that create a dictionary as I add more meeting objects into the Meetings table i created in my models.py

#

which is why i thought it should loop through

native root
#

No, because meeting is a singular meeting you got via get object or 404

#

If you want to have access to all meetings in the template, you'll have to get them manually and hand them to the template just like you did the singular matching 'meeting'

#

actually

#

sorry

#

wait

#

You're using detail and list views

#

but you haven't posted the list view

severe mica
#

wdym by that?

native root
#

Your template is using the variable num_meetings but I don't see that being defined anywhere

#

it's not defined by default, so where's the code that comes from?

severe mica
#

oh yea thats beacuse thats in another views.py file

#

should i maybe move my detail function to that same file?

native root
#

No, the detail function isn't what's applying here so no reason to touch it

#

the list view is important

#

Django templates only have access to explicitly what you give it and a few default items

#

'Meetings' is not defined in the template, so its not listing any

#

you need to pass it within you list view

severe mica
#

ok will try to fix based off information you gave me thx

cosmic cove
#

Hey, what would you guys reccomend as a good authentication as a service provider for a website?

warm igloo
#

auth0

cosmic cove
#

ok, thanks

valid crane
#

im getting this error when trying to save an object to my model:

django.db.utils.IntegrityError: FOREIGN KEY constraint failed

code:

from django.db import models
from datetime import datetime

# Create your models here.
class TutorialCategory(models.Model):

    tutorial_category = models.CharField(max_length=200)
    category_summary = models.CharField(max_length=200)
    category_slug = models.CharField(max_length=200, default=1)

    class Meta:
        verbose_name_plural = "Categories"

    def __str__(self):
        return self.tutorial_category


class TutorialSeries(models.Model):
    tutorial_series = models.CharField(max_length=200)

    tutorial_category = models.ForeignKey(TutorialCategory, default=1, verbose_name="Category", on_delete=models.SET_DEFAULT)
    series_summary = models.CharField(max_length=200)

    class Meta:
        verbose_name_plural = "Series"

    def __str__(self):
        return self.tutorial_series


class Tutorial(models.Model):
    tutorial_title = models.CharField(max_length=200)
    tutorial_content = models.TextField()
    tutorial_published = models.DateTimeField('date published', default=1)

    tutorial_series = models.ForeignKey(TutorialSeries, default=1, verbose_name="Series", on_delete=models.SET_DEFAULT)
    tutorial_slug = models.CharField(max_length=200, default=1)
    def __str__(self):
        return self.tutorial_title

am i using the ForeignKey method wrong? do i remove verbose_name or edit the value for the on_delete argument? for additional context, im learning this: https://www.youtube.com/watch?v=Rju5qdU0e58&list=PLnVyTqAVic7M4_pUJQ-KyxyL6ZLy4EM87&index=21

dense slate
#

Ok I am confusion. With google's OAuth2, I have the auth token/credentials and correct scopes for my needs, I just can't seem to find out where I get the actual user information from. Where is the response that provides the user email/username/etc.?

frozen widget
#

how can i change the post request data before the post request is submitted

#

for eg i want to add a token to the end of the post request but i want to do this on my backend

#

how can i do that

verbal obsidian
#

You can pass that token when rendering the template in context

#

and then put it in a <input type="hidden" name="myspecialkey" value={{ mykey }}>

#

@frozen widget

#

In that way, you won't be 'changing' the post request data per se, but adding that key to it

limber laurel
#

Can I using flask_login see if a view has a decorstor like login_required?

verbal obsidian
#

Why do you need that @limber laurel

limber laurel
#

I am making a navigation bar using url_map, so it is dynamic when I change a functions name, and right now my only problem is that some views require you to be pogfed in yet the header still displays it

inland stirrup
#

i am getting error when i am running this can someone help me

fickle fox
#

u didnt closed name in app route

inland stirrup
#

oh yeah got it

#

btw can i run two different files with flask functionality in one venv

#

cause after running the first file and changing the Flask_app to the second file and running flask it executes 1st file

native tide
#

I am trying to follow along with a django tutorial

#

i one of the videos he is going to \admin route and logging in with a user

#

he then clicks on users and adds a new user

#

then clicks on save and continue and works perfectly fine for him

#

but not for me

#

i use Django version 3.0 and sqlite3 version 3.29.0

#

and i get this error

#

OperationalError at /admin/auth/user/add/

pure hill
#

hello anyone have simple website project that i can use for reference .. ? new to django framework and also new to website development

marsh canyon
green beacon
#

Hi!

#

Does anyone speak Russian?

hardy gazelle
#

Hello everyone

#

is it Flask a good learning path for someone who never did a thing about web development?

fierce sapphire
#

what's best? django or flask?

hardy gazelle
#

@fierce sapphire as far as i know

#

there are good frameworks...flask more on the microservice side

#

and django on the full fledge side

#

this is the best blog i found about vs

#
Stack Abuse

In this article, we will take a look at two of the most popular web frameworks
in Python: Django and Flask.

Here, we will be covering how each of these frameworks compares when looking at
their learning curves, how easy it is to get started. Next, we'll also be
looking at how...

distant trout
#
def delete_account(id):
    if current_user.is_authenticated:
        user = User.query.filter_by(id=1).first()
        db.session.delete(user)
        db.session.commit()
        return redirect(url_for('main.home'))```
#
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(16), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
    image_file = db.Column(db.String(20), nullable=False, 
default='default.jpg')
    password = db.Column(db.String(60), nullable=False)
    posts = db.relationship('Post', backref='author', lazy=True)```
#

can someone tell me why this is not working? i get a NULL constraint error when I try to commit the delete of user.

verbal obsidian
#

neither username or email can be null

#

have you check that none of those are null?

distant trout
#

yeah, i have email and username filled in

hidden pier
#

do you have any posts linked to this user?

#

it looks like deleting user breaks constraint on some post

#

maybe delete cascade is needed?

distant trout
#

hmm not sure what that is but i show u my post model

hidden pier
#

ok

distant trout
#
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100), nullable=False)
    date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    content = db.Column(db.Text, nullable=False)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)

    def __repr__(self):
        return f"Post('{self.title}', {self.date_posted}')"```
#

this is a post i made

hidden pier
#
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)

Here we go

#

so you have basically 2 options here:

  • change user_id on Post model to nullable
  • delete cascade -> deletign user deletes all related objects, like user posts
distant trout
#

oh

#

so right now the error shows because it is only deleting the user but it cant delete the post linked the user

#

is that right

#

so it shows an error

hidden pier
#

close, deleting the user makes Post relation to that user invalid, because relation is set to nullable=False

distant trout
#

OH

hidden pier
#

so it has to point to some user

distant trout
#

i see

hidden pier
#

you can make a guardian user "deleted" and always switch post owner to this

distant trout
#

wait is deleting cascade part of sqlalchemy

hidden pier
#

it is even part of SQL itself

distant trout
#

oh, that seems to be the best choice for me. I am going to research more into that right now

real hare
#

Using a Class based view in Django to display blog posts on my site. It is split across two directories on the site namely /posts and profile/posts. I want to filter the profile/posts to show the authenticated users posts only. How can I achieve this? Could someone share documentation that would demonstrate this?

distant trout
#

Thank you!!

hidden pier
#

np! πŸ™‚

verbal obsidian
#

Thank you!!
@distant trout in the view you can use, if request.user.is_authenticated

distant trout
#

@verbal obsidian inside the delete_account route?

verbal obsidian
#

what?

#

No

#

wait

#

Sorry mate, I pinged the wrong guy

distant trout
#

oh lol, its okay

verbal obsidian
#

Using a Class based view in Django to display blog posts on my site. It is split across two directories on the site namely /posts and profile/posts. I want to filter the profile/posts to show the authenticated users posts only. How can I achieve this? Could someone share documentation that would demonstrate this?
@real hare in the view you can use, if request.user.is_authenticated

real hare
#

Thank you very much, I did not think it would be that simple

verbal obsidian
#

also, If you need that for the entire view

#

you can use the @login_requred decorator

real hare
#

Awesome, thank you πŸ™‚

native pasture
#

Is it just me, or developing user interfaces in js/css is very time consuming?

hidden pier
#

nah, it just is πŸ™‚ some frameworks make it a little easier sometimes if they let you put prepeared pieces together

#

you can use the @login_requred decorator
yep, django is awesome, you always have that request.user object and it's the logged in user or AnonymousUser by default and the have all this crazy methods is_authenticated / is_active etc.

static night
#

Whitch python web framework is best for website?

zealous spindle
#

Hi I am looking for freelancers who would like to work on a social media app. Anyone interested please DM me.

mint umbra
#

does anyone know how I can make my submit button for my form take the user to another page?

#
<form method="POST" class="formone" >
    <input style="font-size:55px !important; font-family: 'Ubuntu', Helvetica, Arial, sans-serif; text-align: center; margin: 10px;" type='text' name='name' placeholder='Your name' /><br/>
    <input style="font-size:55px !important; font-family: 'Ubuntu', Helvetica, Arial, sans-serif; text-align: center; margin: 10px;" type='text' name='message' placeholder='Your message'/><br/>
    <input type='submit' id="feedbackbutton" value='submit' />
</form>
#
@app.route("/contact.html", methods=["GET", "POST"])
def contact():
    sender = request.form.get('name')
    message = request.form.get('message')
    client.messages.create(to="+1XXXXXXXXXX",
                           from_="+1XXXXXXXXXX",
                           body=f"From [{sender}]: {message}")
    return render_template('/contact.html')
#

using this right now. If I try to change the "action" in my html here, I my python ends up sending a blank message, and I get a method not allowed.

#

if I try return render_template("/formcomplete.html"), I get an internal server error.

#

I'm not completely sure what to do- help would be greatly appreciated!

marsh canyon
#

use redirect on a post req

mint umbra
#

@marsh canyon how would I do that? Sorry for continuing this

cold anchor
#

flask.redirect('/other-path')

balmy kernel
#

hi so im doing a code which is a questionaire using flask and wtforms but i get this error and tbh i dont know why write_to_disk() takes 3 positional arguments but 4 were given

native tide
tiny siren
#

how does laravel work

native tide
#

Hi

#

Is there anyone here who uses Django?

bleak bobcat
#

This is the #web-development channel of a python discord, of course there are people who use django

native tide
#

@bleak bobcat anyone using python here?

bleak bobcat
#

Hmm. I'd have to check, not sure.

opaque sail
#

Can someone point me in the right direction for learning Django i tried the bloody tutorial 2 times from scratch and i Fail miserably...?

lyric meadow
#

Two scoops of django is pretty great and they just released their new version

opaque sail
#

Ok thank you :)

#

Django seems overwhelming rn

lyric meadow
#

I feel you

opaque sail
#

I wish ;)

lyric meadow
#

I tried learning django about two years ago but i'm not a dev

#

haha easy there partner

opaque sail
#

Shit

#

Ok

#

Im gonna give it a try

#

Ill let you kids know if I fail again

lyric meadow
#

Learning dash might be a good place to start if you have some python experience

#

depending on what your end goal is

opaque sail
#

I have some Flask and some PyQt expirience

lyric meadow
#

I would give Dash a look as you would know your needs better than me

opaque sail
#

I would like to build up an web service from ground up

lyric meadow
#

maybe django might be better

native tide
#

I tend to learn best that way myself

opaque sail
#

Thank you guys I really wanna go trough this bush of code and find out what the heck is going on

#

Yea I like videos the most as well...

coarse bay
#

hi, im new to django and am making a website as part a challenge against my friends but im currently struggling with getting my css files to load. I'm trying to use the staticfiles to make it work but django isn't able to find it somehow?

#

i've set up my STATIC_ stuff in my settings.py like this ```python
STATIC_URL = '/static/'

#this tells django which files to find static=======#
STATICFILES_DIR=[os.path.join(BASE_DIR, 'assets'),] #
#===================================================#

STATIC_ROOT= os.path.join(BASE_DIR, 'static')

#

my file tree for my project looks like this

#
β”œβ”€β”€β”€assets
β”‚   └───css
β”œβ”€β”€β”€blog
β”‚   β”œβ”€β”€β”€migrations
β”‚   β”‚   └───__pycache__
β”‚   β”œβ”€β”€β”€static
β”‚   β”œβ”€β”€β”€templatetags
β”‚   β”‚   └───__pycache__
β”‚   └───__pycache__
β”œβ”€β”€β”€mysite
β”‚   └───__pycache__
β”œβ”€β”€β”€static
β”‚   β”œβ”€β”€β”€admin
β”‚   β”‚   β”œβ”€β”€β”€css
β”‚   β”‚   β”‚   └───vendor
β”‚   β”‚   β”‚       └───select2
β”‚   β”‚   β”œβ”€β”€β”€fonts
β”‚   β”‚   β”œβ”€β”€β”€img
β”‚   β”‚   β”‚   └───gis
β”‚   β”‚   └───js
β”‚   β”‚       β”œβ”€β”€β”€admin
β”‚   β”‚       └───vendor
β”‚   β”‚           β”œβ”€β”€β”€jquery
β”‚   β”‚           β”œβ”€β”€β”€select2
β”‚   β”‚           β”‚   └───i18n
β”‚   β”‚           └───xregexp
β”‚   └───img
└───templates```
and in my assets folder i have```
β”œβ”€β”€β”€assets
β”‚   └───css
β”‚        └───styles.css
#

but whenever i run in the cmd C:\Users\...> py manage.py findstatic css/styles.css it tells me that styles can't be found. Consequently when i run the collectstatic it can't add styles.css to my static files. I've tried just copying and pasting the file over but it still isn't able to find it? Do you guys have any tips or solutions to this issue? If so it would greatly apprecieted!

dusty plaza
#

Hey guys, good evening, I'm also new to django. Rn I'm working on a REST API using django-rest-framework. Whenever I want to write business logic I don't know if there is a proper or standard way to structure my files. I don't feel like business logic belong to models/views/serializers. Any thoughts on that matter? Can you share/explain if you have a file structure template and why you use it?

molten quarry
#

@coarse bay

STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]```
#

From there you can just use the relative path in your templates

{% static 'admin/css/stylesheet.css' %}```
coarse bay
#

oh ok! i've changed it but im still getting this when i try to load my webpage

molten quarry
#

What's the line of the template look like?

coarse bay
#

what do you mean? like the views.py or the actual html file?

#

(sorry im really new to this)

molten quarry
#

Template refers to the .html

coarse bay
#

Oh ok!

#

oh sorry that cut a little short here

molten quarry
#

Okay, and you're DIRS right? In your code you have it as DIR

coarse bay
#

I did not. Im gonna try changing that

#

er i mean i did have DIR not DIRS

molten quarry
#

Hmm. Might have mixed it up with STATIC_ROOT, though that's what you already had.

coarse bay
#

so should i change the 'static' in STATIC_DIRS to my original assets folder?

molten quarry
#

Try it

#

I always just have a single atatic folder with child folders.

#

static*

#

And then use the relative path in the template

coarse bay
#

what do you mean by child folders?

#

also it got rid of the static_files error when i changed it to asset instead of the static

native tide
#

Hi friends I'm new in Django can you put me on the right track

molten quarry
#

Subfolders.

coarse bay
#

Oh ok!

#

@molten quarry It works now! Thank you so much!

#

so after i changed the to the assets folder, this time the collectstatic actually got the styles.css from my assets folders and added it to static!

#

@native tide hello! what do you need? Im also kinda new to django but im willing to help!

native tide
#

@coarse bay I need to know how to start

coarse bay
#

Oh ok so the django website has a really nice tutorial that i used

#

this one runs you through making a poll/voting app but it touches base on everything. As a consequence tho it is split into 7 parts then goes onto an advanced tutorial

#

which is a different project

#

is this the kinda stuff you were looking for? @native tide

native tide
#

@coarse bay Not exactly, but it's okay

#

@coarse bay Do you have the resources to learn?

coarse bay
#

like some youtube videos?

#

hmm.. do you have an idea for a specific thing in mind?

native tide
#

like some youtube videos?
@coarse bay
And books, Sites

coarse bay
#

ok! so i dont know about books but lemme go look through my bookmarks

#

This one is pretty helpful. There's alot of guides to specific features or issues that you might implement or run into

#

Are you familiar with any frontend stuff like html,css, or javascript? @native tide

native tide
#

@coarse bay yes I've learned html & css but i'll never in Javascript

coarse bay
#

thats fine i haven't had to use javascript yet i just know its kinda important

molten quarry
#

I highly recommend the book "Django 3 by Example".

coarse bay
#

tbh besides django central i didn't use many other resources besides just googling issues on stack overflow or quora

#

or going through the django documentation on their website

#

i have to go rn but if i find any other resources ill be sure to send them your way @native tide

native tide
#

Oh yes thank you

#

=^_^=

coarse bay
#

np

molten quarry
#

9/10 resources will teach you what you want to learn, you just need to stick with it long enough. Don't let yourself get carried away by the vastness of the internet. Pick one and run with it!

native tide
#

Okay yes thank you Pro

next tree
#

Anyone use flask with vue.js? I'm trying to figure out how to turn my .vue files into static .html files to serve via backend routes.

limpid comet
#

I actually use Vue CLI to compile to HTML first.

inland stirrup
#

guys i am new to flask please help me out

i am using vs code and i've set up a venv in a folder of mine
i have 2 py files in it which are using flask
i used the app.py first(i did all that setting of FLASK_APP=app.py thing) and gave the command python -m run flask
it was successful but when i tried doing it for the 2nd py file which was using flask it ran app.py i've changed the FLASK_APP=app.py to FLASK_APP=application.py still its not running application.py

vocal crag
#

hello if im using flask and twilio is sending a post to a designated url how do i get that data twilio is sending me?

#

nevermind got it!

tranquil steeple
#

@verbal obsidian All I'm trying to accomplish it go get information from forms. So I'd like a way for flask to possible save them to some type of database.

fickle fox
#

yea thats possible

verbal obsidian
#

I mean

#

that's the way of doing it

#

you usually either have forms to save that information or to forward it to some other call

native pasture
#

Is there a way to pin the address bar in mobile browsers, ie. prevent it from hiding when scrolling? The solutions I've found online (setting overflow: hidden to html, body) don't seem to actually work.

mint umbra
#

hello, I'm currently trying to use this code

#
@app.route("/contact.html", methods=["GET", "POST"])
def contact():
    sender = request.form.get('name')
    message = request.form.get('message')
    client.messages.create(to="+1",
                           from_="+1",
                           body=f"From [{sender}]: {message}")
    return render_template('/contact.html')
    flask.redirect(url_for("formcomplete"))
#

but it simply doesn't redirect to formcomplete

native pasture
#

You're returning before redirecting. That statement never gets executed

#

I'm not quite sure what you're trying to do, but you probably want to check if the contact() function is being called due to a GET request (=> render page) or a POST request (=> form data received + redirect).

mint umbra
#

@native pasture POST I believe, I removed GET and it still works

native pasture
#

Well, normal http browser requests are GET. POST is usually used when sending data from a form. If your intent is to render a page when the user goes to /contact.html, that is gonna be handled with a GET request (with no form data). If you have a form in that page that submits to /contact.html itself, your contact() function is gonna be called in the context of a POST request.
One thing you could do is this within the function:

if request.method == 'POST':  # received form data
    # process form data and do stuff
    return flask.redirect(...)
else:  # render page
    return render_template(...)
#

N.B. flask.redirect() generates a response object, and it's not gonna do anything if you don't return it from the route function (that is, send it to the client)

mint umbra
#

@native pasture sorry for the super late response. This solved my issue! thank you so much

knotty eagle
#

hello, i'm trying to create a simple web app that fetches lyrics from azlyrics.com
this code here:

@app.route('/lyric-request', methods=['POST'])
def lyric_request():
    song = request.form['song']
    artist = request.form['artist']
    lyrics = Lyrics(artist, song)
    return render_template('lyrics.html', title='Lyrics', song=song, artist=artist, lyrictext=lyrics)```
and here:
```html
<header>
    <link rel= "stylesheet" type= "text/css" href= "{{ url_for('static',filename='lyrics.css') }}">
    <h2>Song: <span>{{song}}</span></h2>
    <h2>Artist: <span>{{artist}}</span></h2>
    <p>
        Lyrics: 
        <br>
        {{lyrictext}}
    </p>
</header>```
is the code in question. However, for some odd reason, the lyrictext is not displaying on the webpage, even though Lyrics() returns a string. I've tested displaing multiline strings by setting
```python
lyrics = """multiline
    comment""" ```
and it still displays, so I'm not sure what the problem is.
#

I've made sure Lyrics() actually does find the correct lyrics, which it does, and if I call on Lyrics() from outside the function it will print out the correct lyrics too.

twilit zenith
#

im trying to run my flask program on flask_socketio

#

i did everything as mentioned in docs, but page isn't loading at all

brittle peak
#

Has anyone tried to use python/flask through a cPanel app? I'm totally lost

next tree
#

@limpid comet thanks! Is templating necessary when you can make API calls instead? I assume JS is compiled with the HTML.

#

also, my project isn't too big, so it won't be a problem.

cloud path
#

guys my web app with flask, in local works fine but in a microsoft azure server, it crashes when i register a new account, it goes down for a while

#

do you have any idea?

young grove
#

Hey, does anyone know how i can display a list of my results in a nice html code. I put the info out of my mongodb database. But i want to display the results in a list with some nice colors so it looks nice. Does anyone know how to make that?

limpid comet
#

@next tree If you don't need Jinja2 templating, just throw everything into static folder, and it should be fine.

midnight needle
#

how can i deploy my flask server to an different address than localhost(127.0.0.1) ?

lilac belfry
#

Don’t quote me on this but if I remember correctly you would do this:

app.run(host= '0.0.0.0')

#

So just edit the run argument

#

To run the flask server on your machines IP

#

(Locally)

crisp saddle
#

@midnight needle use something like Gunicorn, or Uvicorn.

#

gunicorn --bind 0.0.0.0:5000 app:APP

#

if your Flask aplication is called APP inside app.py

#

then you would use an edge router like Nginx, Apache or Traefik to actually map port 5000 to a domain if you have one of those :-)

wintry geode
#

If any of you dumb asses need help, dm me

acoustic oyster
#

hello friends: I have a discord.py bot that I would like to interface with my Django app. I would like to start by using my django app to save data from the bot to mysql database so that I can manage it from the admin site on django.

After hours of googling it appears no one else online has done something similar. Any thoughts on how to accomplish this?

zealous siren
#

Build a rest API that bot can post to

acoustic oyster
#

that is what I was thinking, but it felt silly

zealous siren
#

why? That's perfectly normal method

#

That's how @lavish prism works

acoustic oyster
#

It seems like a bit much since both the django server and the script are running on the same machine... But I am fairly new to this side of python lel

zealous siren
#

other option is have bot pull data from MySQL database

#

depending on what you are doing, that might work

#

it's not considered best practice

acoustic oyster
#

I was just gonna write the queries myself, but I figured it might make more sense to do it through django in the first place.

I am very new to django.

zealous siren
#

best practice is REST API from Django because proper microservice is Django should be only one to mess with it's database

acoustic oyster
#

would it be reasonable to do all the DB stuff through the discord bot, but still be able to manage it though django?

zealous siren
#

doing MySQL queries is probably easier

acoustic oyster
#

ok, I am very interested in best practice though

zealous siren
#

Best Practice, REST API the bot reads/writes to

#

what are you hopingt o change on the bot from Django?

acoustic oyster
#

It is basically just data for an RPG game I made for the bot that is currently just locally stored in JSON

zealous siren
#

What will Django provide?

#

stat site?

acoustic oyster
#

I would need to change values, delete data, sometimes create.

I was mostly just hoping to use the neat front end interface of the admin page with all the models.

Eventually I will display everyone's character data on the site I have.

zealous siren
#

ok

acoustic oyster
#

And allow users to create/delete/modify their characters through the site

zealous siren
#

BTW, PostGres is considered better Database Engine at this point to go with

#

then I would have REST API the bot can read/write from

acoustic oyster
#

I was aware of that when I decided to use MySQL thank you LOL

zealous siren
#

make sure you use aiohttp on discord.py side to prevent blocking

acoustic oyster
#

But setting up postgress failed for me like 5 times on ubuntu so I gave up lol

zealous siren
#

but yea, REST API, gold standard in moving data between applications

acoustic oyster
#

alright, awesome. Thank you so much for your help.

My other friend also recommended this, but I was hesitant.

#

I am also too scared to move over to posgres since I have nuked a database or two in the past by accident

zealous siren
#

it was suggestion, MySQL/MariaDB isn't terrible and depending on your size, it may not matter

acoustic oyster
#

I do not need crazy performance just yet, but I really do need to switch over. My site is getting more traffic than expected haha

zealous siren
#

performance is really more proper SQL queries

#

and building right tables

acoustic oyster
#

well luckily Django means I can remain ignorant of that

native tide
#

Is someone here familiar with the Reddit API or PRAW?

#

Can I retrieve the Karma Score and the number of comments without the submission ID if I have the full link to the submission?

static night
#

Guys have someone good tutorial for django?

grizzled tapir
#

Yeah use Flask instead

native pasture
#

I've been using Flask for a couple of years now, never tried Django. From what I've understood there are some shared concepts between the two (like jinja templating). But why should one refrain from picking one over the other?

cloud path
#

guys, does anyone know why my flask web app in local works fine, while on azure server it crashes randomly as it had a lot of requests?

#

i mean, is there some issue with flask and azure?

#

in the logs there are just a lot of restarts, without errors

shadow orchid
#

Azure generally sucks

#

I use heroku

#

consider it

#

Flask deployment is excellent

cloud path
#

i'd like to not use it but it's not mine

native tide
cloud path
#

rip by the way

#

there should be an "Always On" feature for flask web app as I read, does someone know how to do that?

late gale
#

how to call a django view from javascript what i wanna do is when the payment is complete it calls the django view so it can send email and redirect url

native tide
#

use a json api

#

There's a thing called json view I think

#

That's one option, you could do it in other ways too

#

javascript can do post or get requests as well

#

Are you using an external payment provider?

late gale
#

I am using paypal api

native tide
#

How to use a code that i wrote but in the website

#

For example it shows colorful circles normally when you execute the code

#

From your pc

#

But then i want this code work in website

#

Is that what django do?

#

Or any library/framework?

zealous siren
#

kocis, I'm Azure SRE, I've run flask in Azure, it totally should not crash

#

Is Containerized web app or uploaded?

#

you can install Application Insights to get trace data from python

tardy pier
#

hey everyone, is anyone familiar with ScraPy and how items works? I have a couple for loops that are supposed I am yielding back the results to the items and they work fine independently but when i try it together it doesn't give me the correct output

fringe pine
#

anyone got any projects there working on

solemn thistle
past cipher
#
img_one = f'/static/images/product_images/{product_details.product_img}'

html template:

{{form.product_img(style="background-image:url('{{img_one}}')")}}

I am trying to apply an inline style, based off an if statement. img_one is passed from the back-end to the template. However I am unsure on how I can use a variable the way I want to. Can anyone offer any advice? With the above example, the html just renders:

style="{{img_one}}"
teal scroll
#

Whats a good way to verify emails like by sending a verification link to email in python?

fringe pine
#

anyone have a while to teach some html, i have not used html for a while

past cipher
#

@teal scroll I did something like that on my last project. I would generate a code, and store it in the database, alongside their email. I would then email them a link something like `site.com/verify/ksdfjksdfjksdfjkdsjkfdjdsf'. If the code matches the code I stored in the DB, i would verify their email

teal scroll
#

@past cipher gotcha

#

thanks

outer apex
#

@teal scroll check out ItsDangerous! This package has some utilities for signing, unsigning, and validating info. Specifically useful for the functionality you mentioned.

teal scroll
#

i was looking at it rn actually. @outer apex

#

thanks

outer apex
past cipher
#

Thanks will check it out now

outer apex
#

Something like

{{ form.product_img(style="background-image:url('{img_url}')".format(img_url=img_one) }}
#

Let me know if it works! Might have to use it for my own work too!

past cipher
#

Perfect!! Thank you very much @outer apex. I searched around for over an hour and couldn't find what I wanted

outer apex
#

Oh yay!

cloud path
#

@zealous siren i don't know exactly since i don't handle the server but just the app, but i've uploaded it onto a github repository

#

but atm i have no requests management in the code, i have just the app itself

#

maybe it is due to that

terse surge
#

hi, i have a problem with my view, it returns none, and u know the django error

#
def ContactUs(request):
    form_class = ContactUsForm
    if request.method == 'POST':
        form = form_class(request.POST)

        if form.is_valid():
            contact_name = request.POST.get('contact_name')
            contact_email = request.POST.get('contact_email')
            subject = request.POST.get('subject')
            msg = request.POST.get('msg')

          # Email the profile with the contact information
            template = get_template('form/contact_template.txt')
            context = {
                'contact_name': contact_name,
                'contact_email': contact_email,
                'msg': msg,
            }
            content = template.render(context)

            email = EmailMessage(
                    subject,
                    content,
                    'noreply@painlesspvp.ml',
                    ['plpvpsp@gmail.com'],
                    headers={'Reply-To': contact_email}
            )
                # send(fail_silently=False)
            email.send()
            return redirect('blog-home') and messag.success(request, f'We received your message! We will reply to your email that you provided usually within 48 hours!')
        else:
            return render(request, 'form/ContactUs.html', {'form': form_class,})
    else:
        form = form_class()
    return render(request, 'form/ContactUs.html', {'form': form_class,})
zealous siren
#

@cloud path I just know that Microsoft sees Python support as critical part of Azure and if you found a bug, opening a ticket would be good, they should want to fix it

native tide
#

Anyone have experience with django ? I'm having trouble trying to figure out this model setup for a cart + pizza model. Cart should be able to contain multiple pizzas. I tried to do many 2 many but it was only allowing for 1 pizza of each kind

quasi ridge
#

many to many sounds wrong; can one pizza live in two carts?

native tide
#

I thought so but was recommended to swap to foreign key (1 to many). My reasoning was multiple carts can order the same item.

#

With FK though theres no add method, so how can I add a pizza to a cart?

stiff gyro
#

hello guys, i have a problem with flask for upload file anybody can help me ?

#

sorry for my english

stiff gyro
#

it's good

manic oriole
#

@sudden crest currently the python isn't connected at all to my html but the python has constantly updating values from a api I'm using, but I'd like to output some of that into html

sudden crest
#

hello

#

ok so you should probably make your

#

wait are you using apache or nginx i forgot

#

anyway make it use flask or django or another framework to serve the files

#

assuming you're just using a basic default nginx/apache setup

manic oriole
#

I haven't decided actually on nginx or apache idk what do you think

manic oriole
#

I'll probably wait till I learn a bit more python

celest torrent
#

Quick question regarding Django, is there a preferred way to write views? Classes or functions? Finding classes hard to do what I want them to do but it's probably because I don't understand how Django uses them fully

#

i.e.

def home(request):
    context = {
        "posts": Post.objects.all()
    }
    return render(request, "blog/home.html", context)```

VS

```python
class PostListView(ListView):
    model = Post
    template_name = "blog/home.html"
    context_object_name = "posts"
    ordering = ["-date_posted"]
    paginate_by = 10```
marsh canyon
#

I always prefer class based views as they are more organised and you also get many built in ones

#

but i guess it comes down to ur preference

#

you can implement the home view using class based views in the following way:

from django.views import View

class Home(View):
    def get(self, request):
    context = {
        "posts": Post.objects.all()
    }
    return render(request, "blog/home.html", context)
#

you can also use template view and then modify the context

#

@celest torrent

noble wren
#

how can I get the value of this form in my views.py class

#

type_of_place = request.POST.get('typeform') Trying that gives me a value of none

snow dragon
#

Keep in mind that you don't have to use Django's built-in Form class, you can always write the HTML yourself too as you've done above.

noble wren
#

@snow dragon im trying to get the value that the button is

#

like value='parks' or w/e it is

#

I dont want any user input, they can only choose through the buttons

snow dragon
#

Usually that would be something like a dropdown or checkboxes. Notice the type=submit means those are buttons to submit the form, not usually the value itself. Although I guess you may be able to get that value out somehow. Never tried it.

#

@noble wren

noble wren
#

I see

#

thanks

main dirge
#

This is probably a rather naΓ―ve question, but how homogeneous are element names/divs for different websites that serve the same function (generally speaking)? IE, would it be foolhardy to crawl 50 different websites' HTML, figure out what the elements were which directly corresponded with a login portal, and expect to have any predictive understanding for the next 50 websites' HTML?

snow dragon
#

@main dirge Unlikely. Most of the web is held together by duct tape and 50 is a small sample. Source: I work for a major corporation that owns dozens of websites and I have live ML products on a handful of them.

main dirge
#

At what point do you think the sample size would be large to see any payoff, 10,000?

#

enough to*

snow dragon
#

Depends on what you mean by "predictive understanding"

lavish prismBOT
#

5. Do not provide or request help on projects that may break laws, breach terms of services, be considered malicious/inappropriate or be for graded coursework/exams.

main dirge
#

Can companies use TOS to stop people from scraping data that isn't private or proprietary (data would be public), especially if there is no gate-keeping of the information itself? Seems doubtful if there is no ill intent.

snow dragon
#

@main dirge If you're looking for login pages, that argument is defunct since that data is not publicly available, it's behind a login.

main dirge
#

But just the login itself wouldn't be off limits, right? I'm not looking to login to scrape data.

#

just to figure out if a page has a login, that's all.

#

To be clear - the pre-login, login page.

snow dragon
#

In your now-deleted messages it was pretty clear that was not the intent and so I'm going to maintain my position that I'm uncomfortable in helping any further.

main dirge
#

No worries.

#

I should've expressed my intent better, but it wasn't to scrape data behind paywalls.

#

or logins, for that matter.

#

Just to determine whether the page had a login for volunteers who would be following up.

#

Regardless, I appreciate your response.

snow dragon
#

If we're only looking for login pages, it should be relatively trivial, no ML involved. Just look for <input type="password" tags in the HTML

#

That obviously won't be perfect since many sites can use that tag for other private input fields that are not necessarily passwords, it would give you a good starting point of pages to follow up on.

main dirge
#

Thanks. I didn't mean to put you in an uncomfortable position. I'll try that.

#

Sorry that I did.

autumn plank
#

hello!
i'm trying to add blur box behind the the text but when I apply the blur filter the child element "the text" gets blurred too, here is my code:

<div class="container py-5 mb5">
  <h1 id="r1" class="mb-5">BayCity Rules </h1>
  <div class="guide">
    <div  class= "blur"> <p>
      We want everyone in this community to have fun and enjoy themselves. Please do not deliberately try to ruin anyone else’s experience. This includes common sense things like nitpicking the wording of rules, or trying to otherwise manipulate the system for your own gain. Everyone here deserves to have fun, please do not try to take away from that. We also ask that you please respect the staff. Disrespecting staff and disobeying reasonable requests will lead to disciplinary action being taken.
      <br>By playing on our server you agree to the following rules and you agree that you understand what the following terminology means and hereby agree that you will not partake in breaking the rules stated in this document.</br>
    </p> </div>
    
  </div>
</div>

when I try to use .guide to add blur filter it apply it to the text also
i tried backdrop-filter: blur and it's working fine with google chrome but not with firefox

native root
#

backdrop-filter is only supported in nightly firefox at the moment

#

the going trick for this effect is to have the same bacground image on blur and to have a "below" background layer with blur applied to it

autumn plank
#

@native root that would be 2 blurred layers if I did that!

native root
#

No, just one, since you don't blur the upper layer anymore

candid whale
#

Hello, im using Flask for a web app with sqlalchemy and sqlite for the database. I have established a many to many relationship between user and houses so i can store in what houses a user has rented and who has stayed in a certain house. My question is if i can also establish a one to many relationship between user and houses to store what houses a user owns

fervent cliff
#

?

tulip charm
#

Hello everyone, I hope you all are doing well.

I am kind of confused with a question about a project if you guys can help I'll be thankful.

So, I have an incoming API which gives me data and then I have to write code to work upon that data and output the final data as an API output so that can be used with a webapp and an android app.

Can I use django for this? DRF or graphql?

This will be used by around 10k users so please help me out a bit here.

Thanks

spark frigate
#

BTW if you answer pls mention me

candid whale
#

@spark frigate you want to add the code and the state as parameters to your endpoint?

spark frigate
#

yes

#

@candid whale

candid whale
#

so the code is a string and the the state is an int?

spark frigate
#

yes

candid whale
#

im not very familiar with 2 parameters in an endpoint but try something like this:
@app.route("/login/string:codeint:state", methods=['GET'])

#

and you also need to define them so def login(code, state)

native tide
#

I'm following along with a Django project tutorial

#

i encounter this error

#

'NoneType' object has no attribute '_default_manager'

#

It's an Attribute error

#

In this tutorial he is trying to use django_filters

#

i am doing all the steps

#

but still get this filthy error.

#

also i did pipenv install django-filter

native tide
#

I also included django_filters in settings.py INSTALLED APPS

native tide
#

did i ask my question properly?

#

!ask

lavish prismBOT
#

Asking good questions will yield a much higher chance of a quick response:

β€’ Don't ask to ask your question, just go ahead and tell us your problem.
β€’ Don't ask if anyone is knowledgeable in some area, filtering serves no purpose.
β€’ Try to solve the problem on your own first, we're not going to write code for you.
β€’ Show us the code you've tried and any errors or unexpected results it's giving.
β€’ Be patient while we're helping you.

You can find a much more detailed explanation on our website.

native tide
#

i meet the requirements of all the rules except the last one. I'm kinda need to solve this problem fast.

native tide
#

Hello, is it the best option to use django?

#

If your a Python developer yes.

quick cargo
#

I mean meh

#

Theres all sorts

#

Django is a very heavy framework

#

Flask is a light micro framework

native tide
#

personal portfolio: use Flask.

#

e-commerce website: use Django

quick cargo
#

I mean is choice at the end of the day

fickle fox
#

huys i have one question

#

how can i create something like button menu

#

somehiow confusing but it should be there to create better view of psots

#

on every page 10 posts

quick cargo
#

you mean pagination?

fickle fox
#

yeah i think thats it

#

how do i create it?

#

i mean pagination

distant trout
native tide
#

i'm following along with a Django project tutorial
i encounter this error
'NoneType' object has no attribute '_default_manager'
It's an Attribute error
In this tutorial he is trying to use django_filters
https://www.youtube.com/watch?v=G-Rct7Na0UQ&list=PL-51WBLyFTg2vW-_6XBoUpE7vpmoR3ztO&index=13
i am doing all the steps
but still get this filthy error.
also i did pipenv install django-filter
I also included django_filters in settings.py INSTALLED_APPS variable.

Traceback (most recent call last):
  File "C:\Users\Angelo Hoft\.virtualenvs\django_project-0DacM128\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Users\Angelo Hoft\.virtualenvs\django_project-0DacM128\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\Angelo Hoft\.virtualenvs\django_project-0DacM128\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\kenny\projects\django_project\follow_project\accounts\views.py", line 42, in customer
    'myFilter': OrderSearch(),
  File "C:\Users\Angelo Hoft\.virtualenvs\django_project-0DacM128\lib\site-packages\django_filters\filterset.py", line 192, in __init__
    queryset = self._meta.model._default_manager.all()

Exception Type: AttributeError at /customer/2/
Exception Value: 'NoneType' object has no attribute '_default_manager```
#

this is actual model

import django_filters
from .models import Order


class OrderSearch(django_filters.FilterSet):
    class Meta:
        module = Order
        fields = '__all__'```
this is where i put it in INSTALLED_APPS
```python
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'accounts.apps.AccountsConfig',
    'django_filters'
]```
this is where i use it
in my views.py file
```python
def customer(request, pk_test):
    current_customer = Customer.objects.get(id=pk_test)
    orders = current_customer.order_set.all()
    content = {
        'customer': current_customer,
        'orders': orders,
        'total_orders': orders.count(),
        'myFilter': OrderSearch(),
    }
    return render(request, 'accounts/customer.html', content)```
and the template
```html
<div class="row">
    <div class="col">
        <div class="card card-body">
            <form method="get">
                {{ myFilter.management_form}} /*tried: {{ myFilter.form}}, same error.*/
                <button class="btn btn-primary" type="submit">Search</button>
            </form>
        </div>
    </div>

</div>```
rigid laurel
#

Hm - I haven't ever actually used this part of Django myself. All I can do is try and suggest debugging strategies

#

but first

#

you don't have that in yours

#

yours is slightly different

#

oh wait - different thing

native tide
#

I'm am also a complete beginner at Django😁

rigid laurel
#

Do any filters work for you?

native tide
#

i get an error

#

when i go to that url where the search btn actually is

simple sentinel
#

What does your Order model look like?

native tide
#
class Order(models.Model):
    STATUS = (
        ('Pending', 'Pending'),
        ('Out for delivery', 'Out for delivery'),
        ('Delivered', 'Delivered'),
    )
    customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL)
    product = models.ForeignKey(Product, null=True, on_delete=models.SET_NULL)
    date_created = models.DateTimeField(auto_now_add=True, null=True)
    status = models.CharField(max_length=200, null=True, choices=STATUS)

    def __str__(self):
        return f'the {self.status} {self.product} that {self.customer} ordered'```
rigid laurel
#

looks like you're missing that?

#

you don't pass in the queryset into your filter

#
    content = {
        'customer': current_customer,
        'orders': orders,
        'total_orders': orders.count(),
        'myFilter': OrderSearch(request.GET, queryset=orders),
    }
#

oh wait

#

it's a little more than that

#

but it seems like you're not quite following the tutorial all the way

native tide
#

no i got stuck when i got the error

#
    content = {
        'customer': current_customer,
        'orders': orders,
        'total_orders': orders.count(),
        'myFilter': OrderSearch(request.GET, queryset=orders),
    }

@rigid laurel it looks like that now yeah but now the whole form doesn't show up

simple sentinel
#

To double check, you do have a customer/2 right?

native tide
#

yes

#

i also changed the customer template to this

rigid laurel
#
def customer(request, pk_test):
    current_customer = Customer.objects.get(id=pk_test)
    orders = current_customer.order_set.all()
    filter = OrderSearch(request.GET, queryset=orders)
    orders = myFilter.qs
    content = {
        'customer': current_customer,
        'orders': orders,
        'total_orders': orders.count(),
        'myFilter': filter ,
    }
    return render(request, 'accounts/customer.html', content)```
#

try that maybe?

native tide
#
<div class="row">
    <div class="col">
        <div class="card card-body">
            <form method="get">
                {{ myFilter.form}}
                <button class="btn btn-primary" type="submit">Search</button>
            </form>
        </div>
    </div>

</div>```
#

still no form

#
def customer(request, pk_test):
    current_customer = Customer.objects.get(id=pk_test)
    orders = current_customer.order_set.all()
    filter = OrderSearch(request.GET, queryset=orders)
    orders = myFilter.qs
    content = {
        'customer': current_customer,
        'orders': orders,
        'total_orders': orders.count(),
        'myFilter': filter ,
    }
    return render(request, 'accounts/customer.html', content)```

@rigid laurel isn't it the same

rigid laurel
#

Sorry - I don't think I can really help. My best suggestion is to take a step back and try from scratch. I haven't worked with the Django filters at all myself really

native tide
#

😫

rigid laurel
#

Honestly, this seems like a bad tutorial. The guy jumps about too much and doesn't explain things too clearly. You're on part 12, so you probably don't want to swtich - but if you do, I'd recommend checking out Corey Schafer's videos (linked to in !resources)

native tide
#

oh

#

i actually moved from corey schafer's to this one cuz i encountered an error on his tutorial which i've been posting to this python server for two days so i moved to this tutorial @rigid laurel

#

i'll start all over then

rigid laurel
#

I'm surprised you had such poor luck with the Corey Schafer stuff

#

I've heard he's very good

native tide
#

Corey Schafer does explain better tbh.

rigid laurel
#

either way - keep at it if you can. It might feel like you're making no progress, but even this stuff where you're running into walls, you probably are learning things

native tide
#

ye i know there was a problem on my end no one could help me with so i moved on to a different course.

simple sentinel
#

What error did you get with Corey Schafers? I'm running through parts of it now and it's been fine

native tide
#

admin page error

#

i couldn't add new users to the db

simple sentinel
#

What error did you get with adding new users?

native tide
#

i forgot i'll go check

#

i get this error @simple sentinel

#
OperationalError at /admin/auth/user/add/
no such table: main.auth_user__old```
#

when i try to add a new user

ocean sigil
#

Which version of django you use ?

native tide
#

3.0 @ocean sigil

real hare
#

Using Django, I'm getting the following exception: ValueError: Cannot query "mark": Must be "Author" instance. Trying to filter my blog posts based off the user that is logged in for the /profile/posts/ directory in the website. Here is what I've tried to do:

#
 class NewsListView(ListView):
    """ Paginated view for blog posts created. """
    template_name = 'news_post_list.html'
    model = News_Post
    queryset = News_Post.objects.filter(featured=True)
    paginate_by = 2
    ordering = ['-date_posted']

    def get_context_data(self, **kwargs):
        most_recent = News_Post.objects.order_by('-date_posted')[:3]
        np_auth = News_Post.objects.filter(author_id=self.request.user).values()
        context = super().get_context_data(**kwargs)
        context['most_recent'] = most_recent
        context['page_request_var'] = "page"
        context['queryset'] = self.queryset
        context['get_auth'] = np_auth
        return context

Model:

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

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

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

Using Django 3 btw

native tide
#

😫

nimble epoch
#

@real hare not sure that I can fix it but can I take a look at you view

real hare
#

The view is above

#

I'm using a Class based view @nimble epoch

#

I also realised I've omitted class in my example apologies

nimble epoch
#

Ok I take a look but not sure that I can fix it. I don’t use django😁

real hare
#

okay, thanks

nimble epoch
#

Yeaahh as I said. Sorry I couldn’t find the problem or the error is not related to this part

real hare
#

It's grand, I've worked it out now πŸ™‚ @nimble epoch

nimble epoch
#

πŸ‘

real hare
native tide
#

can you help me with my problem?

real hare
#

What's the issue @native tide

native tide
#

it's up there it got overwritten

nimble epoch
#

From Stackoverflow:

Quick note for people still finding this old issue: This case can also be caused by a ForeignKey/ManyToMany/OnetoOne that uses a string as reference that is invalid (eg: not correctly pointing to a model).

I was updating/refactoring a project and ran into this. Turned out it was just a typo.

Kinda weird django doesn't notify clearly it cannot resolve the string, could be because other apps confused it.

#

And here an example:

image = models.ForeignKey('core.image', related_name='post', blank=True, null=True)

image = models.ForeignKey('core.Image', related_name='post', blank=True, null=True)

Maybe something is wrong in your code like:
core.image, core.Image exactly like example above.

native tide
#

i have no idea where this error comes from

#

no

#

maybe yur right it points to something wrong or something

nimble epoch
#

It can be related to the relationships in your models

#

MAYBE

native tide
#

It all becomes very unclear sinds i am a noob a Django

nimble epoch
#

πŸ˜‚we were all like this or worse

#

But this all get experiences

native tide
#

well yeh got a poimt

past cipher
#

I have a question. I am creating a store where users can sign up, and sell digital products. Now all the payments are processed with Stripe, although I do plan on adding crypto currency and paypal eventually. Right now I have it setup so the user has to enter their Stripe API Keys.

My question is; do you think I should think of another way to do this? Even though I have instructions on how to obtain your API keys, I feel like some users won't be the brightest and may have trouble.

https://gyazo.com/6f8c52de6fc28398c88f32ee332f140f?token=f00d09e39d11f9c8e465b505ba3f59b5

cold anchor
#

have a link to a helpdoc article on how to do it

past cipher
#

I actually just decided to scrap this

#

and instead use Stripe connected accounts instead

past cipher
#
@seller_bp.route('/dashboard', defaults={'token': None, 'account_id' : None}, methods=['GET'])
@seller_bp.route('/dashboard?code=<account_id>&state=<token>', methods=['GET'])
@login_required
def seller_dashboard(account_id, token):
    if account_id != None:
        print(account_id)

when the url is /dashboard?code=<account_id>&state=<token> its not printing the account_id

[07/Jun/2020 22:28:51] "GET /dashboard?code=ac_HQMmNm43YNSx67v45hZzDUdpl5lAOoZa&state=Ktdz9C0UfJhxsPBrF0nn46u8a02kvLqi03 HTTP/1.1" 200 -

I am not sure how to achieve what I want. Does anyone here work with Flask?

cold anchor
#

never seen a flask route include query params in it, I usually do flask.request.args.get('code') if I want to get code out of the query params

warm igloo
#

Right, so @cold anchor has it right. You either need to do it as a route /dashboard/<account_id>/<state> which is weird in this context since your params are filters really (though this format is appropriate for certain routes obviously when designing say REST APIs).

So @past cipher Flask won't count anything after the ? as part of the route signature so those are functionally identical (so really they're both just /dashboard and you get them with request.args like @cold anchor shows above.

#
@seller_bp.route('/dashboard', defaults={'token': None, 'account_id' : None}, methods=['GET'])
@login_required
def seller_dashboard():
    account_id = flask.request.args.get('account_id')
    token = flask.request.args.get('state')
    if account_id != None:
        print(account_id)
celest torrent
#

I can't get an easy answer from the docs. What's the purpose of instance in django forms like this?

cold anchor
#

could you post the code of one of those two form classes? it might not be from the Django itself, but could be custom code?

celest torrent
#

@cold anchor Sure.

class ProfileUpdateForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ["avatar"]
cold anchor
#

where does forms.ModelForm come from? is that a django import?

celest torrent
#

Yeah, that just comes from

from django import forms```
cold anchor
#

ah, found the answer

#

(I'm guessing) to populate the initial form values on page load

#

I don't use django though so I'm not too sure

celest torrent
#

(I'm guessing) to populate the initial form values on page load
@cold anchor I think you're right. Both of these forms are used to update existing information

#

Thanks for your help

cold anchor
#

happy to help πŸ‘ usually these open source libraries are well documented and pretty easy to read- don't be afraid to dive into the source! it's just python after all

native tide
#

Hello

#

Im trying to get python and pip to install some things on EC2 .. but its not working well.

#

is this a good place to ask those kinds of questions?

warm igloo
distant trout
#

Hello, can someone help me figure out how to delete data for a current user without deleting everyone elses data.

#
@login_required
def delete_all_post():
    if current_user.is_authenticated:
        db.session.query(Post).delete()
        db.session.commit()
        flash('All of your post has been deleted!', 'success')
        return redirect(url_for('main.home'))```
#

this delete posts for all the users, but i only want it to delete post for the current user

#

my models

scenic vapor
#

Hello i wanna build a crud programme with react and google sheets as my database
do i need a backend like node or python flask?
i can just call the Google API from react right? or will this cause any issue?

warm igloo
#

Hello, can someone help me figure out how to delete data for a current user without deleting everyone elses data.
@distant trout

Add a where clause where your current user id == Post.user_id?

native tide
#

thanks @warm igloo I have a channel now. once ive typed a few things - what do I do next?

distant trout
#

OH, didnt think of that. ill try and figure that out, thanks @warm igloo

warm igloo
#

@native tide wait and hopefully someone will be along to help you -- which channel is yours, I'll give it a look but the help channels are routinely looked at and that's why the system is set up. So much noise in topic chats that requests for help can be overlooked so the help channels help elevate those.

#

@distant trout Roughly db.session.query(Post).delete().where(Post.user_id==current_user.id)? Sorry, I don't use SQLAlchemy often and write my own SQL.

#

I should probably practice with SQLAlchemy honestly if only to help more people as it comes up so often haha.

native tide
#

Hey

distant trout
#

@warm igloo thanks a lot, that gives me a general idea of what to do. even though it says "AttributeError: 'int' object has no attribute 'WHERE'"

cold anchor
distant trout
#

ill give it a read, thanks

valid crane
#

hi! is there a yt vid/ article that walks you through django web development? like how they professionally create websites, do both frontend & backend and how they manage their github repository? i was wondering about their approach to such projects as well as their organization of folders and such

edit: or if you know livestreams where i can see their workflow and learn from it

tame hatch
#

β€’ Why flask is not running localhost it is automatically truncated

vague apex
#

Is it possible to some parts of a python project in selenium and then continue the project in like regular python

shadow orchid
#

whats a good place to host a flask api app for free

uncut solar
gentle lark
#

^ agreed. there is also heroku and others that does free limited server

#

how would you take an int like 2200 from utc time and convert it into paris time?

shadow orchid
#

Ummmmmm

#

timestamp

#

and then you can parse

#

Using datetime

#

and use the conversion formula

gentle lark
#

how would you use the conversion formula?

#

i was able to parse the string and make it into a datetime object and thats as far as i got

native tide
#

how can i do that?

rose fulcrum
#

Hey
@native tide Hi, I use django quite a lot for my own websites

#

whats a good place to host a flask api app for free
@shadow orchid Brilliant nickname! I use pythonanywhere as well for our production site and I'm happy so far. Paid options are very configurable. However our site has fairly low visitor numbers so can't comment how it scales for heavier usage

shadow orchid
#

I see

#

alas it's an API

#

so the frontend is non-existent

#

i tried aout heroku and the dyno seems great

#

but i wi;; check oi=ut pythonanywhere

#

@rose fulcrum

#

also I plan on ,igrating to fast API

#

seeing flask has not been delivering high performance

native tide
#

someone has 1 second to help me with a basic problem regarding cookies? dm pls πŸ™‚

tame hatch
#

β€’ Why flask is not running localhost it is automatically truncated
@tame hatch
Anyone

verbal obsidian
#

@native tide no dms

celest torrent
#

Quick question. I have a comment form on a django blog. When I submit a comment through the view, it populates the form after submission. How do I stop this?

#

Here's my view

class PostsView(View):
    def get(self, request, pk):
        comment_form = CommentForm()
        context = {
            "comment_form": comment_form,
            "post": Post.objects.filter(pk=pk).first()
        }
        return render(request, "blog/post_detail.html", context)

    def post(self, request, pk, *args, **kwargs):
        comment_form = CommentForm(request.POST)
        comment_form.instance.author = self.request.user
        comment_form.instance.post_id = pk
        if comment_form.is_valid():
            comment_form.save()
            context = {
                "comment_form": comment_form,
                "post": Post.objects.filter(pk=pk).first()
            }
            return render(request, "blog/post_detail.html", context)
tame hatch
past cipher
#

@warm igloo thanks for your reply. The problem I am having is I get redirected from stripe, and the url is /dashboard/connect/?code=ac_HQbTLu7ek5Teodzh30378vVjTZz6Dvqg&state=JG30QDALasNHt0LsFbwzEBQBDWy3NkNy0U

But flask won't work with the ? inside the url

#

@seller_bp.route('/dashboard/connect/code=<account_id>&state=<state>', methods=['GET']) works fine
but
@seller_bp.route('/dashboard/connect/?code=<account_id>&state=<state>', methods=['GET']) does not

#

nevermind I fixed it by doing /dashboard/connect and then using request.args

warm igloo
#

yup was about to say that

#

anything after query ? is ignored as part of route and only accessible via request.args

#

glad you got it working

#

@tame hatch
Answer pls @anyone
@tame hatch

A couple things: explain your situation a bit more, please. Share code (via a pastebin if it is a long example), please. And the image you keep linking to? I can't see it:

<Error>
<Code>AccessDenied</Code>
<Message>Access denied.</Message>
<Details>
Anonymous caller does not have storage.objects.get access to the Google Cloud Storage object.
</Details>
</Error>
tame hatch
#

@tame hatch

A couple things: explain your situation a bit more, please. Share code (via a pastebin if it is a long example), please. And the image you keep linking to? I can't see it:

<Error>
<Code>AccessDenied</Code>
<Message>Access denied.</Message>
<Details>
Anonymous caller does not have storage.objects.get access to the Google Cloud Storage object.
</Details>
</Error>

@warm igloo

The image is below and this is not code related question

shadow orchid
#

helllo

#

so I am ysing fastapi

#

I want to run PIL code in executor

#
fn = partial(getpixel,byt)
            loop = asyncio.get_event_loop()
            img = loop.run_in_executor(None,fn)```
#

I get an error

cursive dirge
#

@celest torrent I'm not sure that i understand what is your problem. What do you want to remove ? The comments display section ?

celest torrent
#

Sorry, no. The form was being filled AFTER I submitted it, whereas I wanted the field to be empty

#

I've resolved it

    def post(self, request, pk, *args, **kwargs):
        comment_form = CommentForm(request.POST)
        comment_form.instance.author = self.request.user
        comment_form.instance.post_id = pk
        if comment_form.is_valid():
            comment_form.save()
            # context = {
            #     "comment_form": comment_form,
            #     "post": Post.objects.filter(pk=pk).first()
            # }
            # return render(request, "blog/post_detail.html", context)
            return redirect("post-detail", pk=pk)
cursive dirge
#

Oh ok. Your problem is that you send your comment_form in your context. I'm not sure because i don't know how your html file looks like but i'm pretty sure it will resolve your issue πŸ™‚

celest torrent
#

Thank you

cursive dirge
#

np πŸ™‚

silent heart
#

@everyone u should add gilbert#1030

native tide
#

Is there a function to use the current HTML as like a layout.html then add content to the layout?

#

can i freely access the admin page on a website build with django

#

Is there a function to use the current HTML as like a layout.html then add content to the layout?
@native tide with what framework?

#

Django

#

Im migrating from Laravel

jaunty zinc
#

I have a flask app and I want to make it scalable. other than switching to django/other frameworks, how can I make it scale horizontally? and do flask blueprints help with scalability? to me, they just look like a way to organize code better

zealous siren
#

scale how?

jaunty zinc
#

when I say scale horizontally I mean many concurrent users

zealous siren
#

generally by multiple instances behind a load balancer

jaunty zinc
#

alright, so the key is changing the way we serve the app, right? is there anything we can change in our codebase to make it scale well?

native tide
#

@native tide

#

Are you here?

zealous siren
#

sratna, making sure it can handle multiple instances doing something

opaque vigil
#

Hello everyone. Anyone is familiar with some good Tutorial with Django Rest Framework and imageField? I have a model Called Image and one called Product, and i have created a one-to-many relations

#

but i don't know how to serialize it

#

I have looked at the Documentation, but there is no serialization field for images

cursive dirge
opaque vigil
#

Yes, I am using that, but I don't know how to use it in my serializer as a related object.

#

Here is what i have tried

#

In my admin panel everything works fine. On a dog instance you can upload multiple images, and a name, but i need it to work with serializers

#

So i could create a details page

cursive dirge
#

I don't know your code but it seems that your serializer needs you to override functions to do what you want to do

#

it's to specific to be handled by the generic model serializer

opaque vigil
#

Are you familiar maybe with some tutorial with django rest framework and images?

native tide
#

Yes I'm now @native tide . Shouldn't you use the jinja syntax to enter values in the HTML template?

cursive dirge
#

nop sorry but in my opinion, the best way to learn how it works is to try to understand how it works behind

#

gl for your project πŸ™‚

opaque vigil
#

Thanks

native tide
#

This @native tide

late gale
#

Hey I am using django i was making an Arabic version for my website I installed gettext and i ran the code django-admin startmessages -l ar so it created the folder for me I translated the words that i want and after i finished i ran django-admin compilemessages and I changed the language code in the settings.py from en-us to ar this should work and the translation should come in action but the problem it doesn't no translation take an action and thanks for your help

native tide
#

What are you trying to do exactly @native tide ?

#

Migrate from laravel

#

to django

#

You know laravel has controllers and MVC views

#

thats what im trying to achive

#

i don't know what laravel is😡

#

same thing as django

hidden pier
#

so here you have more of ModelViewTemplate (MVT), not exactly MVC

native tide
#

but different structure

#

πŸ€” Ahh

hidden pier
native tide
hidden pier
#

aka controllers

native tide
#

Can you make py classes?

hidden pier
#

sure

native tide
#

Ok good

hidden pier
#

there are Class Based Views

#

love them

native tide
#

I would want it to example do the following

hidden pier
native tide
#

/launch/set

#

/launch/get

#

etc...

hidden pier
#

nice sum up of class based views

#

you can make class based view and implement methods for each HTTP method

#

e.g. def get()... will handle HTTP GET etc, all can be done

native tide
#

can i get a HTTPResponse Route

#

like example get path would be /launch/starlink 7

hidden pier
#

request.path or something

native tide
#

Alright Awesome

#

Im guessing its more simple than laravel

hidden pier
#

but you would probably want to look at urls.py

#

there is all routing magic

native tide
#

path('articles/int:year/', views.year_archive),

hidden pier
#

like example get path would be /launch/starlink 7
@native tide path('starlink/<int:id>/', views.some_starlink_view),

native tide
hidden pier
#

yep

native tide
#

cause starlink 7 is not a int

hidden pier
#

I was already typing that for ya πŸ˜‰

#

oh

native tide
hidden pier
#

<str:id>

native tide
#

for example

hidden pier
#

python string type is str πŸ™‚

native tide
#

True

#

🀣

#

I still get mixed up

hidden pier
#

no worries, I do python + JS

#

hard time

#

true vs True

native tide
#

Hopefully i can fully migrate my site to Python

#

I really love the programming language

#

It seems faster to code

hidden pier
#

Oh yeah, Django does a lot for you

#

anyway, good luck πŸ˜‰

native tide
#

πŸ€”

#

oh nvm

#

I know what's wrong

#

urlconf_module = import_module(urlconf_module)
File "/usr/lib/python3.8/importlib/init.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 783, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/home/xilog/autotek/at/urls.py", line 2, in <module>
from . import views
File "/home/xilog/autotek/at/views.py", line 8
def launch(request, id)
^
SyntaxError: invalid syntax

cold anchor
#

you need a colon after the ) when you declare a function

native tide
#

ok ty

hidden pier
#

Hey I am using django i was making an Arabic version for my website I installed gettext and i ran the code django-admin startmessages -l ar so it created the folder for me I translated the words that i want and after i finished i ran django-admin compilemessages and I changed the language code in the settings.py from en-us to ar this should work and the translation should come in action but the problem it doesn't no translation take an action and thanks for your help
@late gale I don't think this would work. Did you define LANGUAGES in settings.py?

native tide
#

Made it work πŸ˜„

hidden pier
#

πŸ‘ πŸ™‚

celest torrent
late gale
#

@hidden pier Nope , should I and shall it be defined as a list like this

LANGUAGES = [ 'ar , 'en' ]

or ?

late gale
#

@celest torrent That's pagination you can access its view by the from the post view in your views.py

#

@hidden pier I fixed it

#

You know what was the problem

#

Single quotes instead of double quotes

#

LMAO!!!

native tide
#

Im Operational πŸ˜„

#

Our main website just got pushed a git and we're now running 100% Python

arctic fog
#

Hello, I am using pythonanywhere to host my flask website. My websites runs a separate python file (the file is 500 lines long) perfectly on localhost. When I host my website on pythonanywhere, I get a 500 internal server error. I'm guessing it's from overloading. Is there any way to fix this issue? Any help would be greatly appreciated.

late gale
#

try to make ur DEBUG = True so you can see the issue

#

@arctic fog

native tide
#

I am trying to access a user page here```python

@login_required(login_url='login')
@allowed_users(allowed_roles=['customer'])
def user_page(request):
orders = request.user.customer.order_set.all()
total_orders = orders.count()
delivered = orders.filter(status='Delivered').count()
pending = orders.filter(status='Pending').count()
content = {'orders': orders,
'total_orders': total_orders,
'delivered': delivered,
'pending': pending
}
return render(request, 'accounts/user.html', content)

arctic fog
#

I already have my debug enabled in my flask app, but doesn't seem to be working. @late gale

native tide
#

this is the user or customer model

#
class Customer(models.Model):
    user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
    name = models.CharField(max_length=200, null=True)
    phone = models.CharField(max_length=200, null=True)
    email = models.CharField(max_length=200, null=True)
    date_created = models.DateTimeField(auto_now_add=True, null=True)

    def __str__(self):
        return self.name```
late gale
native tide
#

and here i have a decorator

#

def admin_only(view_func):
    def wrapper_func(request, *args, **kwargs):
        group = None
        if request.user.groups.exists():
            group = request.user.groups.all()[0].name
        if group == 'customer':
            return redirect('user_page')
        if group == 'admin':
            return view_func(request, *args, **kwargs)
    return wrapper_func```
#

this is the user template

#
{% extends 'accounts/base.html' %}

{%block content %}
{%  include 'accounts/status.html' %}

<div class="row">
    <div class="col-md">
        <div class="card card-body">
            <table class="table table-sm">
                <tr>
                    <th>Product</th>
                    <th>Category</th>
                    <th>Date Orderd</th>
                    <th>Status</th>
                </tr>

                {% for order in orders %}
                <tr>
                    <td>{{order.product}}</td>
                    <td>{{order.product.category}}</td>
                    <td>{{order.date_created}}</td>
                    <td>{{order.status}}</td>
                </tr>
                {% endfor %}
            </table>
        </div>
    </div>
</div>
{%endblock%}```
#

and when i try to log in with the new user

#

and try to access the user page

#

i get this error:

#
RelatedObjectDoesNotExist at /user/
User has no customer.
late gale
#

Catch the error try to say in ur views if user dont have a customer then catch the error and create it

native tide
#

full traceback:```

Traceback (most recent call last):
File "C:\Users\Angelo Hoft.virtualenvs\django_project-0DacM128\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\Angelo Hoft.virtualenvs\django_project-0DacM128\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\Angelo Hoft.virtualenvs\django_project-0DacM128\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Angelo Hoft.virtualenvs\django_project-0DacM128\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "C:\Users\Kenny\Projects\django_project\follow_project\accounts\decorators.py", line 21, in wrapper_func
return view_func(request, *args, **kwargs)
File "C:\Users\Kenny\Projects\django_project\follow_project\accounts\views.py", line 63, in user_page
orders = request.user.customer.order_set.all()
File "C:\Users\Angelo Hoft.virtualenvs\django_project-0DacM128\lib\site-packages\django\utils\functional.py", line 225, in inner
return func(self._wrapped, *args)
File "C:\Users\Angelo Hoft.virtualenvs\django_project-0DacM128\lib\site-packages\django\db\models\fields\related_descriptors.py", line 423, in get
self.related.get_accessor_name()

Exception Type: RelatedObjectDoesNotExist at /user/
Exception Value: User has no customer.```

native tide
#

i am following along with a tutorial

#

and i am doing the same stuff as the course teache

#

so i don't know why it won't work for me

late gale
#

I think i mentioned that u can catch the error and create it if he is not exist

#

here
from django.core.exceptions import ObjectDoesNotExist

#

try to catch it

#

gonna give an example

native tide
#

i tried deleting with which i tried to log in at the admin URL

arctic fog
#

Thanks, I will look into it! @late gale

native tide
#

but now get this error

#
__str__ returned non-string (type NoneType)```
#

but where should i catch

#

it

late gale
#

it has nothing to do with that

native tide
#

i'm not even sure where the erro comes from

late gale
#

am i invisible to you

native tide
#

i see you as bright as day

#

yes

#

i did what you said alright

#

i figured out that the user didn't actually register

#

thx

#

I created two by accident

#

one blank and one filled with user

#

and logged in with the blank one

#

Sorry if i mad you mad or anythingπŸ‘πŸΌ@late gale

late gale
#

np its okay

#

glad it works

mint umbra
#

I apologize if this question is a bit too general, but I have a textarea that the user types in on my website. I want to implement a "WPM" counter, but I am not completely sure how I would do this. Any help would be greatly appreciated!

cold anchor
#

if you had a stopwatch, a pen, and a piece of paper how would you do it?

#

like, without code, what are the steps?

mint umbra
#

@cold anchor sorry for the late response. Probably record the number of words I typed and divide by the number of minutes typed, or the number of letters typed divided by 5, divided by the amount of minutes typed. However, I'm not sure how I would get this to work on my site.

cold anchor
#

ah, okay, well it might help to know that you can set a timed function in javascript

#
const countWPM = () => { ... }
setTimeout(countWPM, 1000 * 60 * NUM_MINUTES)
#

then you can use JS to grab the textarea's contents and count the words (or letters divided by 5) and divide that by the time that passed

cosmic kraken
#

Does anyone if it's possible to make a Chrome extension in Python?

mint umbra
#

@cold anchor ok thanks! will keep that in mind. Sorry for asking multiple questions, but what are the 1000 and 60 numbers there?

cold anchor
#

the frontend for all browser extensions are written in JS, but the backend can be in python

mint umbra
#

I see

#

I'm very new to JS

#

thank you for all your help!

cold anchor
#

no problem!

distant trout
#

someone know why this is happening?

#
class ContactForm(FlaskForm):
    name = StringField('Name', validators=[DataRequired()])
    email = StringField('Email', validators=[DataRequired(), Email()])
    message = TextAreaField('Message', validators=[DataRequired()])
    submit = SubmitField('Send Message')
cold anchor
#

what's the view function code?

distant trout
#

what you mean? the route?

#
@main.route('/contact')
def contact():
    form = ContactForm
    return render_template('contact.html', title='Contact Me', form=form)
cold anchor
#

you're not instantiating your form

#

ContactForm()

#

not ContactForm

distant trout
#

oh wow..

#

didnt even see that

cold anchor
#

in fact, you want to use form = ContactForm(flask.request.form)

#

to allow values to repopulate when submitted with values that don't validate

distant trout
#

ahhh okay

#

thanks a lot!! @cold anchor

cold anchor
#

no problem!

#

there's a couple more things you want to do actually, let me just pull up a quick example

distant trout
#

oh alright

cold anchor
#

@blueprint.route('/formpage', methods=['GET', 'POST'], strict_slashes=False)
def myformpage():
    form = LoginForm(request.form)
    if request.method == 'POST':
        if form.validate_on_submit():
            return redirect(url_for('app.render'))
        else:
            flash_errors(form)
    return render_template('showform.html', form=form)
#

flash_errors is a custom function that helps to display wtform errors

distant trout
#

oh

#

so it would display error if the user puts in something invalid?

cold anchor
#

from flask import flash

def flash_errors(form, category='warning'):
    """Flash all errors for a form."""
    for field, errors in form.errors.items():
        for error in errors:
            flash('{0} - {1}'.format(getattr(form, field).label.text, error),
                  category)
#

yeah

#

and flask has some builtin stuff to flash a message that you can put in a template

distant trout
#

oh

#

could u explain to me what this is doing if request.method == 'POST':

#

when the user sends the msg it is using POST?

cold anchor
#

when a <form> element gets submitted, the default HTTP method is POST

distant trout
#

ahh

#

awesome, im going to experiment with those code! again, thank you

cold anchor
#

no problem, last thing to put in the template to show the flashed messages:

#
{% with messages = get_flashed_messages(with_categories=true) %}
    {% if messages %}
    <div class="row">
      <div class="col-md-12">
        {% for category, message in messages %}
        <div class="alert alert-{{ category }}">
          <a class="close" title="Close" href="#" data-dismiss="alert">&times;</a>
         {{message}}
        </div><!-- end .alert -->
        {% endfor %}
      </div><!-- end col-md -->
    </div><!-- end row -->
        {% endif %}
    {% endwith %}
distant trout
#

this goes in the layout template, am i correct

#

or does it go on the template of the page itself

cold anchor
#

customize the HTML as you want but the key is get_flashed_messages which you can use in the jinja context

#

any one you want the messages in, I usually put it in the layout

distant trout
#

oh, ill do just that. thanks

mint umbra
#

hello, I have a quick question. I have two divs that are being updated very quickly on my site. My code makes them show numbers. However, I am also trying to get them to show something like "seconds" after the number. Sorry if my explanation is a bit unclear

#

if I just try

#
<div class="timer" id="timer">0</div>seconds
#

the "seconds" goes on the next line and (because it isn't in the div) isn't affected by my "timer" css.

#

does anyone know of any way that I might include an extra word like this?

cold anchor
#
<div class="timer"><span id="timer">0</span> 
 seconds</div>
#

div's default display is "block"

#

so you can either change that (to inline, or inline-block)

#

or you can add an element inside that is default inline-block styled (like a span)

mint umbra
#

this solved my issue, thanks!

strong cradle
#

Hi I was working on flask docker uwsgi nginx application, I am getting this error, work fine for small apis like return string in response but gives error for one api
*1 upstream prematurely closed connection while reading response header from upstream

#

new to uwsgi nginx deployment

#

Is it because of nginx timeout or uwsgi timeout?

hasty remnant
#

Does anyone know any good courses to learn rest apis with django?

native tide
#

I can recommend the manga guide to databases

#

But that's a book

#

Only if you enjoy reading manga obviously, but the Manga Guide series is really nice as an introduction to many subjects

quick cargo
#

that sounds like an amazing idea for tutorials

#

Manga + Comp sci stuff

native tide
#

Those that I've read were all pretty decent

#

I've got the Databases, Calculus and Linear Regression Analysis

#

They all do a good job at introducing the topics to you and teaching you the basics

#

which reminds me I should figure out where I put the calculus one and reread it

#

Or find a better book, cause the script from my lecture is really not suitable for learning

verbal obsidian
#

You have plenty of tutorials

#

any will do

#

database normalization is generally a 'begginers topic'

#

not that complex

sudden crest
#

so I have a slightly strange plan

#

I want to see if it's possible to conduct Single Sign On over HTTP, not HTTPS

#

between a local application and a remote server, without a domain

#

so the current plan is that the local application triggers the Google (for example) login flow, and obtains an ID token

#

it then signs a JWT with that token (the JWT payload is a message which the user wants to send to the server, as well as the user id that the user wants to authenticate as)

#

the idea is then that the server figures out what the client token should be based on the transmitted user id, then verifies the JWT against that token

#

the issue is that normally the oauth flow is that you can verify a user token, but not necessarily arbitrarily determine the valid SSO token without knowing it

distant trout
#

can someone help me with bootstrap cards? I want to make it so the cards are side by side instead of being in a line

#

this is how its right now

#

i want the bottom card to the right of the first card

warm igloo
#

You need to put them in the grid then.

#

Using bootstraps row/col classes.

distant trout
#

so I have to put all the cards inside a div with the rows/col?

warm igloo
#

Not necessarily a div but yes.

Since you’re already using bootstrap might as well use their grid classes. And then you can drop that online style too.

#

Unless you still need it.

distant trout
#

ahhh i see

#

thank you πŸ‘

thorny geyser
#

what are the best open source flask projects?

native tide
#

Awesome am i doing it correctly?

#

Cause idk it seems weird to do a sys.path.append

#

Basicly im making my own library

native root
#

Since this seems to be django, I'd strongly suggest looking into django's "import_path" functionality, and importantly importing when the server starts and not on every request like you're doing there