#web-development
2 messages · Page 93 of 1
using something like flask_accepts
the flask.request object also has a method attribute, which will contain the relevant verb for a given request
Oh sorry maybe I expressed myself wrong
I meant, when I recieve a post request
I want to validate that there are no extra fields
and no wrong input on each form input
While having a React template
mmm why do you need to validate that there's nothing extra? just curious, like if i post you {'data': 'info', 'extra': 'foo'} is it that bad that i included extra?
you should validate the correct input using marshmallow and flask_accepts in my view, they are very easy to get started with
introduce a models.py specifying input and output let's say
Because (bad practice) curreently I just store the whole request on my db
first time working on web
ah
So when using postman, I realized how bad that is
yes not a great way to keep your sanity, but let's cover what you need
if you want to move on to using flask_accepts and swagger and api documentation/things of that ilk, post again and i'll help if i can
np
so for marshmallow and flask_accepts (the plural one, not flas_accept, right?) it's a case of either, or?
Or are they used together?
they can be used together, or individually
typically, people use flask_accepts alongside flask_restx for autodocumenting APIs (though fastapi is looking better and better)
example:
# myproj/models.py
from marshmallow import fields, Schema
class RequestBody(Schema):
my_field = fields.String(required=True)
another_field = fields.String()
class ResponseBody(Schema):
some_string = fields.String(required=True)
# myproj/app.py
from flask import Flask
from flask_accepts import accepts, responds
from flask_restx import Resource
from myproj.models import RequestBody, ResponseBody
app = Flask(__name__)
@app.route('/foo', methods=['GET', 'POST'])
class Foo(Resource):
@accepts(schema=RequestBody, api=app)
@responds(schema=ResponseBody, api=app)
def get(self):
pass # your logic here
def post(self):
pass # your logic here
and yes it's flask_accept_s_
but note the article i sent earlier, it outlines a way to do very vanilla flask with marshmallow doing the validation against a request.form or request.json
I am using regex to check passwords users input, I am not sure what Is wrong with this syntax
if not re.search('[A-Z]', password) or not re.search('[a-z]', password) or not re.search('[0-9]', password):
anyone have an idea why I get the error
expected string or bytes-like object
@hallow jacinth Why are you checking users' password inputs? Frameworks should have this covered.
Also, which web framework are you using?
flask, and framework doesn't cover it, I can enter passwords like "test" and it accepts it
Well, first of all, you can combine all those regexes into a single one.
'[A-Za-z0-9]' will cover all those.
That doesn't really solve your problem, but it will make your code way more compact and readable.
oh cool, didn't kno I could compact it like that
yeah
I think the problem is with your password variable. For some reason it isn't the right data type.
yeah I just thought of that
It's not really possible to see what's wrong from what you posted.
It's probably an attribute of the PasswordField object.
maybe .value
That's what it would be in JavaScript.
yeah I am going to look at documentation to see if it is a specific value
If the PasswordField is an object, it's probably an attribute of that.
Make sure it escapes the characters, though, because someone might be able to run code if you don't escape the user input.
Flask might do that automatically, but it's good to make sure. Django escapes automatically.
class registerform(forms.Form):
username = forms.CharField(label="Username", max_length=30, widget=forms.TextInput(attrs={"class": "form-control"}),
validators=[RegexValidator(regex='^[a-zA-Z0-9]*$',
message='Username must be Alphanumeric',
code='invalid_username')])
email = forms.EmailField(label="Email Address", widget=forms.TextInput(attrs={"class": "form-control"}))
password = forms.CharField(label="Password", widget=forms.PasswordInput(attrs={"class": "form-control"}))
confirm_password = forms.CharField(label="Confirm Password",
widget=forms.PasswordInput(attrs={"class": "form-control"}))
Does anybody have an idea to how I can check that password and confirm_password are equal?
Within the class, not the view...
Is this Django? @native tide
Yes @topaz widget
The default process should check that automatically
Which process?
The built-in registration view
Yeah but I'm building my own form from scratch.
I'm sorry, the default UserCreationForm should check that.
Just extend the default UserCreationForm, don't start from scratch.
from django.contrib.auth.forms import UserCreationForm
class MyUserCreationForm(UserCreationForm):
...
@native tide
Yeah but I'm building my own form from scratch.
@native tide why?
Just thought it would help me understand it better. I can't remember stuff just off documentation
how about you look at how Django did it then
I am 😄
And I just implemented it, thanks for leading me in the right direction! :D@topaz widget I now understand how to do it.
np
if I'm trying to authenticate and authorize api's. what library/service do you recommend?
[i'm using django, but solution doesn't have to be a django specific solution ]
I am writing a Rest API in Flask and noticed the request and response payload for some of the endpointsappearing in swagger do not tally with the namespace and resources in the controller
my user_account controller
details = CustomerDetailsResponse.api
cust = NewCustomerDto.api
_user = NewCustomerDto.user_account
_userdetails = CustomerDetailsResponse.userdetails
@cust.route('/')
class UserList(Resource):
@details.doc('list_of_registered_users')
@details.marshal_with(_userdetails, as_list=True, envelope='data')
def get(self):
"""List all registered users"""
return get_all_users()
#@cust.response(201, 'User successfully created.')
@cust.doc('create a new user')
@cust.expect(_user, validate=True)
def post(self):
"""Creates a new User """
data = request.json
return save_new_user(data=data)
my data transfer object
class CustomerDetailsResponse:
api = Namespace('userdetails', description='Response object when fetching customer details')
userdetails = api.model('user', {
'first_name': fields.String(description='user first name'),
'last_name': fields.String(description='user last name'),
'membership_id': fields.String(description='membership id of the user'),
'occupation': fields.String(description = 'occupation of user'),
'mobile_number': fields.String(description = 'phone number of custmer'),
'email': fields.String(description='user email address'),
'enabled': fields.Boolean()
})
class NewCustomerDto:
api = Namespace('user', description='Registers new customer')
user_account = api.model('user', {
'first_name': fields.String(required=True, description='user first name'),
'last_name': fields.String(required=True, description='user last name'),
'username': fields.String(required=True, description='username'),
'occupation': fields.String(description = 'occupation of user'),
'mobile_number': fields.String(required = True, description = 'phone number of custmer'),
'email': fields.String(required=True, description='user email address'),
'password': fields.String(required=True, description='user password'),
})
when I run in terminal I get this in swagger documentation -
Also my namespace -
from flask_restplus import Api
from flask import Blueprint
from .main.controller.user_controller import cust as customer
from .main.controller.user_controller import dea as deactivate
from .main.controller.lease_controller import emp as employee
from .main.controller.auth_controller import api as auth_ns
blueprint = Blueprint('cust', __name__)
cust = Api(blueprint,
title='REST API AUTH WITH JWT',
version='1.0',
description='An API for a Rent Management System'
)
register = Blueprint('dea', __name__)
dea = Api(register)
lease = Blueprint('emp', __name__)
emp = Api(lease)
validate = Blueprint('auth', __name__)
api = Api(validate)
cust.add_namespace(customer, path='/user')
cust.add_namespace(deactivate, path='/user')
cust.add_namespace(employee, path='/employee')
cust.add_namespace(auth_ns, path='/auth')
I am coming from a C# background, so I have limited experience writing APIs in Python (Flask). How can I resolve this?
To make sure my form submission works, should I get the information and display it in an html form, should I just display the inputs on another page?
if I'm trying to authenticate and authorize api's. what library/service do you recommend?
[i'm using django, but solution doesn't have to be a django specific solution ]
@weak chasm DRF?
@vestal hound vanilla
Hello
I'm new to Django and I'm wondering why this
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
{% for posts in posts %}
<h1>{{ posts.title }}</h1>
<p>By {{ posts.author }} on {{ posted.date }}</p>
<p>{{ posted.content }}</p>
{% endfor %}
</body>
</html>
```Isn't loading
When I run it it shows this
When it's supposed to show
posts = [
{
'author':"Fairy King Lucifer",
'title':"Becoming the Fairy King",
'content':"This is how I became one of the few Fairy Kings to ever live.",
'date':"August 22, 2020",
},
{
'author':"Demon King Lucifer",
'title':"Becoming the Demon King",
'content':"This is how I became one of the few demon Kings to ever live.",
'date':"August 21, 2020",
}
]
...
for posts in posts?
how about for post in posts
also, you have posts and posted
posted doesn't exist
the latter is the ultimate cause of your problem
Sorry that I wasted your time
@native tide you didn't
but I would really suggest you use better names
for posts in posts is doubly confusing because you use a plural term "posts" for a single post, and because the element and the collection are called the same thing
tell what help
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
{% for posts in post %}
<h1>{{ post.title }}</h1>
<p>By {{ post.author }} on {{ post.date }}</p>
<p>{{ post.content }}</p>
{% endfor %}
</body>
</html>
```Thats the html code
from django.shortcuts import render
post = [
{
'author':"Fairy King Lucifer",
'title':"Becoming the Fairy King",
'content':"This is how I became one of the few Fairy Kings to ever live.",
'date':"August 22, 2020",
},
{
'author':"Demon King Lucifer",
'title':"Becoming the Demon King",
'content':"This is how I became one of the few demon Kings to ever live.",
'date':"August 21, 2020",
}
]
But what it shows is
open developer tools check if get your html code there
try to rerun the server
check your url & views
Urls
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='blog-home'),
path('about/', views.about, name='blog-about'),
]
```Views
```Python
from django.shortcuts import render
post = [
{
'author':"Fairy King Lucifer",
'title':"Becoming the Fairy King",
'content':"This is how I became one of the few Fairy Kings to ever live.",
'date':"August 22, 2020",
},
{
'author':"Demon King Lucifer",
'title':"Becoming the Demon King",
'content':"This is how I became one of the few demon Kings to ever live.",
'date':"August 21, 2020",
}
]
def home(request):
context = {
'posts': post
}
return render(request, 'blog/home.html', context)
def about(request):
return render(request, 'blog/about.html')
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
{% for posts in post %}
<h1>{{ posts.title }}</h1>
<p>By {{ posts.author }} on {{ posts.date }}</p>
<p>{{ posts.content }}</p>
{% endfor %}
</body>
</html>```
@native tide you spelled it wrong it should be posts.author but you wrote post.author
I just changed it
ok
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
{% for posts in post %}
<h1>{{ posts.title }}</h1>
<p>By {{ posts.author }} on {{ posts.date }}</p>
<p>{{ posts.content }}</p>
{% endfor %}
</body>
</html>
ya it should work now
ok just a second
@native tide <!DOCTYPE html> <html> <head> <title></title> </head> <body> {% for post in posts %} <h1>{{ post.title }}</h1> <p>By {{ post.author }} on {{ post.date }}</p> <p>{{ post.content }}</p> {% endfor %} </body> </html>
I will try that
ok
ya you mis spelled the context variable in you template
check it out again i fixed it
No problem
IIT WORKED
@onyx crane check it's documentation it will help you to solve our problem
me having no idea what a .scss file is
so i assume, this is the propper way of implementing it ?
Install the package under installed apps ?
Is this ‘u’ thing me? Or python converting from html form?
Is it just from print, and doesn’t actually have a u in its submission?
@plucky tapir https://docs.python.org/3/howto/unicode.html
I just changed it
@native tide the other way round...
which makes more sense to you in English?
“for post in posts” or “for posts in post”?
Yea your right but English isn't my main. My main is like Latin
Thanks
Out of curiosity which db language do you guys prefer with flask? I've read you shouldn't get into too much of sql lite if you're more serious about db in the future
if you're using SQLAlchemy with Flask, which you should be
then you can pick any db
You guys recommend flask over django for first time web development? as a middleman between databases and front end. Plan to have an admin page eventually
both have their places, django puts some rules in place so you have a consistent project structure that just works. Flask is generally easy to learn. At the end of the day, go with what suits you, not what people think you should use.
I spent a good amount of today doing things in flask, but maybe I should give the other a shot as well. django seems to have a lot of features I'd probably have to really dive into to learn for flask, idk how much more time consuming it'd be to implement database/security/admin features
django takes time to pickup tho, learning all the stuff that is built in and using them.
Can anyone suggest me some project idea to learn Django rest framework?
todo app lol
any app but just use drf
or convert ur existing projects to use drf
i had a social media site built with pure django first, then I changed it to use drf and vanilla JS
whats drf ? I though it was django rest framework => django
You guys recommend flask over django for first time web development? as a middleman between databases and front end. Plan to have an admin page eventually
@plucky tapir if you have experience with Python but not with web dev, I would reco Django
it makes many decisions for you
can anyone make any sense out of that error msg ? (@me)
I've used it just like they describe in the documentation... + im using the endcompress tag in the next line
do a propper screenshot and then maybe
@native tide post errors as text.
It's indentation error I think so
First impression I thought django had a lot code written beforehand but it looks like a lot of it is imported, mainly settings having the most preset code?
Tbh most of the code written before-hand are just comments
Like urls.py file is 90% comments
Hello, I am having an issue with my testing db. Using postgres and when i run this test file the test data is overriding my db data and saving the test data! I have no idea what I'm doing wrong. My app database is called informed_voter_db and my test db is called voter-test. Can someone help me out? Below is the file setup and teardown. The users in this file are being saved to my app db and all other data being deleted.
os.environ['DATABASE_URL'] = "postgresql:///voter-test"
# Create tables and delete data in each test
db.create_all()
class UserModelTestCase(TestCase):
"""Test views for users"""
def setUp(self):
"""Create test clien and sample data"""
db.drop_all()
db.create_all()
test_user1 = User.signup('tester@test.com', 'tester987', 'password1')
test_user1id = 99999
test_user1.id = test_user1id
test_user2 = User.signup('mcnair@test.com', 'McNair', 'qwerty')
test_user2id = 1001
test_user2.id = test_user2id
db.session.commit()
test_user1 = User.query.get(test_user1id)
test_user2 = User.query.get(test_user2id)
self.test_user1 = test_user1
self.test_user1id = test_user1id
self.test_user2 = test_user2
self.test_user2id = test_user2id
self.client = app.test_client()
def tearDown(self):
res = super().tearDown()
db.session.rollback()
return res
Never mind. Figured it out. Used URL instead of URI. The eyes get tired at night. Also forgot app.config["SQLALCHEMY_ECHO"] = False
Hey guys. I just want to know how can I use the flask app context in a thread?
My code here raises a RuntimeError:
from flask import current_app as app
from threading import Thread
from flask_mail import Message
from .. import mail
def thread_send_mail(msg: Message) -> bool:
with app.app_context():
try:
mail.send(msg)
return True
except ConnectionRefusedError as e:
print(e)
return False
def send_mail(to: str, subject: str, text: str, html: str, from_: str = "info@simplymeet.gq"):
print(app.config)
msg = Message(subject, to, text, html, from_)
Thread(target=thread_send_mail, args=[msg]).start()
And this is my folder structure. The current python file is mail_helper.py
| src
|-- __init__.py
|-- routes.py
|-- util
|---- __init__.py
|---- mail_helper.py
| ...
Please mention me while providing an answer. Thanks
nevermind, i just didnt use threading and it worke
is it a better idea to containerize everything if im intending to add more things (like another web api or web app) on the same host as my bot?
help i don't get pseudocode?
@native tide
Hello guys i need help i want to know how to create a route that a admin can access in which i can create posts for my blog i dont know how this work
and how am going to get the that route after deploying
@native tide if you're using django, then look into "view level permissions"
[{"quote":"I can't even say the word 'titmouse' without gigggling like a schoolgirl.","character":"Homer Simpson","image":"https://cdn.glitch.com/3c3ffadc-3406-4440-bb95-d40ec8fcde72%2FHomerSimpson.png?1497567511939","characterDirection":"Right"}]```
If this is my API response, how can I select "quote" if the braces are in the way?
In JavaScript
response[0].quote @native tide
Thank you! 😄
Hey can anyone tell me why this gap is coming between navbar and content
There is margin-bottom:0 on navbar and margin-top: 0 on content
@twilit dagger are you using bootstrap?
What class is the content div? Have you tried container-fluid?
container-fluid increases the margins lol
there was container on the content div but the gap remains even after I removed it
<img class = "top-image" src = "../../media/arling>
<div class = "text-overlay" id = "top-image-text">
<h1>Nimbus Communications</h1>
</div>
</div>
#content-section{
margin-top: none;
}```
With django if I wanted to share a few web pages I made through github with someone else, would you upload all the files even if you didn’t use them all yet? That django created by default
if anyones used wtforms before, do you guys know if the checkbox logic goes in the form class?
like do the options in my check boxes need to be variables in my form class
im trying to set this up such that if a person selects one of the check boxes, a different set of options appear as a subsection
@plucky tapir ofc, why leave something you'd have to do later anyway
<script>
$(document).ready(function(){window.setTimeout(function(){
$(".alert").fadeTo(500, 0).slideUp(500, function(){
$(this).remove();
});
}, 5000);})
</script>```
i have this script tag in my template
and it doesn't work
This script tag is for when an alert message pops op
I want it to fade away after a couple of seconds
{% if messages %}
{%for message in messages%}
<div class="alert alert-success" role="alert">
{{message}}
</div>
{%endfor%}
{% endif %}```
but when I click inspect and go to the console
I see this error
?user_login=/all-users/:10 GET http://localhost:8000/login/jquery-3.5.1.min.js net::ERR_ABORTED 404 (Not Found)
?user_login=/all-users/:43 Uncaught ReferenceError: $ is not defined
at ?user_login=/all-users/:43
(anonymous) @ ?user_login=/all-users/:43```
The jquery cdn is in the head tag
like so <script src="jquery-3.5.1.min.js"></script>
I have no idea why it doesn't work
It’s looking like the django way is to categorize everything in their own apps within the project. I’m trying to figure out the purpose, This would help with more features later on and organization?
a register and login page considered under the main app?
Yes in a users app @plucky tapir
Ah yes thanks
It seems like there’s be main, users, then one for like info on your site.
Like articles if you had a blog site
A few like that, seems right? Or does it get broken down into a lot more apps
Usually I've seen a home/whatever is the main on your site, and stuff like about and contact goes in there too, then a Users app and then stuff like shop, forums, etc.
So actually I've mostly seen only 2 apps for most websites
👍
One option to go from userinput to db, I could create an html form, post the input to a model and migrate it to a database?
Django provides you a default CreateView for making models @plucky tapir
You don't have to make a form
Django gives you a lot of things from the get-go
any experience with ListWidget from wtforms
@twilit dagger CreateView would still need a template right? Would it sortof be a substitute for the html? Would it much more convenient in the long run to use modelform rather than html?
All you need to put in a CreateView template is {{ form.as_p }} @plucky tapir
Or better is to use Crispy Forms, then it's just {{ form|crispy }} and it looks much better
That's it
It makes the form and creates the model for you, you just have to make a submit button
It's far far more convenient to use the Views Django gives you, though in certain cases you still have to use ModelForms, no point in using base html forms.
Django gives you CreateView, DeleteView, ListView, DetailView, UpdateView etc. It also gives you LoginView and LogoutView
Using the views from django, push/pulling info to/from the database will be significantly more convenient?
feels like django has the ability to make it mainly a python project
Hey does anyone know the best way to keep text on a page at the same location when the page / element it's inside of resizes?
I have a slide-out navigation panel on my web page, and I need wherever the top of the page is to stay the same when I expand/collapse the panel.
My issue is I have a partner who doesn’t know python but is doing the css/html and dB side of things. Django feels like it removes their contributions from the project
Although thinking of finished product in a short time it seems like django is the way to go.
@plucky tapir They need to learn Django's templating language, and you should be handling database stuff since most of that is taken care of by Django's ORM.
They should probably also "git gud" with JavaScript if they're going to be taking on the front-end part of it.
Django's templating language is not that hard to learn if that's all you need to learn.
@plucky tapir Your division of labor doesn't make a lot of sense. Usually isn't front-end and back-end. Having someone doing HTML/CSS AND database while you work with the back-end framework is not a great division of labor.
You should be handling the database.
How can I capture whenever a POST request is sent to my rest api in django
Because I want to do something whenever that happens so how do I detect it as soon as it does happen
@topaz widget Thank you got it. So if I continue with django, there are still a lot of areas that html/css could still give a good amount of labor? If so what type of stuff would that be, I had the idea that using views almost removed html use.
You can't really remove the HTML use. Views in Django use HTML templates to render the pages. Your partner would just design the pages, and they could either learn Django's templating syntax, or you could just modify the HTML pages to add the templating syntax. It's probably better if they learn the syntax, though, since you will have parent and child templates, and someone will be doing a lot of extra work if the Django templating language isn't just used from the start.
@mortal shale Every request will have a method. If the request's method is POST, then do something in the view that handles that.
heres my current views.py
class HeroViewSet(viewsets.ModelViewSet):
queryset = Hero.objects.all().order_by('name')
serializer_class = HeroSerializer
is there a request type arg?
@topaz widget
There is a request object that would be handled by a view. This request object will have the HTTP request method (POST in this case) as an attribute.
Yes, it would be an argument to a view, as well, to answer your question further.
so I can put it in my HeroViewSet class as an argument or?
I'm not sure. I don't really know what the ModelViewSet class does.
I've never really worked with DRF
Hi, I'm trying to generate a database with MySQL and MAMP. I installed sqlAlchemy to generate a data table but it didn't work. I am having this problem and already installed the libraries mysql flask-sqlalchemy, etc with terminal and python libraries.
Don't know what else I can do.
Love
Having issues here
@topaz widget I'm going to try to convert an html template to a django template to see the difference. Django would remove the need of creating/modifying databases because views handles it directly correct?
I'm not sure I follow what you're saying in either of those sentences.
@plucky tapir Not sure what you're saying. It's hard to render web pages with Django without making it a "Django template".
As for the database, Django models handle all the database stuff. You need to configure your database in settings.py, if you don't want to use the default sqlite database, but that's pretty much it.
Yo - I'm using flask and having a weird issue where a route creates a form which immediately procs "submit"
@swift sky yeah I have some experience with wtforms, whats up?
This has the rest of the code too
the issue is i want to dynamically be able to add scores on a page - so i have two forms
one is the base, which contains just scores and a submit button, and the other specifies the scores through a fieldlist of formfields
class PowerGridScore(FlaskForm):
scores = FieldList(FormField(PowerGridForm), max_entries=6)
submit = SubmitField('Submit')
Therefore for the route I have to do something like
scoreformname = game.gname.replace(' ','')+'Score'
baseformname = game.gname.replace(' ','')+'Form'
current_mod = sys.modules[__name__]
score_form = getattr(current_mod, scoreformname)
base_form = getattr(current_mod, baseformname)
class LocalForm(score_form):pass
LocalForm.scores = FieldList(FormField(base_form), min_entries=int(entries), max_entries=6)
form = LocalForm()
if i check submission of the form with form.validate_on_submit(), it IMMEDIATELY procs
the only workaround I've seen is just if request.method == 'POST': instead of if form.submit(): or even if form.validate_on_submit():
if i use validate, even though the field list is called with proper validators (datarequired() ) it will never actually validate
if I use submit, it never displays the page to begin with and just immediately redirects me
why does that newly created form immediately get submitted?
is there a better way to do this instead of checking if POST? i feel like that exposes me to just malicious code that could be interpreted but idk if wtforms handles that
class PowerGridForm(FlaskForm):
player = StringField('Player', validators=[DataRequired()])
plants = StringField('Plants', validators=[DataRequired()])
money = StringField('Money', validators=[DataRequired()])
that's the other form getting fieldlist'ed
@topaz widget I already have html files that would submit input, I would send that to a database using flask. Today I was going to try to convert the html into django templates to see what it is like. but I don't really see any examples online (to see a side by side comparison.)
It's probably somewhat similar to Flask. I think Flask uses Jinja, which is not that different from Django.
@plucky tapir If you have a bunch of HTML templates that are written in Jinja and it will be a lot of work to change them, you can also specify in your project's settings.py file that you want to use a different templating engine than the Django default. I have not done this, so I do not know the details. It is possible, though.
well you can use jinja as templating engine in Django as well
but Django template language is not much different from Jinja anyway so won't be much of a hassle converting them
It's probably somewhat similar to Flask. I think Flask uses Jinja, which is not that different from Django.
@topaz widget fun fact, jinja2 was created based on django templating engine and the same creator made a fork of it for php
@native tide I am trying to build a "survey form" which has multiple choice, open ended, and questions need to appear depending on responses
how would you approach htis
Im trying to deploy my Flask app to heroku, but it's not working. Im trying to figure out the issue, but cant quite figure it out. First time deploying to heroku. I think it might be an issue with bootstrap? Can anyone take a look at my logs and tell me what im not seeing please?
https://pastebin.com/3wdWCicA
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
@zealous cloud 2020-09-26T00:00:33.084755+00:00 app[web.1]: ModuleNotFoundError: No module named 'keys'
@vestal hound Oh shoot thats my api key. I put it into a separate file and put that into my git ignore. Is there a way to include it into the project without hard coding it in obviously?
venv/
__pycache__/
.DS_store
keys.py
.vscode
huh
why is it in your .gitignore
that's what I'm asking
like
your server files won't be visible
to outsiders
it's fine to put it there
oh because its my api key. It was my understanding that you dont want that in your project files?
hm
not if your code is public
but if you're only pushing to Heroku
(i.e. not hosting on a public GitHub repo or something)
it's fine
because ultimately
you need to have some sort of credentials in your server code, right?
otherwise how will you authenticate
so push to heroku master with the api key but not to github correct?
correct. hadnt considered that. thank you. I didnt include it because I also have a github repo for it and thought somehow id be publishing the api key in my code'
so push to heroku master with the api key but not to github correct?
@zealous cloud yup!
correct. hadnt considered that. thank you. I didnt include it because I also have a github repo for it and thought somehow id be publishing the api key in my code'
@zealous cloud yeah, that's a good thought
it's great that you're considering the security implications
another way to do it is with an environment variable
I would suggest not using a .py file
some data file might be better?
like a JSON
or .env
even a .txt is fine
that makes more sense now that you mention it. Thank you again. I'll look into a way to do that after I get it up and running.
yw!
I'd put it as an environment variable and then load it in with os.getenv("NAME_OF_VAR")
Rather than keeping the code in a file at all
Rather than keeping the code in a file at all
@urban wyvern why?
Avoid the potential of accidentally publishing it anywhere
they can leak (depending on the deployment environment)
there's a package called python decouple for that

heroku has config vars in project settings, which are equivalent to environment variables
I used environment variables for my database and secret key. Not sure why I didn't think of doing it with my api keys also. BTW my project opened successfully
I'm using flask with my first try of blueprints, here is my tree:
├── app.py
├── LICENSE
├── PaktMonitor
│ ├── appliance
│ │ ├── __init__.py
│ │ ├── models.py
│ │ └── routes.py
│ ├── __init__.py
│ ├── user
│ │ ├── __init__.py
│ │ ├── models.py
│ │ ├── routes.py
│ │ ├── static
│ │ │ └── main.css
│ │ └── templates
│ │ ├── base.html
│ │ └── login.html
│ └── views.py
├── README.md
├── requirements.txt
└── run.sh
Whenever I go to any of the urls, such as /user/login, this is the result:
$ curl localhost:5000/user/login
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>404 Not Found</title>
<h1>Not Found</h1>
<p>The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.</p>
No matter what I do, there is a 404 on every page.
Is the django templates have a quick learning curve? I can just read basic html tbh
if uk python, django template language doesn't require much learning
just go over the docs and you'll be fine
i loaded my style.css in static folder but the images dont show up on my site
can anyone help me?
@rotund token I'm here
does anyone know a bit of html as i need help with making this contact form stack on top of eachother and need it on the right. TAG ME
ok @cosmic nebula
Use FlexBox API
i loaded my style.css in static folder but the images dont show up on my site
@solemn igloo make sure youlinkthem properly and have the right names and tags
how
/* style.css */
.container {
float: right;
display: flex;
flex-direction: column;
}
did u see my github
Or you can remove float and make the position: absolute; and then adjust/set the right to some viewport width
did u see my github
@rotund token no where is the link
@cosmic nebula
Can you tell me where your code is? I'm on mobile rn and it's kinda hard to go through your code
Like the file and the line number
wdym
Or your can tell me the class'name
In CSS
Like .container or whatever you named it
ok let me find it
You can share a line by clicking on the line number and then clicking on the three dots and share
And it's children?
.contact
Ok found it
wdym
Like contacts
ur confusing me
Or does it have a parent?
A parent container?
Which should hold all the contacts as a stack
yeh there is 2 lables
Make a different container class for contacts
Cause of you change the main container class, all elements having that parent class will behave like a stack
No no
<div class="contact">
<form action="#">
<label for="email">
Email: <input type="email" id="email" placeholder="Enter your email">
</label>
<label for="messages">
Message: <textarea id="message">Message</textarea>
</label>
<input type="submit" valid="Send Message" id="submit-button">
</form>
</div>```
Ohkay
Then just add ```css
display: flex;
flex-direction: column;
And lemme know if it works
hold on
Also I think this is how you use a label
<label for="email">Email: </label>
<input type="email" id="email" />
Use divs to cover all the label+inputs
i have ill commit and push so u can see
You just have to postion the submit button a bit below
Yea
Add a .submit class for the submit button and style it
And then change its top value to a larger value
Or you can change the bottom value too
<input type="submit" class="submit" />
div class='submit-button-wrapper'
.submit {
/* Style it, like color or background-color, etc. */
bottom: /* some value */%; /* or even vw works instead of % */
}
like margin
Yea that works too
so
margin-bottom
.submit-button-wrapper{
margin-bottom :
/* STYLE BUTTON */
}```
how would i get the links to go lower as i did margin-top N it didn't go lower
@cosmic nebula
that
Try postion: absolute; top: 95vh;
You can change the value 95 until it looks good
Remember it shouldn't be greater than 100 cause that will put the elements below the viewport
Hello, for some reason when I deploy my simple flask app to Heroku it says it can't find flask
I have these in my requirements.txt file
This is my procfile
This is my project structure
ok thanks tho
@rotund token did it work?
yo how can i pass variables to my base template is it possible?
Are there any Python things I can use for front-end alongside HTML and CSS? No browser supports Python, yes, but are there are any things I can compile from Python to JS, either manually or not? Brython compiled it very incorrectly.
From what I’ve searched, Flask and Django are for backend.
Can postcss with plugins completly replace SASS
And this is my dockerfile
@brittle basin do you need Ubuntu or just python ? Usually good practice is to separate front end, back end, and db with docker and link them with docker compose, so if i was you i'd directly take an image of python instead of ubuntu:latest
Thanks I'll check that
anyone have experience with scrapy-splash? I'm trying to get the variables inside my return function, but the response object only has the body, without the variables i want to pass
How to upload images from webpage to Django & through Django to firebase without using forms?
how do i allow pypi packages in my django site
for example urllib3
because im trying to use the requests module
https://pypi.org/project/urllib3/
does anyone know about fastapi ? i'd like to build a fastapi project, and i'd like to put my users models and endpoints inside a subfolder just like this
backend
├── main.py
├── ...
│ ├── users
│ ├── models.py
│ └── users.py
│ └── ...
so like a django project with multiple apps, can anyone tell me how to do this with fastapi ? i see mount and router, but i don't understand the difference between both
Is there anyone here who knows about flaske and can speak German.
I need some help
🥬
does anyone have any front end web development courses as i’m trying to learn
tag me
Can someone explain to me in simple terms. The purpose and use case of the SECRET_KEY inside config file in Flask
SECRET_KEY = os.environ.get('SECRET_KEY') or 'you-will-never-guess'
Read up on 12 factor apps and managing config through environment for each deployment target @wicked lodge
@warm igloo Thanks is this the site https://12factor.net/
A methodology for building modern, scalable, maintainable software-as-a-service apps.
A methodology for building modern, scalable, maintainable software-as-a-service apps.
👍
Guys how can I make an image cut out extra spaces instead of squeezing?? in html and css
Is the extra space IN the image, or in the HTML around the image?
in the image, like say if I want the image to be square, but it's a rectangle, I'd want to cut off parts of the side to make it square rather than squeeze it into one
in the image, like say if I want the image to be square, but it's a rectangle, I'd want to cut off parts of the side to make it square rather than squeeze it into one
@crude heath PIL (pillow) has builtins for that I am sure
Is it not possible to use the default sqlite module in a flask application?
@ me when answering, please.
@crude heath wrap the image in a div with a max width; say 100px, with overflow-x: hidden?
or...
use the actual object css properties
object-fit: contain;
object-fit: cover;
object-fit: fill;
object-fit: none;
object-fit: scale-down;```
blissfully taken from tailwind CSS's docs™️
this is what cover essentially does
That's my search engine!
Here's my other sites which I have a doubt. https://austrix.itf.repl.co I want it to be the RALEWAY font not the horrible default heading on iOS!
Does trying to use both SQLAlchemy and the default sqlite module screw up Flask apps?
@ me when answering.
When I launch the localhost:8000 server on my computer, is it possible to access it via my phone?
Is it possible?
If you are on the same network you can probably set up some proxy, but not out of the box no.
Android can do forwarding afaik, not sure about Ios devices
Hello:) I've got a question for you ppl.
What's better / when to use Django template vs sending JSON to JavaScript?
When I launch the
localhost:8000server on my computer, is it possible to access it via my phone?
@native tide I think it's possible
You need to set your IP Address in settings.py
ATM I don't remember in which list you need to append it
ALLOWED_HOSTS = ['*']
🤔
And in your terminal
$ python manage.py runserver 0.0.0.0:port
In port you put any port you want I think
try with 8000
Oh, and in your phone
You go to http://your-ip-address:port
O kay
I followed the instructions here to run Django using the built-in webserver and was able to successfully run it using python manage.py runserver. If I access 127.0.0.1:port locally from the webser...
Would Django be a good tool to create a website for image archiving?
I'm working on a family archive project, and would like a place for people to see the photos (and potentially upload their own)
Yeah I think so
Would Django be a good tool to create a website for image archiving?
@cursive violet You could use something like AWS' S3 to save those photos
Or you could set your own NAS:)
well yeah, but i just mean for getting all of the tools and stuff
like i want to implement face tagging and other shit
yeah, there are python libraries for that you can use
doubt they're django specific
django would be good cause you'd get an admin piece right out of the gate to help you manage what you build
@wicked lodge https://en.wikipedia.org/wiki/Session_hijacking
In computer science, session hijacking, sometimes also known as cookie hijacking is the exploitation of a valid computer session—sometimes also called a session key—to gain unauthorized access to information or services in a computer system. In particular, it is used to refer ...
How to upload files to Django through Ajax ?
that's flask
do you know how i can correct this mistake
https://quickpaste.net/4gV4uCz
that is my error
and that is the code
https://quickpaste.net/BGvLTFU
if you can solve this problem you will get lemon pepper wings
Hi here, how to make vscode check the site-packages of my virtualenv?
How in django can I use cache_control with a class based view?
It doesnt expalin how I can use that function specificvally
as it is a decorator but I am not sure how I can use3 decorators in class based viewws
Oh it expalins that, ty, but Im not sure how I could use multiple decorators
How?
cache_control(private=True)cache_page(60 * 2)(views.ProfileView.as_view())
If I do it like this it gets underlined red
?
Wdym?
if I use it above the class definition I get this error:
path('profile/', cache_page(60 * 2)(views.ProfileView.as_view()), name='profile-view', ),
AttributeError: 'function' object has no attribute 'as_view'
it isn't Django specific
@marble carbon
Yup thunder is right
Theres nothing to with django.... It will fine with javascript
im using wtforms to build a survey
idk how to make it so that depending on the answer to question, a new set of questions appear
any ideas?
Are there any beautiful soup experts in the house?
For example
<h2>Main Title</h2>
<p>Here is a subtitle text</p>
<p>
<strong>Bold title 1</strong>
</p>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
<li>Item 6</li>
</ul>
<p>
<strong>Bold title 2</strong>
</p>
<ul>
<li>Stuff</li>
<li>I</li>
<li>don't</li>
<li>want</li>
<li>to</li>
<li>capture</li>
</ul>
<p>
<strong>Bold title 3</strong>
</p>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
</ul>
Is there a way I can just grab the Bold title 1 and it's items, skip bold title 2 and it's items, then capture bold title 3 and it's items? Is that possible?
not sure if this is the right subchannel for that, but good luck
Or would I be able to achieve this with another utility like scrapy or selenium?
Ugh, I started in advanced discussion, they told me to come here 🤦♂️
Where should I go to find the answers since google isn't helping?
Thanks @marsh canyon. Ignore bold title 2 and it's items
alright
So capture bold title 1 and 3 and their items (for clarification)
so firstly u will want to get all the p tags and ul tags, delete the first p tag as its not needed
right
Sounds like it would be a long argument
Is beautiful soup the best utility for something like this, in your opinion?
Cool. Appreciate the help
soup = BeautifulSoup(x, "lxml")
paragraphs = soup.find_all("p")
del paragraphs[0]
uls = soup.find_all("ul")
for p, ul in zip(paragraphs, uls):
if p.text.strip().endswith("2"):
continue
# you got your title 1 and 3
print(p.text.strip())
print(ul.text.strip())```
@errant creek
x is the html string which u sent above
Got it. I'm assuming I use requests to pull the html from the website first?
sure, that can work
I'll give it a try. Thanks @marsh canyon
can someone please explain to me what is a post request ? and why do we have to make sure it's a post request when making a form ?
@opal fulcrum , the POST requests hold the data to be sent to the server in the body of the request. From what I understand, and I could be wrong, the POST is better as the GET request with lots of data would be a massive URL. Check this out as it seemed to help me https://www.w3schools.com/tags/ref_httpmethods.asp
thanks man that was useful
I am using a flask app, and am trying to use the sqlite3 module in it. I got this error when revisiting a page:
cur = self.conn.cursor() sqlite3.ProgrammingError: SQLite objects created in a thread can only be used in that same thread. The object was created in thread id 140453609432832 and this is thread id 140453567469312.
what exactly does this mean, and what actions would you recommend I take?
Please @ me when answering.
does anyone knows how to save image to database using flask??
hello
I'm using django and django-filters
And I had my filters working and then randomly stopped working, no changes made
but I think my filtered queryset
( .qs )
is not working in the template
if someone can help me plsssss
The View
The Filter
The template
No errors displayed, the filter form generated correctly
but when I press the search button it doesn't bring me any objects to the template
and that stopped working from one time to another
also, I tried the {% for ... % } inside the form?????
So django 3.1 added models.JSONField and I've migrated my project to use that from the old postgres specific one, is there a way to have migrations not fail on sqlite but also not break current deployments by squashing migrations
@opal fulcrum , the POST requests hold the data to be sent to the server in the body of the request. From what I understand, and I could be wrong, the POST is better as the GET request with lots of data would be a massive URL. Check this out as it seemed to help me https://www.w3schools.com/tags/ref_httpmethods.asp
@marsh fog yes but also
GET requests should be idempotent i.e. if you submit them multiple times it shouldn’t be a problem
which is usually not the case for POST requests
e.g. imagine you use a GET to place an order
if you send it multiple times, you get multiple orders
which is not right
so usually GET requests are used for read-only stuff
Is this where i ask about web scraping?
Maybe I can helpya if it's bs4
Is it ok to post my Django project to GitHub?
You know... With all the sensitive info in my settings.py
Like tokens and my email with password.
Usually I use environment variables to hide my sensitive info, but when I want to deploy it do a live server I have to replace the path to the environment variable with the actual value.
Which is redundant
that is indeed the correct way to manage secrets
what makes you think it is redundant?
Hi! I'm trying to use django and when I do: django-admin startproject mysite, I just get this error:
operable program or batch file.```
Someone help please!
@native tide https://docs.djangoproject.com/en/3.1/howto/windows/
@native tide Check whether you have installed Django correctly or not. It is not installed yet.
Could anyone help we with this bootstrap problem?
I have a navbar
but Idk how to make your current location highlight
it should be highlighting home
Guys I have a problem in updating data in Django
I cant update and also delete a data
there is no error when I click the Update button and Delete Button
it's just redirect me to the Dashboard and nothing will change
in the database there is also no change
I have inputted also form tags
in my html
@rain wren you haven't done any database stuff in your view, why would it save anything?
I have the database
my only problem now is that it cant update and also delete
and when I click the buttons, it has no error and only redirects to the dashboard
I wrote this using the FastAPI module, thoughts? Criticisms? Anything?
Has any had trouble getting Django Debug Toolbar to work? I have followed the instructions, although I get a javascript blocked error due to the MIME type.
<script type="module" src="/static/debug_toolbar/js/toolbar.js" async></script>
I can view the debug panel when in the inspector view. This confirms that the template is loading, and injecting into my webpage. But none of the buttons work due to this error
I'm getting a 200 status when django is serving the js file as well.
Adding the javascript import directly in my own template fixes the issue:
but this isn't a resolution to the original problem.
Any idea what may be going on here?
The bug must have appeared 4 months ago due to this commit where 'type="module"' was changed.
I am creating a booking system. Seller signs up and they choose what days they want to work. i will then create a calendar and then only show the days the seller wants to work. So lets say I sign up, and I say I want to work Days: Monday, Wednesday, Sunday. I need to then add these days to the DB and then on the front-end only show them days in the calendar. How would you setup the DB table? I am thinking something like this:
class WorkerAvailability(db.Model):
__tablename__ = 'worker_availability'
id = db.Column(db.Integer, primary_key=True)
monday = db.Column(db.Boolean, nullable=True)
tuesday = db.Column(db.Boolean, nullable=True)
wednesday = db.Column(db.Boolean, nullable=True)
thursday = db.Column(db.Boolean, nullable=True)
friday = db.Column(db.Boolean, nullable=True)
saturday = db.Column(db.Boolean, nullable=True)
sunday = db.Column(db.Boolean, nullable=True)
Seems a bit long though, any other way I am setup the table ?
Which is redundant
@native tide There are different ways to go about it. I am usinggitlab-runnerand storing my secrets in my repo, so gitlab-ci gets them automatically when building my project. There's also Hashicorpvault, and you can use.envfiles with https://pypi.org/project/python-dotenv/
Just be sure to .gitignore your .env file, and use scp to copy it onto your server.
I am creating a booking system. Seller signs up and they choose what days they want to work. i will then create a calendar and then only show the days the seller wants to work. So lets say I sign up, and I say I want to work Days: Monday, Wednesday, Sunday. I need to then add these days to the DB and then on the front-end only show them days in the calendar. How would you setup the DB table? I am thinking something like this:
@past cipher That works. You can also store it as a single int using bitwise operations, which would keep your database smaller.... but it would make your code slightly more cryptic 😄
Hello, are there efficient ways of hosting web services , something like lazily loading the service only when needed , like for now im hosting my php service with docker and nginx , so is there some way I can lazily load it only when a request comes in?
Hello, are there efficient ways of hosting web services , something like lazily loading the service only when needed , like for now im hosting my php service with docker and nginx , so is there some way I can lazily load it only when a request comes in?
@hidden gulch you're thinking of https://en.wikipedia.org/wiki/Serverless_computing
@lethal orbit seems that this utility is not provided by all cloud platforms, we're planning to deploy everything on hetzner server
is there some tool which can be used to achieve this?
like for my other services which dont require nginx , Im using something called ynetd , https://github.com/rwstauner/ynetd , for lazily loading up containers only when a request is made
so I was wondering if I could do the same with my web services too
Depends on how fast your services start.
I don't actually use it; my projects are usually small enough they can be always on...
once an image has been built , I think docker cache can handle stuff right
Sometimes, you can spend thousands of dollars on engineering to save a few hundred on deployment costs, and end up with a more complex system, so make sure you calculate the costs properly first lol
I don't actually use it; my projects are usually small enough they can be always on...
@lethal orbit true , but since there are lot of services running parallely on my side, I prefer to free up ram whenever possible
Sometimes, you can spend thousands of dollars on engineering to save a few hundred on deployment costs, and end up with a more complex system, so make sure you calculate the costs properly first lol
@lethal orbit yes that is so true , thank u so much , Ill surely look up everything properly
is it possible to insert html into iframe from flask variables
How do I have all these blocks be of the same width?
CSS - ```.parent-element{
margin-top: 80px;
display:flex;
justify-content: space-between;
}
.block{
display: flex;
flex-direction: column;
margin-left: 30px;
padding-top: 10px;
}```
Is there any way I can use javascript to change a timezone in django?
I use this in base.html
`{% load tz %}
{% timezone "GB" %}
{% block content %}
{% endblock %}
{% endtimezone %}`
But I found that this javascript code Intl.DateTimeFormat().resolvedOptions().timeZone
Gave the timezone.
Is there a way to get the results of that code and change the timezone?
I've a package installed using poetry, but if I try to execute it I got 'ModuleNotFoundError: No module named 'packagename'" is possible to include self or how can I fix it?
Hey there wanted to ask a question its about a game not programming its name is Ag Drive is it still available on app store or any country or region to download it from app store?
how do you guys feel about sanic for building a frontend? i was comparing it to django, and it seems better because it has async functionality built-in from the get-go
does scraping count as web dev? @ me if u answer
let me try
resultset has no attribute text
i am using findall...
hmm
should i iterate through them?
yea
what even is it idk how to make it into a list or iterate it
is it a list or a string idk
more details:
why do you keep screenshotting an impossible to read image at this point instead of just copying the text itself?
copying the text would probably make it easier for people to read, and therefore help you
ok
so originally I needed to extract the text from some html code i scraped
I got how to do that but I cant do it to a resultset
I need to iterate over it to do it to each one
but i have no idea how.
ok
Hey i have a question about Django + Bootstrap can anyone help?
flask-restful vs fastAPI, someone know which one is better overall?
this is a summary @terse viper provided in #career-advice
my quick summary of benefits are:
- it's an API framework, so specialized for API work. Flask is a bit more general-purpose. An obvious example of where specialized for API is good is the error messages re json by default
- unified query, path, and body inputs as arguments. Flask uses the request singleton for stuff, and it's inconsistent. Having arguments is neater (functions more pure)
- built-in run-time schema validation and static checking with pydantic. Flask has no such thing. This also uses python type hinting
- built-in automatic documentation generation. you will literally get a /doc page with swagger UI generated for you automatically if you define your input/output models with pydantic
- async support
- websockets
- graphql
Hey, Im trying to run my Flask app in apache2 using wsgi and Im facing some issues, someone help?
Post your problem
Can anyone explain why my static and media files are not working on deployment server?
#urls.py
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
#settings.py
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
os.path.join(BASE_DIR, "media"),
]
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static_cdn')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media_cdn')
Include a path for staticfiles @honest dock
@twilit dagger can you tell me how?
@twilit dagger how does that make sense
@twilit dagger can u pls help me correct this script.
if (command == 'kick'){
const userKick = message.mentions.users.first();
if (userKick) {
var member = message.guild.member(userKick);
if (member) {
member.kick('you have been kicked for brekaing the rules.').then(() =>{
message.reply(kicked zuser ${userKick.tag}!);
})
} else {
message.reply('that user is not in the server.')
}
} else {
message.reply('you need to state a user to kick')
}
}
if (command === 'ban') }
const userBan = message.mentions.users.first();
if (userBan) {
var member = message.guild.member(userBan);
if(member){
member.ban({
reason: 'you broke the rules.'
}).then(() => {
message.reply(${userBan.tag} was banned from the server.
})
} else {
message.reply('that user is not in the server.'
}} else }
message.reply('you need to state a user to ban.')
it sais theres 9 erros
but i fixed it all
and it still doesnt work, im not sure if its the start
o
k
huh
its javascript
Also first line there are three ===
@twilit dagger u always have 3 equals in javascript to ensure type checks
@old reef this question is related to discordjs i believe, this might not be the right server for that
you can ask in a javascript server
I can't believe I didn't see all the {}
@marsh canyon ty ur the BEST
hey everyone, need some help with something. i had this flask program that was running fine before, but now it keeps giving me a flask.cli.noappexception
Anyone know what the best practice for having something done on a schedule or a regular basis in Django is? For example I want to go through all my records in a model and if they are certain days old I want to delete them.
@devout coral that kind of thing is best done with a script that you run by way of the operating system's task scheduler.
Well my initial thought was to run a cron job to directly interface with my SQL database but then I thought implementing it into the Django site might be best.
you can run a cron job to launch a script that uses Django's ORM
that's the way I'd do it myself
theres a library called schedule that is very easy to use. im not sure its a 'best practice' though
for something that only happens once a day or something like that, use cron.
Yeah, which is what I thought of doing but lets say I deploy this at a different location and now i'd have to set that up and add seperate documentation for it. I thought adding it to the app would be best. Guess not.
cross that bridge when you come to it :D
use what works now to get it working now.
Haha ok.
just make a note that it has to be ported.
Yep, I can add that to the doc no big deal. Just thought it might piss some people off that there is also this separate thing that needs to be used.
As long as it's documented, it should be fine
Then from cron I should be able to use the Django ORM if anyone is using different SQLs?
ideally. I believe Django ORM is pretty abstract
Ok, I also saw some people mentioning celery but I have never used it. Any thoughts on that?
I haven't used it myself
I dont know if this is the write chat sorry but I want to make an app using react native that basically allows me to take a picture of something at store it in a map like google maps would i have to use the google cloud api?
So you normally just set up a management command and then run it through cron?
@devout coral or a script that imports the needed components to be Django-aware
@brave gyro you'd have to use Google's APIs to interact with anything Google.
Ok, I think I am going to go for a management command so I do not have too many outside dependancies
and this way if something happens I could also easily run it manually
that makes sense
Cool, I appreciate your help.
YW!
Is there someone from Sweden here?
may ik wot has gone wrong here?
you have no path at /
how to configure this for windows then?
im trying to do author/ books example from django. in my books class im adding author with foreignkey relation
i dont want to add books in author class too
Is there someone from Sweden here?
Yes
is there anyway to do without adding books via hand
i checked docs, manytomany relation maybe can help me
may ik wot has gone wrong here?
@proven orchid you need to register a view at/inurls.py
but example for manytomany relation is not good
can anyone help me make my socket io site less laggy
@proven orchid you need to register a view at
/inurls.py
thanks
I keep getting django.core.exceptions.ImproperlyConfigured: The included URLconf 'project.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import.
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('admin/', admin.site.urls),
path('register/', include('QuickQuiz.urls')),
]```
my main urls file
from django.urls import path
from . import views
urlpatterns = [
path('', views.Register.as_view(), name='register'),
]```
is the QuickQuiz urls
how do i fix it?
??
Can you deploy a Django project on Netlify?
I keep getting
django.core.exceptions.ImproperlyConfigured: The included URLconf 'project.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import.
@last patio pls help
okay...
anyone?
from django.urls import path
from . import views
urlpatterns = [
path('', views.Register.as_view(), name='register'),
]```
@last patio Is this in the QuickQuiz app?
yes it is
I've changed it sine but its the same error. ```py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('register/', include('QuickQuiz.urls')),
]
from django.urls import path
from . import views
urlpatterns = [
path('', views.register, name='register'),
]``` this is the one it includes
When i google it literally all the answers are "check how you spell urlpatterns"
I've never seen this error before, but try to check this part now the issue is probably caused by a circular import.
Im not quite sure what would cause that
Is the register view a function based or a class based view?
from django.shortcuts import render
from .forms import *
from django.contrib.auth import login, authenticate
from django.contrib.auth.forms import UserCreationForm
def register(request):
if request.method == 'POST':
context = {}
registration_form = RegisterForm(request.POST)
context['form'] = registration_form
if registration_form.is_valid():
registration_form.save()
else:
context = {}
registration_form = RegisterForm()
context['form'] = registration_form
return render(request, 'QuickQuiz/register.html', context)```
@native tide
@cerulean vapor I have implemented the command and it worked great but I had a question. Do you know of a package similar to bootstrap_daterangepicker which will allow me to have users select multiple days. In that specific package I can have them choose a range but I would also like for users to select separate days. Any ideas?
how did you make the text green in discord tho
did it do that because its code block?
@last patio
oh thats cool
print ("I see now")
ah
ik thats not proper print format btw lmao
actually ill just change it
hey, can anyone here help just a bit w django?
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(null=True, blank=True,
default='default.jpg', upload_to='profile_pics/',
validators=[validate_image_file_extension])
about = models.CharField(null=True, blank=True, max_length=200)
githubusername = models.CharField(null=True, blank=True, max_length=80)
domes = models.IntegerField(default=0)
followers = models.ManyToManyField(
User, default=None, blank=True, related_name="profile_followers")
slug = models.SlugField(null=True, unique=True, max_length=256)
def __str__(self):
return f'{self.user.username} Profile'
def get_absolute_url(self):
return reverse_lazy('users:profilepage', kwargs={'slug': self.slug})
def followers_as_flat_user_id_list(self):
return self.followers.values_list('id', flat=True)
def save(self, *args, **kwargs):
username = self.user.username
self.slug = slugify(username)
super().save(*args, **kwargs)
This is my model
Was wondering how do I list all the followers of a profile in an APIView?
class FollowerModelSerializer(ModelSerializer):
user = CharField(source='slug')
class Meta:
model = Profile
fields = ['user', 'followers']
This is the serializer.
class FollowerModelViewSet(ModelViewSet):
queryset = Profile.objects.all()
serializer_class = FollowerModelSerializer
allowed_methods = ('GET', 'HEAD', 'OPTIONS')
def list(self, request, *args, **kwargs):
self.queryset = self.queryset.filter(id=request.user.id)
return super(FollowerModelViewSet, self).list(request, *args, **kwargs)
And this is the API
All it returns to me is the id of followers in the API View instead of all the followers.
Allow: GET, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept
[
{
"user": "pop",
"followers": [
1,
4
]
}
]```
This is the response I get.
Basically, I want to get the username in there instead of the user id.
Hi wanted to ask a question its about a game not programming its name is Ag Drive is it still available on app store or any country or region to download it from app store?
Missed it bad just wanted to know if you can help
@willow iron look into nested serializers
nvm lol
it was an easy problem, was just missing a concept. solved it a while later. thanks a lot either way!
just had to use slugrelatedfield
anyone here able to help me with django-allauth?
sure
what's the issue?
I personally prefer django social auth but allauth works too ig :))
sure
can someone help me with Flask ?
can someone help me with Flask ?
@sage thistle don't ask to ask, just ask.
👀 ^ [**flask **] i am trying to do a site where users can type in some stuff ,which they want us to deliver like , example : if u want grocery u need sugar 5kg , salt 1kg .... u just type it in and the things which they type will be saved in db and sent to the delivery guys ,,,
problem : when they type the item which they want and click on the add more button i want that previously written item to be displayed bellow the Sugar ^ in the pic if they click add more again the same should happen
how can i do it?
can anyone help me a little bit
im making a webpage
i want it to be like when a person fills a form, the data is sent and shown in my terminal
i don't flask so i asked
👀 ^ [**flask **] i am trying to do a site where users can type in some stuff ,which they want us to deliver like , example : if u want grocery u need sugar 5kg , salt 1kg .... u just type it in and the things which they type will be saved in db and sent to the delivery guys ,,,
problem : when they type the item which they want and click on the add more button i want that previously written item to be displayed bellow the Sugar ^ in the pic if they click add more again the same should happen
how can i do it?
@sage thistle JS would be useful here
oooh! okay ? i havent tried it yet but can u tell me a bit more about it? @vestal hound
JavaScript
you basically want a dynamic webpage
you could do this with Flask but it’d be inefficient and complex IMO
You will basically have an empty array and a js function that each time you call it, it will push that required ingredient to the array
so when u use "add more" button you will call that js function instead of performing a server call
ooooh! okayy ig i have a idea , i will try it out ty
is there any good tutorials on this subject?
What subject?
maths
Web development with python
I'm very new to it, where would be a good place to start. I know js, HTML, css, php already.
Try cs50 web
Thanks !
any help for react here?
or this
F
Can someone tell me if there is some tool to make beautiful websites like these? They look so similar.
Python datetimes made easy
Python dependency management and packaging made easy.
lmao
jekyll theme
@marble carbon where can I get it?

AttributeError: Manager isn't available; 'auth.User' has been swapped for 'user.User'
how to fix this.... I am getting this after i made a custom user model using AbstractUser class
any suggestion
@native tide AUTH_USER_MODEL='youapp.CustomUser' in settings.py
I did this already....my custom user model is working fine but when i register a new user ...it raise this exception
the django docs say that swapping out the default model mid way through a project introduces a lot of problems
maybe delete your db and try again?
It was starting....i deleted the database three times making every thing again 😂
I'll have to dig deeper in docs i guess
Hey guys Im using django , I have a Model that i added a custom function to, when i get a queryset i need to sum all of monthly_totals
class CustomerTransaction(models.Model):
customer_transaction_id = models.CharField(unique=True, max_length=255, blank=True, null=True)
customer_agreement_id = models.ForeignKey('CustomerAgreement', on_delete=models.CASCADE, null=True, blank=True)
meter_id = models.ForeignKey('Meter', on_delete=models.CASCADE, null=True, blank=True)
amount_tax = models.DecimalField(max_digits=12, decimal_places=2, default=0,
transaction_date = models.DateTimeField(blank=True, null=True)
amount_including_tax = models.DecimalField(max_digits=12, decimal_places=2, default=0, blank=True, null=True)
meter_number = models.CharField(max_length=255, blank=True, null=True)
def monthly_total_kw(self):
today = datetime.date.today()
total = 0
if self.transaction_date.month == today.month and self.transaction_date.year == today.year:
items = self.customertransactionitem_set.filter(units__isnull=False)
for item in items:
total = total + Decimal(item.units)
return total
i would like to be something like this,but it wouldn't work because its not a column in the table but rather a function...is there another way i could do this without having to loop through each item and add them together?
transactions = CustomerTransactions.objects.all()
total_kwh = transactions.aggregate(total_kwh=Sum('monthly_total_kw'))
does anyone have experience serving a django page as an actual url instead of localhost?
I tried using hosts file to redirect an example url to localhost with the port, but it doesn't direct from that url to the stuff I am serving on the localhost
Hey guys Im using django , I have a Model that i added a custom function to, when i get a queryset i need to sum all of monthly_totals
class CustomerTransaction(models.Model): customer_transaction_id = models.CharField(unique=True, max_length=255, blank=True, null=True) customer_agreement_id = models.ForeignKey('CustomerAgreement', on_delete=models.CASCADE, null=True, blank=True) meter_id = models.ForeignKey('Meter', on_delete=models.CASCADE, null=True, blank=True) amount_tax = models.DecimalField(max_digits=12, decimal_places=2, default=0, transaction_date = models.DateTimeField(blank=True, null=True) amount_including_tax = models.DecimalField(max_digits=12, decimal_places=2, default=0, blank=True, null=True) meter_number = models.CharField(max_length=255, blank=True, null=True) def monthly_total_kw(self): today = datetime.date.today() total = 0 if self.transaction_date.month == today.month and self.transaction_date.year == today.year: items = self.customertransactionitem_set.filter(units__isnull=False) for item in items: total = total + Decimal(item.units) return totali would like to be something like this,but it wouldn't work because its not a column in the table but rather a function...is there another way i could do this without having to loop through each item and add them together?
transactions = CustomerTransactions.objects.all() total_kwh = transactions.aggregate(total_kwh=Sum('monthly_total_kw'))
@hollow root if it's a function, you most likely can't directly query it, as it is pure python
an option is adding computed fields and store in the db, and then you can directly query it
does anyone have experience serving a django page as an actual url instead of localhost?
@vestal estuary as a url, just means hosting it somewhere else, pointing your dns at it, and wiola (of course, not the whole story)
ngrok is a nice alternative
or geting an aws ec2 instance for example and just hosting it there
look up computer networking basics and you'll begin to understand the process
but what you're basically looking for is, "deploying the app"
google deploying a django app, and im sure you'll find some great sources on how to do it
@hollow root actually now that i think of it, you don't really have complex logic in that function, look into query expressions more specifically, F queries - a django thing
and rewrite it as a pure query
Has anyone here worked with Crispy Forms?
you'll have more luck actually asking your question
@flint breach thanks ill have a look at f queries
I have this Crispy Form in Django, I want there to be some space between the fields and for the last 2 fields to take up the entire row
In the template I just have ```
<fieldset>
<legend><h1>Get a Quote From Us:</h1></legend>
{% crispy form %}
</fieldset>
Forms.py - ```
class ContactForm(forms.Form):
first_name = forms.CharField(required=True)
last_name = forms.CharField(required=True)
contact_email = forms.EmailField(required=True)
phone_number = forms.CharField()
company_name = forms.CharField()
additional_comments = forms.CharField()
helper = FormHelper()
helper.layout = Layout(
Row('first_name', 'last_name'),
Row('contact_email', 'phone_number'),
Row('company_name'),
Row('additional_comments'),
)
helper.form_tag = False
field = forms.CharField(
widget = forms.Textarea(attrs={
'padding-right': '10px'
})
)
I think you can do something like this @twilit dagger
else, you need to split the form and use columns and rows (that is if you use a css framework)
I hosted my Django project on PythonAnywhere. Now i want to update some stuff in my css file but the changes do not show up.
Before I put it on the server I did add a STATIC_ROOT and ran collectstatic
But should I run collectstatic again when I make changes to the static files?
Notsure if this is the right place for my questions, if not, im sorry.
but anyone here with experience with flask?
Trying to make a "bank"-app as a project, and I was thinking that every user that makes an account would get a "randomized encrypted URL", so that i can prevent people from just typing in other users in the URL and getting there bank account up.
Im new btw. So little experience 😦
you should probably look into flask_login @lean rapids
because a url can be brute forced, but flask_login uses sessions to allow you to restrict acess to urls based on the users status
@native tide willdo, thanks! 😄
np xd
Anyone here have experience with flask-socketio and/or vue-socket.io
Having some issues with the two combined, not sure if its related to either of them or to Traefik
Flask is logging the requests so they are reaching the server which is inclining me to believe it is an issue with flask and vue, not traefik
Hello everyone! I am trying to learn how to host a little chat on the web as an exercise, but I don't know where to start.
I would like to create everything, from the server hosting the chat to the actual code 🙂 Does anybody know where I should start?
Hilariously enough there are tons of screencasts of implementing a chat app using flask-socketio
Following along to them is a good start
Deployment stuff is another ballgame with tons of options
Im not sure if web development is the right spot, But im trying to go through the django tutorial and I cant even create the project, Ive been trying for over and hour and am totally lost
I have django and pip and python installed but it wont let me create the project
@quick cargo Thanks for the help, It dosent error but now just does nothing
no file or folder is created either
try "dango-admin"
you sure its not installed on a virtual enviroment or the sort
I dont know what that is
okay so somehow you have two diffrent aliases for that but alright
you should be able todo:
py -m django startproject name_here instead of django admin
yea when i do anything with python instead of py it just does nothing
OMG I LOVE YOU
How do you host a Django project on something like Wordpress?
Can you integrate it?
thank you @quick cargo
I feel like something is wrong with my computer, It now isnt working for the very next thing.
It created the folder with everything in it but
py manage.py runserver
Does nothing
im in the project directory so that isnt it
i tried with Python instead of py just for kicks and same thing, nothing
no why would you need to do 'py'?
because thats how you run python files...
whats you current working directory and file layout
It goes "RootFolder/Project/manage.py runserver" that's all
manage.py is in the directory
@twilit dagger doesn't work like this on windows, only linux man
same thing nothing
uninstall python
yeah pretty much
reinstall it
uninstall it all and reinstall it entirely
I did that this morning because I thought something went wrong, do it again?
uninstall it all
get a new distribution
preferably 64 bit not 32 this time though
i cant really do much other than say say, My Python doesnt have sqlite installed so by default i cant run manage.py lol
https://www.python.org/downloads/release/python-386/ Is the right spot right?
Maybe you should get like VSCode
I have that
then you can use the terminal in that rather than cmd
Alrighty everything is working perfect and as expected after reinstalling and running in the visual studio code terminal
Thank you two

Posting your specific question will let people help you faster
I'm trying to fix up a models for different text sections
for example
this is hard coded
but I want those text field soft coded
here is my code
from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse
# Create your models here.
class ProfileImageBox(models.Model):
profile_image = models.ImageField()
name = models.CharField(max_length=50)
sub_description = models.TextField(max_length=150)
def __str__(self):
return 'Profile Image'
class InfoBox(models.Model):
title = models.CharField(max_length=100)
content = models.TextField(max_length=4000)
def __str__(self):
return self.title
class DescriptionInfoBox(models.Model):
title = models.CharField(max_length=100)
content = models.TextField(max_length=2000)
def __str__(self):
return self.title
But how do I link this to the database?
I applied migrations
so it should work
but
it doesn't
I can't see it in the django admin page
Could anyone help with this problem?
when you said you applied migrations, you mean you ran the make migrations and then the migrate command?
ye
