#web-development
2 messages ยท Page 75 of 1
test = request.json.get('name')
replace it with thta
the python bit
or in fact - just do print(request.json)
No error, but it printed None haha
127.0.0.1 - - [31/Jul/2020 15:18:38] "[31m[1mPOST / HTTP/1.1[0m" 405 - None 127.0.0.1 - - [31/Jul/2020 15:18:38] "[37mPOST /extract/ HTTP/1.1[0m" 200 -
I'm thinking it's an issue with post
hmmmm - I don't know enough jquery to be of any help I think. The last thing I can think to suggest is $.post( "/", { name: "John", time: "2pm" }, dataType="json" );. My only other suggestion would be ditching jquery and using the default JS fetch API
const data = { username: 'example' };
fetch('https://example.com/profile', {
method: 'POST', // or 'PUT'
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
There's an example of posting some data with the fetch API
I'll give fetch a go! I've been trying this method for three days and can't for the life of me figure it out, haha. Thanks for the help, though!
If you're having trouble with the fetch stuff. Ping me and I'll set up a minimum example to show the two parts working together
Hello, everybody,
I recently finished a book on "Flask Web Development", it was very enriching. So I was able to familiarize myself with Flask and SQLAlchemy to build a small REST API.
I would now like to do a more consistent project, so I turned to OpenAPI to do the specification of my future API. So I generated the backend code in Flask with Swagger Editor but I'm having difficulties to make the link with SQLAlchemy. The generated models should not be touched in case of code regeneration, which is logical, but how can I define my columns for my database? I was thinking of inheriting this model or maybe creating a model only for the database, but in this case I don't see the interest of this code generator.
I have difficulties to define an interesting workflow. Has anyone ever built an API from the code generated with Swagger Editor and implemented persistence with SQLAlchemy?
I hope my question isn't too general...Thanks for the help
I FIGURED IT OUT!
So the route needed to be '/extract'
$.post( "/extract", { name: "John", time: "2pm" }, dataType="json" );
Which makes a ton of sense lol
oh - haha. It's always a simpler problem than it seems to be
Honestly. I'll tell you what though, never gonna make that mistake again haha
Hi, so I have the following function:
def get_user():
data = get_cookie_data()
if not data:
return None
else:
discord_id = data['discord_id']
print(discord_id)
current_user = User.get(int(discord_id))
print(current_user.username)
return current_user
get_cookie_data() is this:
def get_cookie_data():
try:
token = request.cookies.get('user')
return jwt.decode(token, read_file('./assets/public.pem'))
except Exception as e:
print(str(e))
return None
I am using Stripe with sessions api, which basically lets you pay and redirects you back to the main website along with a code. When I am trying to register the user to the database I am calling the get_user() function, which occasionally returns None, meaning that there is not user logged in. In order for the user to pay it is obligatory for them to be logged in.
This is the route in which the error is being generated:
@app.route('/success')
def payment_success():
session_id = request.args['session_id']
customer_session = stripe.checkout.Session.retrieve(session_id)
customer = stripe.Customer.retrieve(customer_session['customer'])
stripe_response = requests.get(url=f'https://api.stripe.com{customer["subscriptions"]["url"]}',
headers={'Authorization': f'Bearer {stripe_keys["secret_key"]}'}).json()
resp = make_response(redirect('/dashboard'))
if 'data' in stripe_response.keys():
if customer['id'] == stripe_response['data'][0]['customer']:
user = get_user()
user.stripe_id = customer['id']
user.cancelled = 0
db.session.add(user)
db.session.commit()
user_to_guild_handler(BOT_TOKEN, GUILD_ID)
requests.post(f'http://{DISCORD_SERVER_URL}/new_member_alert',
data=json.dumps({'user_id': user.discord_id, 'email': user.email}))
try:
coupon_key = request.cookies.get('coupon')
coupon = Coupon.get(key=coupon_key)
coupon.uses -= 1
coupon.update()
resp.set_cookie('coupon', 'USED', expires=0)
except Exception as e:
pass
return resp
Does anyone have any idea on why that thing could happen"
Exception details:
AttributeError: 'NoneType' object has no attribute 'stripe_id'
File "flask/app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "flask/app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "flask/app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "flask/_compat.py", line 39, in reraise
raise value
File "flask/app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "flask/app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "app.py", line 251, in payment_success
user.stripe_id = customer['id']
NoneType is referring to the None user object
Basically my question is: How can I solve this issue? What is causing it? Cookie expiration is set to one week
One possible answer I have is that they use incognito mode
But they wouldn't be able to login in the first place
Anybody familiar with node.js?
@plain zealot I can help with syntax and discord.js, idk about anything else
For the user accounts database, do you want make a different table explicitly for users only or do you create a custom User Model?
Using django
I dont want to use the default login/signup form of django so what should i do?
Does django let you use html?
yes
Learn How To Make Signup Form Using HTML And CSS | Create Sign Up Form In HTML CSS
โค๏ธ SUBSCRIBE: https://goo.gl/tTFmPb
โค๏ธ Complete website Using HTML and CSS
โ๏ธ 8 Complete website step by step
โ๏ธ Source Code Download
โ๏ธ 76 Lectures, 12 Hours Video
โ๏ธ Course Completion certifi...
Idk how good it is
I went with the first thing I found
Swap out the background with whatever, shouldn't be too hard
Actually django has a inbuilt way of dealing with forms, and i want to create a custom form but to do that should i use the default Users model or create a new one?
It is not about syntax though
backend stuffs
@upbeat forge
Make a database with table called logins (or whatever you wanna call it) with an id, username, and password column
Definitely not the most secure, but it works for development
It is not about syntax though
@plain zealot wait til someones online I guess
hi, it's possible to start http.server (SimpleHTTPRequestHandler) and close him after one request? or after N request?
@upbeat forge i usually create a new one.
@upbeat forge i usually create a new one.
@ripe goblet ohh and can i use all the default functions lile login or logout with that self created model?
Okayyy
If I want to let the user upload a thumbnail image for a post and I want to be able to use it in different sizes, how should I do that?
I can save it in a small size like 125px by 125px but then quality will be super low when I need to enlarge it
So do I just save it as the original file and scale it down in the HTML as needed?
Hi, for DRF, is it okay if I only have JWT Authentication under DEFAULT_AUTHENTICATION_CLASSES or will I not work with sessions?
The problem I'm facing right now with sessions enabled is whenever the server restarts, it deletes all sessions and it doesn't seem to check if there's an existing JWT token so it just throws an Unauthorized error.
who knows how to use django
not me, I'm also trying to learn it
I want to make a comment web app, where you can select a user and give them a suggestion
is it a bad idea to host web server on localhost? I'm thinking of getting some of the new raspberry pi 4gb ram and making a cluster server
would be better
I'm a high schooler just making a blog with Flask for fun
In that case is it possible to use Google Drive instead of S3 to store my images?
would NodeJS be better than django or flask?
@native tide Both are powerfull when used properly . The one you know how to use properly, can be a great asset for you.
In that case is it possible to use Google Drive instead of S3 to store my images?
@wind walrus
You don't have to use s3, but Google drive won't work
Are there any free alternatives?
Well. S3 gives you 5gb for free
So
S3
I'm not sure on what, but there probably are free ways to host or
is S3 free?
5GB is permanently free? Or like just 1 year or sth?
That's nice cos I won't be using that much GB anyway
As part of the AWS Free Tier, you can get started with Amazon S3 for free. Upon sign-up, new AWS customers receive 5GB of Amazon S3 storage in the S3 Standard storage class; 20,000 GET Requests; 2,000 PUT, COPY, POST, or LIST Requests; and 15GB of Data Transfer Out each month for one year.
Sorry my English is not my first language does that mean it's "for one year" only?
There is not any limit i suppose
I mean you can use those requests and 15gb data each month for one year
Oh. Apparently so. It's very cheap though, every after that one year
so yeah, its for one year
True, would've been great if it was permanent but
Everyone company tries its best to provide the service but there's always a catch lol
Technically, I mean there won't actually be any company that will provide you unlimited cool features forever.
what is the difference between react and django
React is a Javascript Framework whereas Django is a Python framework
I know that
that is what I don't understand
You don't understand front-end and back-end?
yeah
React is a Javascript framework which proves to be a powerful alternative
we can not do like django, i mean templates and urls ...
Django is a back-end framework and React is a front-end framework.
That's why you cannot use React like Django
Imagine I wanna build an instagram clone what do I use?
if react what is it's job
django
or both
yeah
For instagram clone, you need a client and a server.
yeah
I hope you understand what they mean?
good.
For the Client side, You would use React
Client side == Front end
got it
yes please
alright.
Now after you have designed the client side, you will require it to send requests to the server side for retrieving data
For that, you will require a server to process the requests and send back reports
for the client side do I use react to bring data from the server and display it
For a server to work, you need to do server-side scripting using any backend language
@late fjord , the front-end part is a large concept.
Let me explain to you what the front-end actually is.
please
yeah
you've visited spotify right?
no, but I know how it works
yes
Like the new releases, the new songs , etc. etc.
This is the front - end
Now, whenever I click on any of the song
you send a request to the server
it will shift to the back end
The front end requests the server aka back-end
the server sends back the required code and the front end runs it.
That's it.
got it
Now, the backend consists of server and a database too
For a database included server, the server , after receiving the request from client will check into the database(ofc through a piece of code) and then retrieve the data and send it to the client.
That's how it works ๐
I hope you understand, do you?
No doubt?
but I have seen some people building react clone with react and firebase
react clone of what?
I mean facebook spotify instagram ...
React is capable of making API calls (send request to backend), which deals with the data. React cannot deal with database or any datasource itself.
btw React is a library and not a framework.
I would suggest you to check it out.
It has a good explaination about firebase.
If you do not understand , just ping me ๐
Firebase is a mobile-backend-as-a-service that provides powerful features for building mobile apps. Firebase has three core services: a realtime database, user authentication and hosting.
^ there.
It is the first line the webpage says.
thank you
basically, firebase is a mobile-based-backend
no problem!
It's my pleasure to help you :D.. If you need further help, feel free to ping me up! ๐
We surely can.
If the website has a client and a server that works, then we cannot.
React is only a front-end library.
got it? @late fjord
Btw a quick question - why would something like Imgur or Google Drive not work to store images? You can upload/retrieve files with Python right?
Imgur or Google Drive as opposed to S3 that is
yes, but can u give me an example of a website without server
sure
@late fjord btw do not use the words - "without a server"
Every website is hosted on a server which keeps it alive
Lol my first website was just HTML and CSS no backend at all
yeah got it, so, can a website exist without backend
Like a simple <h1> Hello world </h1>
Let me grab a link asap.
yeah got it, so, can a website exist without backend
@late fjord yup!
It is a gaming blog.
It only has a front-end and a CMS by blogger (if that really counts lol)
thank you so much you helped me a lot I'll check it, btw, can I send you a friend request
sure ๐
It's my pleasure to help people clear their doubts.
I do myself have a lot of doubts in general.
A quick tip: "Always try to clear your basic concepts when progressing further"
can I ask a quick question as well
why would something like Imgur or Google Drive not work to store images? You can upload/retrieve files with Python right?
I've accepted it.
I'm just a high schooler coding for fun, so this website won't be important or anything
Imgur or Google Drive as opposed to S3 that is
why would something like Imgur or Google Drive not work to store images? You can upload/retrieve files with Python right?
@wind walrus Google drive stores images?
Yeah you can upload any file to Google Drive
yea?
can't we just use Google drive or Imgur instead of paying for S3?
It's just a website for fun so it's not serious or important or anything just a blog
For simply displaying images, you can use Imgur probably. I have not tried. Google drive might be difficult though, it may not allow embedding the image in another site. Worth a try though,
So what can S3 do that Imgur wont be able to do?
be interacted with programmatically
Does anybody know how to use file feilds in django
just ping brunckek he know a lot of stuffs he might help you @unique hill
@flint breach i have a doubt regarding file feilds in django
can you help me
@late fjord thanks
you are welcome
I am trying to make a form to ask a question, I set initial to the asker to the request.user but it is not saving to the database, I don't know why @unique hill can you help me with this
this is my forms.py:
from django import forms
from .models import *
class AskQuestion(forms.ModelForm):
class Meta:
fields = "__all__"
model = Question
and this is my views.py:
@login_required(login_url='/user/register/')
def ask_question(request):
form = AskQuestion(request.POST, initial={'asker':request.user})
if form.is_valid():
form.save()
return redirect('/questions/')
return render(request, 'questions/askquestion.html', {'form':form, })
yes it does
@unique hill
then checkout if the form has the appropriate action
and also if the button is of the type submit
I didn't set the action
that's why i believe its reloading
<form method="POST">
{% csrf_token %}
{{form.title.label}}
{{form.title}}
{{form.text.label}}
{{form.text}}
{{form.tags.label}}
{{form.tags}}
<input type="submit" value="Ask">
</form>```
put a action
what is the role of the action
to check whether that is the problem
do I set it to ""
action means your form knows where to go when this form is submitted
if there is no action than it will keep on reloading the current page
so what do I do
what do you want to do after the ask button is pressed
I want them to be redirected the page of the question
try using action for this ask_question function
what is the name in urls.py for ask_question function
action={% url 'askquestion' %}
just {% url 'askquestion' %}
show what changes you made
maybe because the form is not valid
in the html file
<form method="POST" action="{% url 'askquestion' %}">
{% csrf_token %}
{{form.title.label}}
{{form.title}}
{{form.text.label}}
{{form.text}}
{{form.tags.label}}
{{form.tags}}
<input type="submit" value="Ask">
</form>
this looks fine
put a breakpoint at form
wait a sec
what is the name of your table in models
where you want to save this data
and my urls.py:
urlpatterns = [
path('', questions, name='questions'),
path('ask_question/', ask_question, name='askquestion'),
]```
where breakpoint
I don't get you
do you know how to debug
no
very good
so search on youtube
how to debug a django code
do u use vs code or pycharm
I use vs code
I actually removed the instance and it is saving
do you know how to the instance correctly
please tell me that you do
@unique hill
your code is working now??
after changing python form = AskQuestion(request.POST, instance={'asker':request.user})
to:
form = AskQuestion(request.POST)```
but overhere it says initial
i am actually not familiar with this instance thing
this might help
Hey, hope I'm in the right channel. I'm looking to build some API for an ELO system (specifically using Docker, but that shouldn't change much from the python side). I've been looking at Flask to build the API. What I'm not sure about is how to build that API. I want some private routes for registering that a match has happened and should update the ELO. But I also want some public API at some point for other services to be able to read the data. Is there a way to do this in Flask, or would it be better to separate the two into two different apps?
thank you @unique hill
Anyone using apscheduler for flask scheduling ?
I am now having trouble with django I don't know what is happenning ```bash
if request.method=="POST":
^
SyntaxError: invalid syntax
can anyone help me
@native tide please help me, you're the only one online
Well you are having synax error if you dont have any code after : just add pass
error should dissapoear
Sorry to bother you I found where the problem is, it is because I forgot to close ()
if u want to use js in django does it have to go in the static folder?
also is there a way to pip install pyjs or do i have to clone the repo
Hi, does anyone know if it is possible to have the user be able to "change" the queryset filter on Django? I want to make a field on my site that allows the user to type in a date and hit enter, then it will show them a list of objects that match that date. is this possible within Django?
@native tide if its only a small 1 off bit of JS it can just go in <script></script> tags in the html
@native tide pip install git+https://github.com/pyjs/pyjs.git#egg=pyjs
Can someone help me. I have completed a 'register' page and form in Flask. It redirects to /login. I want to flash a success message when i reach /login from my completed /register form. How can i do this? I assume there is someway under the @login route to determine where the user came from... but i dont know
Bois
I need to know if a pi zero could run a basic flask app
The app only takes input, saves it to a database, then displays it
@ me if anyone knows
it should still
Like flask is light weight
and a small server wont use much
A small Django app i run uses about 100MB RAM total and a unnoticeable amount of CPU

im cheap ok
does anyone know any search engines that allow crawling/scraping? Or free apis for web search results? (Must abide by TOS and of course laws)
Does anybody know if you can add a name to a URL path in Django when using the include object? or can you only add a name with returning a view from the url path?
wonder if the path seperators in html differ for windows and linux systems
I've forked a project on codepen to use as an animation for my site nav, but I can't seem to get it to work. Consists of three files, but testing it through my flask app fails
anyone have a sec to tell me how I'm an idiot?
So im trying to web scrape using bs4 and im following an old tutorial. This is my current code: ```from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup
my_url = 'https://www.retailmenot.com/view/shopdisney.com'
#opening connection, grabbing page
uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()
#html parsing
page_soup = soup(page_html, "html.parser")``` but i keep getting an error
am i missing any dependencies ?
Not that easily
hmm is there a work around
They use Cloudflare which detects your bot and forces you to solve a captcha which you can not do that easily
That should work
But they may still ask for a captcha
but there are apis to solve them
captcha solver services
I'm just wondering can i really incorporate Google Material design to a Dango project? I have used Materialize CSS but i prefer MD
I have been search for quite sometime now but haven't found any example on how to achieve this
Guys what is the point of name in url definition in my urls.py?
Like :
path("".views.function,name="something") #What does the name do?
You can easily refer to that view in your template
when in a template, you can link that url with {% url 'something' %}
and I think redirect can also use those
Oh
So I can do a href like :
<a href="{% url 'something' %}">Goto something</a>
And this will point to the main page right?
Since something's url is "" in this case
that seems correct
@edgy marsh use selenium
What kind of database would I use for an email subscription list?
I'm using Flask with Flask-SQLAlchemy and deploying it to Heroku with Heroku Postgres
Would I store a mailing list in SQLAlchemy database?
mailing database doesn't seem to be a huge deal i guess choose whatever you're comfortable with. you should be more focus on the content than which database to choose.
Hello people,
Does someone have a good tutorial to help me setup a Flask app with Apache WSGI without using virtualenvs?
I tried it myself but I keep having a ImportError: No module named flask in the Apache logs (of course the Flask app works fine if I run the standalone server, and I already tried making sys.path.appends in the wsgi file)
Maybe print out sys.executable to see what python Apache is running from
How can I do that? Trying to write to a file in the wsgi file does not seem to work
Print should appear in the log, or you could raise an exception, which you already know how to see
How do I put my logo on my navbar?
@silent shore <img src="image link">
ah, looks like my WSGI is running python 2.7 instead of 3.5
does anybody know how to upload multiple images in django
Managed to fix it. Discovered at the same time that wsgi module for Apache is only compiled for a specific version of Python... that sucks.
Thank you btw
Im using Django and I need to make requests from POSTMAN with the csrftoken, however I noticed the token is only generated and returned when I visit the /admin route, but is there some way I can get this to work with guest endpoints, such as a /register route?
thx, the csrf_exempt decorator works
I'm having a lot of trouble reading Flask data for my frontend. I have a React frontend and a Flask backend which serves as the REST api. When I serve it locally with npm start, the two can communicate seamlessly. However, if I try to host them on Heroku, I'm unable to do so with the error (index):1 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0.
I've spent the entire day fruitlessly trying to solve this issue. Any advice?
Stack Overflow question with more details: https://stackoverflow.com/questions/63215903/cannot-get-data-from-flask-from-react-when-deployed-on-heroku-but-works-locally
Current website, trying to GET data made with Flask from /api/test: https://test-mandarin-web-app.herokuapp.com
Repository with a dozen extra commits from me trying to figure out all the different ways this could be solved: https://github.com/Destaq/chinese-resource-app
Does Django support OAuth2 Login with Discord? I know OAuth2 is platform agnostic, but the resources I've found mostly stresses on how to create your own OAuth2 system so other people can create clients to use it as a third party service, I just want to have my Django app allow OAuth2 login
hmmm, I think this might be what im looking for https://django-allauth.readthedocs.io/en/latest/installation.html
Ye, afaik that supports it
thx
Is BaseBackend not a class anymore from the module django.contrib.auth.backends?
When i import it, it doesnt appear in intellisense, and it also throws an error saying BaseBackend cannot be found
from django.contrib.auth.backends import BaseBackend
class DiscordAuth(BaseBackend):
def authenticate(self, request, token=None):
print("Hi")
I checked my django version ```
"django": {
"index": "pypi",
"version": "==3.0.8"
},``` just incase
AWS EC2 Django help needed.
my django backend has function wherein a file is created with :
f = open("xyz.txt", "w")
when i run it with runserver command on ec2 aws it runs fine.
but when i run it with apache it says permission denied and give me an error
Hi! Im have been studing the most basic of python this entire week, i know loops, functions, classes, objects, data types, lists and all that stuff... And i want to start learning web development, i have been asking and some say... look for Django or flask... so i will do it but i dont really understand which is better and what the are for... so if some one is able to help me with a recommendation about How to enter into web development it will be great.... Thank you
flask it will be nice if you are a beginner
but before flask you should learn html & css
@dark agate do you know where can i learn those? and its completely necesary?
there is a lot of resources in youtube
a lot of people recommend the html & css crash course by Traversy Media
D:\programs 2.0\python\webdev\python-getting-started>heroku local
[OKAY] Loaded ENV .env File as KEY=VALUE Format
6:49:09 PM web.1 | Traceback (most recent call last):
6:49:09 PM web.1 | File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1520.0_x64__qbz5n2kfra8p0\lib\runpy.py", line 194, in _run_module_as_main
6:49:09 PM web.1 | return _run_code(code, main_globals, None,
6:49:09 PM web.1 | File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1520.0_x64__qbz5n2kfra8p0\lib\runpy.py", line 87, in _run_code
6:49:09 PM web.1 | exec(code, run_globals)
6:49:09 PM web.1 | File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\Scripts\gunicorn.exe\__main__.py", line 4, in <module>
6:49:09 PM web.1 | File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\gunicorn\app\wsgiapp.py", line 9, in <module>
6:49:09 PM web.1 | from gunicorn.app.base import Application
6:49:09 PM web.1 | File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\gunicorn\app\base.py", line 11, in <module>
6:49:09 PM web.1 | from gunicorn import util
6:49:09 PM web.1 | File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\gunicorn\util.py", line 9, in <module>
6:49:09 PM web.1 | import fcntl
6:49:09 PM web.1 | ModuleNotFoundError: No module named 'fcntl'
[DONE] Killing all processes with signal SIGINT
6:49:09 PM web.1 Exited with exit code null
so i was following the heroku tutorial https://devcenter.heroku.com/articles/getting-started-with-python?singlepage=true and theabove error occured when i run heroku local right after changing the index method to
def index(request):
r = requests.get('http://httpbin.org/status/418')
print(r.text)
return HttpResponse('<pre>' + r.text + '</pre>')
how do i fix this and what even happened in thefirst place
import fcntl
6:49:09 PM web.1 | ModuleNotFoundError: No module named 'fcntl'
pip install -r requirements.txt
Did installing the requirements work?
Guys what could I do to profit with Django or Flask excluding Freelancing and Making an online shop?
(As a teenager)
But it's related to web dev too
And I don't have permission to send message to #career-advice
like adsense
Oh... But it's blocked in our country . Isn't there like another way?
Ok lemme check it our . Thanks for the info tho!
tho affiliate marketing is good idea as well
Yeah . But still , almost the same
ik , but they have similarities
Like you advertise something in both
As far as I know*
well yea just u promote ur self as affiliate
I am having an issue using djangos LoginRequiredMixin, I get a circular imports error if I set login_url to reverse('test') for example, also even if I hardcode the url, it redirects me to some iwerd non existing url, could anyone help me with this?
you can build front ends with it
yeah, html is better
Is there someone who know about MYSQL and displaying data in a table with flask?
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.
Hey guys, i really need your helps.
Im making a project and im confused about design
so,
what i got:
the layout matters
as you can see, there are threads on the right
what you say, where should they open up?
if you click on a thread then it should move into the middle
upon the base chat
or stay in the right panel?
which is more comfortable?
this is it if you click on a thread
the right side changes
but is it okay to see the chat there? or would it be more intuitive to see just one chat in the middle,
base or a threaded chat
What do you say? Any response would be helpful :/
I'm not a UI designer but I'd rather the text input to be in the chat's div
Or the chat should be centered on the screen
@glass sandal yees-yes, this is just the layout. On the right side there will be a chat panel like in the middle if i choose this way.
But should it be there?
or open in the middle
I mean , I am not a UI designer as I said :(
yeah, i know ๐ but thanks
I am not as well, just thinking about best approaches. If it'd open in the middle, then you cant make mistakes and send messages to the wrong chat(because you might send if you see two chat opened)
but if you need to search for some infos, then you have to go back, search in the base chat or wherever
and open up the thread again
both has pros and cons
but which one's pros are bigger and cons are smaller? thats the question
personally you, @glass sandal , what would you use with more "passion", which one?
Uhhhh...Ummmm... I would say remove the div that is on the right side , and move the chat to the center
And you can do another chat in the dashboard
Like the left side
and then on the right u can see the list of threads, and if you open one, then it shows up in the middle. Otherwise you see the base/"main" chat of the channel in the middle
Oh I see
Threads are meant to organize the main chat into topics
you know
and organizing infos
around topics
to catch up later if you go on holiday or something
I mean , it's 00:21 here and I'm being a lil dumb . I may not be able to answer rn
They will
wait, so can u use flask as backend?
?
flask is backend framework @uncut rover
Hi i just instaled sublime text 3... can someone say me how to put there flask?
Hey
what u mean by put flask??
with pip install flask create something u want and run in terminal
@fickle fox Im new and i dont understand what is a virtual enviroment and i dont know how to download it and put there flask... can you help me?
pip install flask
I use phyton 3.5
where do i copy pip install flask?
ok, thank you
terminal
And if i understand well a Virtual Enviroment is a place where you run a project like in a closed room?
yes
ok, so i will go for it, thanks
@fickle fox thx for the conformation, wanted to hear it from a non-crappy coder
@silent shore <img src="image link">
@native tide @native tide it stays under it, I used a png image for nav bar
bois i have a question abt gunicorn
ive been getting
index() takes 0 positional arguments but 2 were given
and idk why
pls @ or dm if anyone knows
can someone help me with mock testing? I wrote this code but it dosen't work. Let me know what I am doing wrong. Thank you```python
class PrivateHomePageTests(TestCase):
"""Here we will check homepage for logged in user"""
def setUp(self):
"""Lets create a user and log him in"""
# Lets set up some user obj
self.user = get_user_model().objects.create_user(
first_name='test',
email='testman@testmail.com',
last_name='man',
mobile_number='9999999999',
)
self.user.country = 'Wakanda'
self.user.city = 'Gotham'
self.user.state = 'Metropolis'
self.user.country_iso = 'India'
self.user.longitude = '25.0000N'
self.user.latitude = '71.0000W'
self.user.save()
self.client.force_login(self.user)
@mock.patch("geoip2.database.Reader", mock.MagicMock(return_value="123.201.248.48"))
def test_that_logout_button_is_present(self):
"""Lets do a get req to home page with loggedIn user"""
res = self.client.get(HOME_PAGE_URL)
# now lets check is logout button is present in the home page
self.assertIn(b'<button class="btn btn-outline-danger"><a href="""{% url "accounts:logout" %}"""> Logout </a></button>',
res.content)```
so here the geoip won't work in TestCase so I am trying to mock it's response.
or if someone can tell me how to use geoip in tests that would help me too
need help with django
main.models.ToDoList.DoesNotExist: ToDoList matching query does not exist.
@last ginkgo #โ๏ฝhow-to-get-help But it looks like whatever entry your query is looking for does not exist.
hi im starting the webdevelopment by python
i have already started making a website
using css and html
but
should i need to install pycharm for it
or
can i make a seperate page on vs code {main.py} and i can make???
which is the correct way
plz anyone tell
send ss
@native tide
Is there something opposite of LoginRequiredMixin or should I make custom logic for that?
Pls anyone who can make some simple calculator with 1 parameter
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.
https://pastebin.com/qtZSerXg
@native walrus Please help me xD
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.
@native walrus Please help me xD
@native walrus SOLVED
hey is there any django help discord server
guys i need help i inserted an image using static the cod works but i cant see the image
@native tide can you show me your html file where you are trying to insert the image
can someone help me my regex url isnt working
here is the code re_path(r'^tic-tac-toc/pos(\d{1})/$', views.tictactoePos),
i need some help in #help-chestnut with django
hey, i have seen underscore used quite often in django docs, can anyone explain what it means? py role = models.CharField(max_length=1, choices=[('A', _('Author')), ('E', _('Editor'))])
('A', _('Author'))
``` `underscore before ('Author")`
that's usually used as the "no name" function for localization/i18n
here's an article on using it and how it works https://medium.com/@fanisdespoudis/how-to-translate-python-applications-with-the-gnu-gettext-module-12634ad6debf
Simple Flask question: do users see any print('something') commands that are run in the code?
I have quite a few print() commands for development and bug fixing purposes, but I don't want my users to see those, even when they go looking
by users do you mean other developers? or webapp users? @nova crest
@nova crest prints go to the console, so unless you are doing something strange, generally, your user won't see print statements (unless they are running said server)
I was talking about Web App users
I figured the prints would only go to the server console, and not reach client side
thanks for the confirmation!
@nova crest fwiw, generally, when running a server, you don't want a bunch of prints to console though because daemons typically don't run in an active console (they are usually background jobs) so you usually want to do logging to a file rather than to a console... but for dev purposes, that is fine
not to mention, administrators typically have a set number of places to go hunting for logs
@mellow tide Fair point. I will eliminate the prints when I'm ready for prodution
TODO: ftw ๐
Hey guys. I created a boolean field in my models, and I wanted to set to True this specific field, from my settings.py in Django. Is it possible to do that? If anyone could help me to sort this out, it would help a lot
I don't really know Django, so I'm of no help here 
I figured it out, (its flask btw), in the app.run() you put debug=True
Hey guys. Is there any datastructure in js to implement a queue with O(1) time operations?
List's shift() operation has O(n) time complexity
which operations?
enqueue and dequeue
An array
Popping and insertion are o(1)
Oh wait
That's a stack
No. An array will work
I'm sure there're tons of implementations, but it's trivial to roll your own
You just need to use shift instead of pop
@rigid laurel p sure that's O(n)
Reading about it, it's engine dependant
I think common implementations would leave it O(n)
it is possible to have constant time shifting but I don't think that's what most common use cases require
Yeah. You can't rely on it. I'm surprised js doesn't set out these requirements the way python does
I can't find a decent source for time complexity of operations in JS anywhere. Shift/Unshift seem to be pretty much always O(N), but I'd like to see a reasonable place have done the research
JS is just a spec, so the time complexity will depend on the underlying implementation of the JS engine, which varies between browsers
Sure. But python specifies time complexities
And is also just a spec
Although it does have one main implementation
User submits a link, it adds the link to the database with a timestamp. I want to remove this row once 30 days has passed. I want to know the best way to check if a record is older than 30 days and remove it ?
delete from table where condition
here's the v8 engine for example, it looks like they have a "fast" version of array shift as well as a slow ( O(n) ) version depending on if they can use the fast one https://github.com/v8/v8/blob/4b9b23521e6fd42373ebbcb20ebe03bf445494f9/src/builtins/builtins-array.cc#L563-L592
hey ik this is a python server but
Im having some trouble making my image full size in css
body{
margin:0;
padding:0;
display:flex;
justify-content:center;
align-items:center;
height:100vh;
background: url('https://cdn.wallpapersafari.com/1/88/L6Aojc.jpg');
background-repeat: no-repeat;
font-family:cursive;
}
this is what i have so far
ive tried many things but nothing works
please ping me if you could help
delete from table where condition
@rigid laurel but how can I run this automatically once a day without restarting server ?
Cron job or built in python scheduler
thanks will check out a cron job
or hook it into some unrelated process
@native tide What do you mean by Full size?
take up the whole screen
The full size of the Image, or fill the size of the container?
container
Background-size:cover
If you want to make things correctly use this:
background-size: cover;
background-repeat: no-repeat;
background-attachment: fixed;
background-position: center;
thank you
You're welcome
Hi y'all, I'm not quite familiar with JavaScript and the legacy code of the Flask App that i have here, but maybe you can help me to figure this one out:
I have a Slider with control buttons that lets you cycle through a few pictures. I want to automate this slider so that it executes the function for the next image on click or does it automatically if no click is received within 3 seconds. I think I identified the relevant function:
$(".hero-wrap-text-slider-holder a.next-slide").on("click", function() {
$(this).closest(".hero-wrap-text-slider-holder").find(sync2).trigger("next.owl.carousel");
return false;
});
$(".hero-wrap-text-slider-holder a.prev-slide").on("click", function() {
$(this).closest(".hero-wrap-text-slider-holder").find(sync2).trigger("prev.owl.carousel");
return false;
});
How can I add something like an OR Operator to wait three seconds before triggering the next slide?
I guess this is some sort of Boostrap Carousel deviant if that helps
if this is the wrong place to ask, since this is a python place, please just ignore the above
correct me if im wrong but isn't that jquery?
guys, quick question
my image is getting stretched
how to fix it
i tried width 100% and height auto but it's not working
Can I see your code @wild thunder
yes
Cool dm me
NP, i'll send it here
.card-profile-img {
width: 100%;
height: 100%;
margin: 10 auto;
border-radius: 50% 50% 50% 50%;
background-position: 50% 50%;
}
<img class="card-profile-img border-2px" src="{{url_for('static', filename='images/profile.jpg')}}">
i'm just testing some stuff, i have a game in mind i would enjoy to do, but i'm stuck with this
@lapis stratus
Alright try to change the background position to center
nothing happens, stills the same
background-size:cover;
yes
Just try to use border-radius:50%;
oh
i made one thing
my container is 19rem
i put this as 18rem x 18 rem
width and height
worked
Really nice keep working on that man!
Maybe your container is too large
No problem @wild thunder
anybody have experience with taking an existing Flask-via-gunicorn-on-Ubuntu app and integrating datadog for monitoring? is it as simple as preempting the entrypoint with ddtrace-run or is it preferable to ddtrace.patch_all()? or some third option i'm not considering?
I think the patchall is the way to go
I think they are working on some auto instrumentation though
10-4, thank you @mellow tide
can anyone tell me why i got '''path('store/', store_views.store.as_view(template_name='store/store.html'), name='store'),
AttributeError: 'function' object has no attribute 'as_view''''
the path is a views from the store app
Howdy. I'm extremely new to coding (my only experience is really making interactive stories in Twine! ) and I just played around with making some code for a "random character generator".
I'm trying to figure out a way to host my short code (all it does is spit out some info on this random character) on a place that isn't repl.it
Been trying to use Flask on Glitch and I'm a little out of my depth ๐ https://glitch.com/edit/#!/great-lavender-bonnet
I can't even figure out where to put my code - total newbie. If anyone was able to just give me the 10-second explanation of where to place the various dumb print commands, let me know.
What's a good choice of asynchronous web framework nowadays? Tornado seems to be the only option when I started my previous project, but there seems to have been a lot of movement in that area (with ASGI etc)
I have a very simple Flask app and I want to break out the long processing (to something like Celery) but I need to request to wait and return when the task is done
The most performant are Starlette and fastAPI, the most flask like is Quart, Aiohttp and Sanic are also two common ASGIs
Hello, if anyone knows flask, heres my code and the error.
from flask import flask
app = Flask(__name__)
@app.route("/")
def home():
return "Hello, welcome to the Lumber Legend's main page!"
if __name__ == "__main__":
app.run()
Traceback (most recent call last):
File "D:/codyk/Coding/.Aprojects/Website/website.py", line 1, in <module>
from flask import flask
ImportError: cannot import name 'flask' from 'flask' (D:\codyk\Coding\.Aprojects\PythonMain\venv\lib\site-packages\flask\__init__.py)
Process finished with exit code 1
Any help is appreciated
What
wow that did not do what i wanted it todo
from Flask import Flask?
I only want certain users to have access to the moderation app in my project. Would I do that with user groups and permissions?
can i ask, is it always lower cse first then capital?
thanks so much
if they follow Pep8 All classes should be CaseLikeThis any things like modules or files are lower case setc...
hi guys im just here asking why this get_or_create() won't work
it gives this error
games.models.gameMoves.DoesNotExist: gameMoves matching query does not exist.
and in the handling of that error gets this one TypeError: cannot convert dictionary update sequence element #0 to a sequence
what's the best hosting server for django Pythonanywhere or Google Cloud Platform and why ?
Because probably has better bandwidth etc
Because of how many requests they get
And because its google
But pythonanywhere might be better because its specifically for python
i have an html which loads and play an audio file in program directory... from the html page i use js recorder to record realtime and replace the audio file in program directory.....but when i play the audio file again i get the old audio from cache memmory, not the replaced one..i want my html page to update frequently when i play the audio.... (refreshing doesnt work, but closing and opening the tab again works..., but i wanna update the audio without refreshing nor closing the tab) any solutions?
window.reload()
Stick that in the Javascript and see if it works
It should be obvious that it reloads the page
And might fix it since it's being reloaded by the page and not the person
Idk tho
@thick inlet
so one of my apps looks like this:
`app
- static
-----css
-----icons
-----js
-templates
------base.html`
and it seems nothing under my static folder seems to load in my html after i {% load static %}
iam playing the audio in html, refreshing js doent work @balmy shard
What?
anyone knows flask?
anyone knows flask?
@serene agate yes
I know some Flask too
@classmethod
def create(cls, name, c_goal, user):
plan = cls.objects.create(name=name, c_goal=c_goal, user=user)
plan.save()
Is this syntax valid?
If I want to create a mailing list, what sort of database would I use?
It needs to contain a name and an email column, at the very least
MySQL? This isn't the job for SQLAlchemy right?
Im pretty sure you can use SQLAlchemy with MySQL @wind walrus
sqlalchemy is an ORM that works with many databases, it's not a database itself
MySQL being one of them
class SubscribedUser(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(20))
email = db.Column(db.String(120), unique=True, nullable=False)
could I just do this?
then to send an email I just SubscribedUser.query.all() and get their emails
yes
I made an AJAX post request to send the name/email data from the HTML forms to Python backend via JavaScript
and this is my Python to add the user to the mailing list
@main.route("/email_confirm", methods=['POST'])
def email_confirm():
email_data = request.form["email"]
name_data = request.form["name"]
user = SubscribedUser(name=name_data, email=email_data)
db.session.add(user)
db.session.commit()
send_confirmation_email(name=name_data, email=email_data)
return "<h1>" + email_data + "</h1>"
Here, what should I return? I'm not rendering a template or anything...
what is the use of SECRET_KEY in flask ?
I am new to djnago do you think it is goood to moove from djangooo to flutter
flutter is a framework which use dart similar to C# which is kinda low level language if your starting out(on your programer journey) I recommend useing django or flask
It's just not the same purpose
flutter can be used make website
Looking at the docs it uses canvas mostly, so no, not the same purpose
but i think only flutter for frontend
django is for backend
Looking at the docs it uses canvas mostly, so no, not the same purpose
@bleak bobcat flutter mostly use "widgets"
hi guys i needed some help... so like i was trying to make a django project and i had deleted the pip for django some time back now ive successfully reinstalled it however usually to start a django project we use execute django-admin startproject (name of file) however it seems to not work can anyone help?
im using vsc btw
@lusty kernel Are you using a Virtual Env?
no
ill give trhe error one sec
Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
this is the error @hollow linden
Use this
python C:\Users\blufl\AppData\Roaming\Python\Python38\Scripts\django-admin.py startproject (name of file)
oh ok
This is not a solution but I just wanna see if it will work ^^
but will the files be installed in the directory i want them in ?
I'll gave you the correct solution after ^^
You can add: "C:\Users\blufl\AppData\Roaming\Python\Python38\Scripts" to you Path environment on windows
ok cool
Like that you can use the command you mentioned before
You're welcome
welp new problem
python3 manage.py runserver
this is the command i used and the error i get is
C:\Program Files (x86)\Python38-32\python.exe: can't open file 'manage.py': [Errno 2] No such file or directory
is it another file location problem
?
Hmm let me clarify my words
If you wanna run a Script
You should be in the same folder where the script is
Or run python3 'the absolute Path of the script ' run server
That can be a little hard to understand ^^
Do you know the path where your script 'manage.py' is?
Can you copy paste the whole path of your project folder?
C:\Users\blufl\Desktop\dexbotx\pyshop/manage.py
Use python3 C:\Users\blufl\Desktop\dexbotx\pyshop\manage.py runserver
i legit just did that
but like nothing happened
tho lemme try it again
it shdu give me a webadress to go to right @hollow linden ?
I don't know what the script did ^^
That's another problem ^^
hmmmm
Your path changed now?
Do you know the name of your app?
its called pyshop
It's not recommanded but try to delete line number 1
#!/user ... python
Save and try to run the script
ok
If not use : django-admin runserver
does anybody know how to solve this error in djano Forbidden (CSRF token missing or incorrect.):
It's more like a warning, not and error ^^
first thing inside <form>
Anyone who know React, how to solve this:
Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
Check the render method of `Header`.
Here is header
import React from 'react';
import { Navbar } from 'react-bootstrap';
export class Header extends React.Component {
render() {
return (
<Navbar>
<Navbar.Header>
<Navbar.Brand>
<a href="/">My site</a>
</Navbar.Brand>
</Navbar.Header>
</Navbar>
);
}
}
and importing
import { Header } from '../Header/Header';
@wind walrus what does that do
@hollow linden how do i solve it
btw addin form.hdden tag stuff didnt work
I'm here, let me see ^^
@valid cypress You don't need you need quote inside the return? ^^
You don't think *
@modest scaffold That will help? https://stackoverflow.com/questions/12731305/django-csrf-token-missing-or-incorrect
@hollow linden that does not help
the strange thing is its working for my other forms
@hollow linden What quote?
<Navbar>
<Navbar.Header>
<Navbar.Brand>
<a href="/">My site</a>
</Navbar.Brand>
</Navbar.Header>
</Navbar>
");```
No, this is JSX syntax, so no quotes
@modest scaffold Strange
should i share more code
{% csrf_token %}
<button name="reset" value="True">Reset</button>
</form>``` here is the html
corresponding view ```def tictactoe(request):
newGame, created = liveGame.objects.get_or_create(id=0,gameId="yes")
movesModel, created2 = gameMoves.objects.get_or_create(game=newGame)
moves = list(movesModel.moves)
if "reset" in request.POST:
return render(request, 'tic-tac-toe.html', {"boardSetup":[0,1,2,3,4,5,6,7,8],"error":"hi there"})
else:
return render(request, 'tic-tac-toe.html', {"boardSetup":[0,1,2,3,4,5,6,7,8],"error":"hi there"})```
@valid cypress Try to add default after export export default class ...
Still not working
@modest scaffold Something is missing! are you using Jinja?
@modest scaffold is you website https?
@valid cypress https://stackoverflow.com/questions/31852933/why-es6-react-component-works-only-with-export-default
That will help
@hollow linden its not https i dont think so anyway
@hollow linden what is missing
I don't know ^^
no django
okay Django
missing crsf token for some reason
even though i have it in the html and im returning a render object
You seem to need to get the template object then pass it the context first then the request
This is still not working when I changed this to default
@quick cargo cant i use a render() function though
In the corresponding view functions, ensure that RequestContext is used to render the response so that {% csrf_token %} will work properly. If youโre using the render() function, generic views, or contrib apps, you are covered already since these all use RequestContext.```
nvm its working now
i think it was somthing to do with broswer cache
All fine ^^
in django can you have variables inside template tags like this {% if apples|slice:"{{x}}" %} where x would be a variable
Yes you can but you'd remove the " and {{}}. However don't put logic inside templates
anyone know how to run a java program using subprocess in django?
HEy guys
I have an issue
@app.route("/") #Homepage
@app.route("/home")
def home():
return render_template("home.html", posts=posts) #Use render_template to return html files containing the code for the pages.
@app.route("/about") #About Page.
def about():
return render_template("about.html", title='About')
@app.route("/register", methods=['GET', 'POST'])
def register():
form = RegistrationForm()
if form.validate_on_submit():
flash(f'Account created for {form.username.data}!', 'success')
return redirect(url_for('home'))
return render_template('register.html', title='Register', form=form)
@app.route("/login")
def login():
form = LoginForm()
return render_template('login.html', title='Login', form=form)
if __name__ == "__main__": #__name__ is __main__ if we run this directly.
app.run(debug=True) ```
so this is a small snippet of code
but when it should redirect it doesn't it just reloads the page
redirections do not always work on all browsers afaik
so you have the fallback link
if the redirection does not redirect, the user can still click the link
too many values to unpack (expected 2)
I get a value error and it points to my ChoiceFields
gender = forms.ChoiceField(choices=('male', 'female'), label='Gender')
This is one of my choice fields
I have an Instagram account and I may change its username in the future
But I want to link it to my websites
Is it possible to get a link to the account with the account ID or something instead of the username so that I wonโt have to go change the code for my website every time I change my username?
But wouldnโt that still need to have a link that points somewhere?
And in the link will be the account username so...
The best I could do would be to have a clickable instagram logo
but I am still new to this web dev stuff so yeah.
Yeah, I canโt find a better solution, thanks for your time
Oh no worries sorry for not being able to help more.
how do i only slice one element from a list in django templates
class SignUpForm(FlaskForm):
field1 = StringField('Field1:', validators=[DataRequired()])
field2 = StringField('Field2:', validators=[DataRequired(), EqualTo(field1, message='Fields not equal')])
submit = SubmitField()
@app.route('/signup', methods=['GET', 'POST'])
def signup():
form1 = SignUpForm()
return render_template('signup.html', form=form1)```
Would anybody know as to why EqualTo() validator is not working (not showing the message)?
ive got this html form with text input boxes
this is what the form looks like
lets say i want to retrieve the value "hello"
shouldnt request.form['MB_IDLE_TIME'] get it for me?
Try request.form.get(x)
field1 = StringField('Field1:', validators=[InputRequired(), EqualTo('field2', message='Fields not equal')])
field2 = StringField('field2')
submit = SubmitField()
@app.route('/signup', methods=['GET', 'POST'])
def signup():
form1 = SignUpForm()
return render_template('signup.html', form=form1)```
None of the validators except InputRequired() give me any feedback. Even though both fields are not equal, the message isn't showing.
{{ form.hidden_tag() }}
{{ form.field1.label }}
{{ form.field1() }}
{{ form.field2.label }}
{{ form.field2() }}
{{ form.submit() }}
</form>```
This is the form
Flask btw
which one is easier to learn
django or flask?
Flask
Does anyone know if thereโs a way to import a variable defined outside of the webpage function into the html template in flask?
With the delimiter {{ }} or am I misunderstanding
So Iโm making a function that web scrapes and grabs a value, I want to show that value on the flask webpage.
@native tide doesnโt using the delimiter {{}} require the variable to be defined in the page function
you could assing the scaped value to a global variable and then use that variable in your page function @void leaf
but now you are taking the risk of blocking on a scrape
Thatโs what I did. The scraped value is x . Do I need to put x in the page function arguments
@strong oriole flask by a long shot lol ... but that is because django includes EVERYTHING you need. Flask you have to lego it together
Thatโs what I did. The scraped value is x . Do I need to put x in the page function arguments
@void leaf either as an argument, or defined as a global variable
wdym lego it together
Thanks Iโll let you know if it works @mellow tide
puzzle-piece it, you have to find and build functionality outside of the original intent of flask
Sorry bro I'm not that experienced to answer
flask is great for hosting sites, but doesn't include user auth, a database, it's not really that great for APIs unless you use another plugin
basically, you have to find the plugins you want with flask, whereas, Django is "batteries included" and they all exist, but you have to learn all the parts
it's ultimately more work to use flask, but you get to break it up a bit
Guys if you have a DataRequired() validator, if the form is empty, it will show you a box saying 'Field empty' right?
Is that the same for other validators such as Length()?
i would assume, but without looking at it, i don't know lol
soo django is more noob friendly as it has everything but flask is just some bits i need to use to create something big did i get you guys right?
I think flask is more user friendly but there are plugins for stuff such as authenticating users instead of it being included in django
so final decision flask or django is easier to learn while being good enough to do something useful
xD
flask is more friendly for beginners
Yea I'm a beginner I'm having a good time with flask
Except for the validators :(( still unsolved
Does anyone here familiar with pythonanywhere please
i've used it in a pinch, why do you ask @late gale
if i have a flask application that is beginning to accrue a lot of routes/the main application file is getting pretty long, is splitting it into blueprints a decent improvement?
yeah, that is what blueprints are for ๐คท thats typically how i do it anyway
granted, i don't do much with Flask anymore
awesome, thanks!
@mellow tide I have made translation in django like i made a button to change from english to arabic and vice versa it works very well on local host but it doesn't work on pythonanywhere is there any problem how to solve this
oy, yeah i18n is not my strongest area lol
=,=
i have added the local files on the url of pythonanywhere but still not working
what shall i do then
i added all the urls
/locale/
/ar/
/LC_MESSAGES/
and nothing has worked
does anyone know a solution for this i searched alot on google but seem most people doesn't use localization /django translation
please i was trying to search for a fix since july
hey so rn i have this view where i post a message in a forum:
class NewMessage(LoginRequiredMixin, CreateView):
model = Message
fields = ['content']
def form_valid(self, form):
form.instance.author = self.request.user
thread_path = self.request.path.replace('/new', '')
form.instance.thread = Thread.objects.filter(pk=int(thread_path[thread_path.rfind('/') + 1:])).first()
return super().form_valid(form)
```and i have the middle two lines in `form_valid` to get the current forum
the thing is, would there be a more efficient way to do this? (ping plz)
If I give some flask code can you guys try to run it and see if it works? Because I'm getting no errors the code matches documentation and it's not working for me
you can send the code
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, PasswordField
from wtforms.validators import DataRequired, EqualTo, Length, InputRequired
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SECRET_KEY'] = 'CSRF_PROTECTION'
class SignUpForm(FlaskForm):
username = StringField('Username:', validators=[DataRequired()])
password = PasswordField('Password:', validators=[InputRequired(), EqualTo('password1', message='Passwords do not match')])
password1 = PasswordField('Confirm Password:', validators=[InputRequired(), EqualTo('password2', message='Passwords do not match')])
submit = SubmitField()
@app.route('/')
def hello_world():
return 'Hello World!'
@app.route('/signup', methods=['POST','GET'])
def signup():
form = SignUpForm()
return render_template('signup.html', form=form)
if __name__ == '__main__':
app.run()```
This is for first app, app.py
This is the form
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sign Up</title>
</head>
<form method="post">
{{ form.username.label }}
{{ form.username() }}
{{ form.password.label }}
{{ form.password() }}
{{ form.password1.label }}
{{ form.password1() }}
{{ form.submit() }}
</form>
</body>
</html>```
signup.html
So, the issue I am having is that EqualTo() is not showing errors when the password fields do not match. Can you possibly see if it is showing you anything, if the password fields are different?
Thanks so much btw
Oh, this is on /signup page btw
sqlite3.DatabaseError: file is not a database, what the hell does this mean? It is for a fact a database ๐
fun fact is that identical files work fine on another pc...
also if I run the function directly, not through flask it updates the values as it should
guys, what is the best way to schedule tasks in flask?
I've had success with flask crontab in the past https://github.com/frostming/flask-crontab
@cold anchor what are the disadvantages of using crontab?
the most granular time is 1 minute
you need to make sure the user running the command has permissions to do so
and you're limited to the health of the server it runs on
I have a question involving security with Django. A project I'm working on with it is going to be using React components in some places, for instance a private message window commonly seen in a lot of forums. For the inbox for example, the component will simply make an API call to the server of the user's ID, and get back a paginated list of messages. The necessary data for JS is fed in through the template as context, simple enough right?
This is the part that loses me though... can't this functionality be easily manipulated, or if not, what is preventing it? For example, someone locally changing their html data, running it, and then getting someone else's inbox messages (provided they have another person's primary key), or doing the same with a POST request, changing data that isn't theirs. Any nudge in the right direction would be much appreciated.
only give load the messages of the currently authenticated user, then the security will be as good as your authentication system
I want to run a background task where it refreshes the state of membership for my members, I have around 1300 members connected through Stripe
I need a way to refresh their data every 12 hours
and I am thinking of using crontab
Instead of installing something like celery
If I already use flask-SQLAlchemy for my databases should I try making a nested comment thread system with SQLAlchemy too?
Or would Postgres or MySQL be better
@rustic pebble celery is a pain and overpowered for what you need. Crontab is the right answer here. You can either set it up locally to run on your server, or set up an endpoint through flask/django and have a service like setcronjob senda request to that endpoint when you specify.
Yup