#web-development
2 messages Β· Page 63 of 1
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"
yup that what i am trying to do
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
and how to fix that
Simplest way is probably to just edit the user in the admin screen
so i make him the super user?
He already is?
nope he is just active
I'm loggedin as the active user not the super one
did you create that user before adding the post_save code?
Logging out and back in, I guess
that won't change anything
Since User stores last login time, logging out and in should call User.save()
That should call your post_save handler
and fix things
why should i add User.save() when django saved the user once registered
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)
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
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
true
so created is True, but you still need to add a profile
You need to ensure that the user object has a profile attached
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?
No, it checks if the user is being created, and if so adds a profile
ooh
Actually I'm going to give you an easier solution, sorry about not thinking about it earlier
np
ofc
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
can't i just remove them from the admin page?
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?
@uncut yarrow see #βο½how-to-get-help
i can add this to the views
You could, but it's written to apply to all models of course
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
π
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
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 %}
what do you mean by the template is only given one meeting?
sorry I am very new to django
return render(request, 'template_name_snip', {'meeting': meeting})
the {'meeting': meeting} is the variables passed to the templates
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
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
wdym by that?
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?
oh yea thats beacuse thats in another views.py file
should i maybe move my detail function to that same file?
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
ok will try to fix based off information you gave me thx
Hey, what would you guys reccomend as a good authentication as a service provider for a website?
auth0
ok, thanks
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
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.?
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
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
Can I using flask_login see if a view has a decorstor like login_required?
Why do you need that @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
u didnt closed name in app route
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
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/
hello anyone have simple website project that i can use for reference .. ? new to django framework and also new to website development
https://github.com/RohanJnr/IceBook-Django
@pure hill
Hello everyone
is it Flask a good learning path for someone who never did a thing about web development?
what's best? django or flask?
@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
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.
neither username or email can be null
have you check that none of those are null?
yeah, i have email and username filled in
the user id also works https://i.imgur.com/XwNfwm3.png
do you have any posts linked to this user?
it looks like deleting user breaks constraint on some post
maybe delete cascade is needed?
hmm not sure what that is but i show u my post model
ok
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
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
Postmodel to nullable - delete cascade -> deletign user deletes all related objects, like user posts
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
close, deleting the user makes Post relation to that user invalid, because relation is set to nullable=False
OH
so it has to point to some user
i see
you can make a guardian user "deleted" and always switch post owner to this
wait is deleting cascade part of sqlalchemy
it is even part of SQL itself
oh, that seems to be the best choice for me. I am going to research more into that right now
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?
Thank you!!
Thank you!!
@distant trout in the view you can use,if request.user.is_authenticated
@verbal obsidian inside the delete_account route?
oh lol, its okay
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
Thank you very much, I did not think it would be that simple
also, If you need that for the entire view
you can use the @login_requred decorator
Awesome, thank you π
Is it just me, or developing user interfaces in js/css is very time consuming?
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_requreddecorator
yep, django is awesome, you always have thatrequest.userobject and it's the logged in user orAnonymousUserby default and the have all this crazy methodsis_authenticated/is_activeetc.
Whitch python web framework is best for website?
Hi I am looking for freelancers who would like to work on a social media app. Anyone interested please DM me.
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!
use redirect on a post req
@marsh canyon how would I do that? Sorry for continuing this
flask.redirect('/other-path')
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
Hey y'all, can somebody point me the right direction how I can pass this API response to a pandas dataframe?: https://api.pushshift.io/reddit/search/submission/?subreddit=NEO&after=1500004800&size=10&fields=author,created_utc,full_link,num_comments,score,selftext,title
how does laravel work
This is the #web-development channel of a python discord, of course there are people who use django
@bleak bobcat anyone using python here?
Hmm. I'd have to check, not sure.
Can someone point me in the right direction for learning Django i tried the bloody tutorial 2 times from scratch and i Fail miserably...?
Two scoops of django is pretty great and they just released their new version
I feel you
I wish ;)
I tried learning django about two years ago but i'm not a dev
haha easy there partner
Learning dash might be a good place to start if you have some python experience
depending on what your end goal is
I have some Flask and some PyQt expirience
I would give Dash a look as you would know your needs better than me
I would like to build up an web service from ground up
maybe django might be better
@opaque sail maybe try a video?
https://www.youtube.com/watch?v=F5mRW0jo-U4
Learn the Python Django framework with this free full course. Django is an extremely popular and fully featured server-side web framework, written in Python. Django allows you to quickly create web apps.
π»Code: https://github.com/codingforentrepreneurs/Try-Django
βοΈCourse Co...
I tend to learn best that way myself
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...
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!
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?
@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' %}```
What's the line of the template look like?
what do you mean? like the views.py or the actual html file?
(sorry im really new to this)
Template refers to the .html
Okay, and you're DIRS right? In your code you have it as DIR
I did not. Im gonna try changing that
er i mean i did have DIR not DIRS
OK i changed and i am now getting this now.
Hmm. Might have mixed it up with STATIC_ROOT, though that's what you already had.
so should i change the 'static' in STATIC_DIRS to my original assets folder?
Try it
I always just have a single atatic folder with child folders.
static*
And then use the relative path in the template
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
Hi friends I'm new in Django can you put me on the right track
Subfolders.
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!
@coarse bay I need to know how to start
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
@coarse bay Not exactly, but it's okay
@coarse bay Do you have the resources to learn?
like some youtube videos?
@coarse bay
And books, Sites
ok! so i dont know about books but lemme go look through my bookmarks
heres one: djangocentral.com
Django Central is an educational site providing content on Python programming and web development to all the programmers and budding programmers across the internet. The main goal of this site is to provide quality tips, tricks, hacks, and other Programming resources that allo...
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
@coarse bay yes I've learned html & css but i'll never in Javascript
thats fine i haven't had to use javascript yet i just know its kinda important
I highly recommend the book "Django 3 by Example".
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
np
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!
Okay yes thank you Pro
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.
I actually use Vue CLI to compile to HTML first.
And, mustache templating is possible, if you need SSR, or server to HTML communication. https://github.com/defunkt/pystache
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
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!
@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.
yea thats possible
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
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.
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
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).
@native pasture POST I believe, I removed GET and it still works
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(...)
Also, check the docs: https://flask.palletsprojects.com/en/1.1.x/api/#incoming-request-data
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)
@native pasture sorry for the super late response. This solved my issue! thank you so much
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.
im trying to run my flask program on flask_socketio
i did everything as mentioned in docs, but page isn't loading at all
Has anyone tried to use python/flask through a cPanel app? I'm totally lost
@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.
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?
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?
@next tree If you don't need Jinja2 templating, just throw everything into static folder, and it should be fine.
how can i deploy my flask server to an different address than localhost(127.0.0.1) ?
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)
@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 :-)
If any of you dumb asses need help, dm me
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?
Build a rest API that bot can post to
that is what I was thinking, but it felt silly
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
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
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.
best practice is REST API from Django because proper microservice is Django should be only one to mess with it's database
would it be reasonable to do all the DB stuff through the discord bot, but still be able to manage it though django?
doing MySQL queries is probably easier
ok, I am very interested in best practice though
Best Practice, REST API the bot reads/writes to
what are you hopingt o change on the bot from Django?
It is basically just data for an RPG game I made for the bot that is currently just locally stored in JSON
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.
ok
And allow users to create/delete/modify their characters through the site
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
I was aware of that when I decided to use MySQL thank you LOL
make sure you use aiohttp on discord.py side to prevent blocking
But setting up postgress failed for me like 5 times on ubuntu so I gave up lol
but yea, REST API, gold standard in moving data between applications
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
it was suggestion, MySQL/MariaDB isn't terrible and depending on your size, it may not matter
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
well luckily Django means I can remain ignorant of that
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?
Guys have someone good tutorial for django?
Yeah use Flask instead
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?
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
i'd like to not use it but it's not mine

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?
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
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?
I am using paypal api
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?
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
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
anyone got any projects there working on
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}}"
Whats a good way to verify emails like by sending a verification link to email in python?
anyone have a while to teach some html, i have not used html for a while
@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 check out ItsDangerous! This package has some utilities for signing, unsigning, and validating info. Specifically useful for the functionality you mentioned.
@past cipher You can use str.format in Jinja hey?
https://jinja.palletsprojects.com/en/2.11.x/templates/#python-methods
Thanks will check it out now
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!
Perfect!! Thank you very much @outer apex. I searched around for over an hour and couldn't find what I wanted
Oh yay!
@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
hi, i have a problem with my view, it returns none, and u know the django error
heres my views.py
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,})
@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
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
many to many sounds wrong; can one pizza live in two carts?
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?
hello guys, i have a problem with flask for upload file anybody can help me ?
sorry for my english
it's good
@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
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
I haven't decided actually on nginx or apache idk what do you think
I'll probably wait till I learn a bit more python
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```
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
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
What value are you trying to get? You just have submission buttons but no form inputs. Try looking through: https://docs.djangoproject.com/en/3.0/topics/forms/#building-a-form
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.
@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
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
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?
@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.
At what point do you think the sample size would be large to see any payoff, 10,000?
enough to*
Depends on what you mean by "predictive understanding"
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.
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.
@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.
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.
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.
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.
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.
Thanks. I didn't mean to put you in an uncomfortable position. I'll try that.
Sorry that I did.
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
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
@native root that would be 2 blurred layers if I did that!
No, just one, since you don't blur the upper layer anymore
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
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
hi so i need help at this i need from this url (http://localhost:8080/login?code=EULPK3PWJC1OLDY16UCLDKEZGUDLXUOYMP&state=342725139626065920) to get the code and state as parameters how do i do it i am using flask
BTW if you answer pls mention me
@spark frigate you want to add the code and the state as parameters to your endpoint?
so the code is a string and the the state is an int?
yes
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)
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
Multi parameter search form with django filter form.
Follow me on Twitter: https://twitter.com/dennisivy11
Linkedin: https://www.linkedin.com/in/dennis-ivanov/
Source code + Live Demo: https://dennis-sourcecode.herokuapp.com/26/
Django Filter documentation: https://django-f...
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
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.
i meet the requirements of all the rules except the last one. I'm kinda need to solve this problem fast.
I mean meh
Theres all sorts
Django is a very heavy framework
Flask is a light micro framework
I mean is choice at the end of the day
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
you mean pagination?
https://www.youtube.com/watch?v=PSWf2TjTGNY&lis @fickle fox
In this Python Flask Tutorial, we will be learning how to use pagination within our application. Pagination allows us to only load a select number of items at a time so that our application doesn't get bogged down. We will also learn how to display links to different pages at ...
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```
Multi parameter search form with django filter form.
Follow me on Twitter: https://twitter.com/dennisivy11
Linkedin: https://www.linkedin.com/in/dennis-ivanov/
Source code + Live Demo: https://dennis-sourcecode.herokuapp.com/26/
Django Filter documentation: https://django-f...
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>```
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
I'm am also a complete beginner at Djangoπ
Do any filters work for you?
What does your Order model look like?
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'```
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
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
To double check, you do have a customer/2 right?
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?
<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
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
π«
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)
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
I'm surprised you had such poor luck with the Corey Schafer stuff
I've heard he's very good
Corey Schafer does explain better tbh.
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
ye i know there was a problem on my end no one could help me with so i moved on to a different course.
What error did you get with Corey Schafers? I'm running through parts of it now and it's been fine
What error did you get with adding new users?
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
Which version of django you use ?
3.0 @ocean sigil
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
Here is the stack trace:
https://pastebin.com/68THCvuH
Using Django 3 btw
π«
@real hare not sure that I can fix it but can I take a look at you view
The view is above
I'm using a Class based view @nimble epoch
I also realised I've omitted class in my example apologies
Ok I take a look but not sure that I can fix it. I donβt use djangoπ
okay, thanks
Yeaahh as I said. Sorry I couldnβt find the problem or the error is not related to this part
It's grand, I've worked it out now π @nimble epoch
π
Changed it over to:
np_auth = Author.objects.filter(id=self.request.user.pk).values()
can you help me with my problem?
What's the issue @native tide
it's up there it got overwritten
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.
i have no idea where this error comes from
no
maybe yur right it points to something wrong or something
well yeh got a poimt
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
have a link to a helpdoc article on how to do it
I actually just decided to scrap this
and instead use Stripe connected accounts instead
@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?
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
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)
I can't get an easy answer from the docs. What's the purpose of instance in django forms like this?
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?
@cold anchor Sure.
class ProfileUpdateForm(forms.ModelForm):
class Meta:
model = Profile
fields = ["avatar"]
where does forms.ModelForm come from? is that a django import?
Yeah, that just comes from
from django import forms```
ah, found the answer
looks like model forms pull data out of the model instance and pass it to the form https://github.com/django/django/blob/master/django/forms/models.py#L288-L294
the base form then gets passed that data as initial_data which gets assigned to self.initial and gets pulled out here https://github.com/django/django/blob/38a21f2d9ed4f556af934498ec6a242f6a20418a/django/forms/forms.py#L482-L490
(I'm guessing) to populate the initial form values on page load
I don't use django though so I'm not too sure
(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
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
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?
This is more specific to web development. You might have more focused help using the help channels #βο½how-to-get-help
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
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?
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?
thanks @warm igloo I have a channel now. once ive typed a few things - what do I do next?
OH, didnt think of that. ill try and figure that out, thanks @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.
@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'"
this looks helpful https://stackoverflow.com/questions/27158573/how-to-delete-a-record-by-id-in-flask-sqlalchemy#27159298
ill give it a read, thanks
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
Is it possible to some parts of a python project in selenium and then continue the project in like regular python
whats a good place to host a flask api app for free
Host, run, and code Python in the cloud: PythonAnywhere
^ 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?
Ummmmmm
timestamp
and then you can parse
Using datetime
and use the conversion formula
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
Hey
@native tide Hi, I use django quite a lot for my own websites
www.altimapa.com and www.wedidit.app
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
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
someone has 1 second to help me with a basic problem regarding cookies? dm pls π
β’ Why flask is not running localhost it is automatically truncated
@tame hatch
Anyone
@native tide no dms
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)
Asked in #help-cookie
https://cdn.discordapp.com/attachments/650401909852864553/719436855963156500/20200608_115423.jpg
@tame hatch
Answer pls @anyone
@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
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
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
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
@celest torrent I'm not sure that i understand what is your problem. What do you want to remove ? The comments display section ?
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)
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 π
Thank you
np π
@everyone u should add gilbert#1030
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
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
scale how?
when I say scale horizontally I mean many concurrent users
generally by multiple instances behind a load balancer
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?
sratna, making sure it can handle multiple instances doing something
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
@opaque vigil django-rest-framework.org/api-guide/fields/#imagefield you're welcome π
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
I have tried something like this: https://www.django-rest-framework.org/api-guide/relations/
Django, API, REST, Serializer relations
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
Are you familiar maybe with some tutorial with django rest framework and images?
Yes I'm now @native tide . Shouldn't you use the jinja syntax to enter values in the HTML template?
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 π
Thanks
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
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
so here you have more of ModelViewTemplate (MVT), not exactly MVC
aka controllers
Can you make py classes?
sure
Ok good
I would want it to example do the following
I personally recomend this site: https://ccbv.co.uk/
The best way to understand Django's class-based views is to see it in Classy CBV, so pick your version and jump in at the deep end.
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
request.path or something
but you would probably want to look at urls.py
there is all routing magic
you type paths and give views which ought to handle the logic https://docs.djangoproject.com/en/3.0/topics/http/urls/#example
like example get path would be /launch/starlink 7
@native tidepath('starlink/<int:id>/', views.some_starlink_view),
so i'd need to do string:launch
yep
cause starlink 7 is not a int
look at https://automatedtek.net/launch/Starlink 7
<str:id>
for example
python string type is str π
Hopefully i can fully migrate my site to Python
I really love the programming language
It seems faster to code
Can someone help me here
https://discordapp.com/channels/267624335836053506/366673702533988363/719588000069320744
π€
oh nvm
I know what's wrong
maybe not
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
you need a colon after the ) when you declare a function
ok ty
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 arso it created the folder for me I translated the words that i want and after i finished i randjango-admin compilemessagesand I changed the language code in thesettings.pyfromen-ustoarthis 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 defineLANGUAGESin settings.py?
π π
How do I access this in a Django view?
@hidden pier Nope , should I and shall it be defined as a list like this
LANGUAGES = [ 'ar , 'en' ]
or ?
@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!!!
Im Operational π
Our main website just got pushed a git and we're now running 100% Python
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.
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)
I already have my debug enabled in my flask app, but doesn't seem to be working. @late gale
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```
@arctic fog Try to see this
https://stackoverflow.com/questions/14993318/catching-a-500-server-error-in-flask
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.
Catch the error try to say in ur views if user dont have a customer then catch the error and create it
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.```
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
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
i tried deleting with which i tried to log in at the admin URL
Thanks, I will look into it! @late gale
but now get this error
__str__ returned non-string (type NoneType)```
but where should i catch
it
it has nothing to do with that
i'm not even sure where the erro comes from
am i invisible to you
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
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!
if you had a stopwatch, a pen, and a piece of paper how would you do it?
like, without code, what are the steps?
@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.
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
Does anyone if it's possible to make a Chrome extension in Python?
@cold anchor ok thanks! will keep that in mind. Sorry for asking multiple questions, but what are the 1000 and 60 numbers there?
no worries, the second argument is the number of MS to wait to call the function https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout so 1000 * 60 makes one minute
the frontend for all browser extensions are written in JS, but the backend can be in python
no problem!
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')
what's the view function code?
what you mean? the route?
@main.route('/contact')
def contact():
form = ContactForm
return render_template('contact.html', title='Contact Me', form=form)
in fact, you want to use form = ContactForm(flask.request.form)
to allow values to repopulate when submitted with values that don't validate
no problem!
there's a couple more things you want to do actually, let me just pull up a quick example
oh alright
@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
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
oh
could u explain to me what this is doing if request.method == 'POST':
when the user sends the msg it is using POST?
when a <form> element gets submitted, the default HTTP method is POST
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">×</a>
{{message}}
</div><!-- end .alert -->
{% endfor %}
</div><!-- end col-md -->
</div><!-- end row -->
{% endif %}
{% endwith %}
this goes in the layout template, am i correct
or does it go on the template of the page itself
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
oh, ill do just that. thanks
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?
<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)
this solved my issue, thanks!
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?
Does anyone know any good courses to learn rest apis with django?
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
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
You have plenty of tutorials
any will do
database normalization is generally a 'begginers topic'
not that complex
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
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
here is the code https://i.imgur.com/4nBe1oZ.png
so I have to put all the cards inside a div with the rows/col?
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.
what are the best open source flask projects?
Awesome am i doing it correctly?
Cause idk it seems weird to do a sys.path.append
Basicly im making my own library
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