#web-development
2 messages · Page 209 of 1
it still says
incorrect
the admin log in?
@app.route('/admin_login',methods=['GET','POST'])
def admin_login():
msg = ''
if request.method == 'POST' and 'username' in request.form and 'password' in request.form:
username1 = request.form['username']
print(username1)
password1 = request.form['password']
print(password1)
cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute("SELECT * FROM accounts WHERE username = %s AND password = %s AND adm = 'yes'", (username1, password1,))
account2 = cursor.fetchone()
print(account2)
if account2:
session['loggedin2'] = True
session['id'] = account2['id']
session['username'] = account2['username']
return redirect(url_for('adminhome'))
else:
msg = 'Incorrect username/password!'
return render_template('admin_login.html', msg=msg)
nope
aaaaaaaaaa
whats wrong with the template file now
wdym between?
its showing the incorrect pass thing
yea
Hey i need help ;m facing issues in handling img file in django by request.files idk why
@login_required
def course_upload(request):
if request.method == 'POST':
course_title = request.POST.get('course_title')
course_desc = request.POST.get('course_desc')
course_subj = request.POST.get('course_subj')
course_thumbnail = request.FILES.get('course_thumbnail')
course_author = request.user
print(course_desc,course_subj,course_thumbnail)
entry=Course(course_title=course_title,course_desc=course_desc,course_subj=course_subj,course_thumbnail=course_thumbnail,course_author=course_author)
entry.save()
messages.success('Course Uploaded!')
return HttpResponseRedirect(reverse('home:index'))
return render(request,'index/course-upload.html')```
so the thing is when im filling the form its showing this error
n it's not adding default value but when im adding a post through admin panel its adding the default
n when im trying to upload thumbnail then too it isnt storing to db
its showing same error
<div class="input-box file-box">
<span class="details">Thumbnail</span>
<div class="dragarea">
<header class="header">Drag & Drop To Upload Thumbnail</header>
<span>OR</span>
<a class="browse" onclick="clike()" style="border: 1px solid #11101d;border-radius: 4px;padding:6px;cursor: pointer;">Browse</a>
<input type="file" name="course_thumbnail" id="course_thumbnail" hidden>
</div>
</div>```
class Course(models.Model):
course_title=models.CharField(max_length=90,unique=True,null=False,blank=False)
course_desc=models.TextField(null=False,blank=False)
course_subj=models.CharField(max_length=20,choices=course_subject_choices,blank=False,null=False)
course_thumbnail=models.ImageField(upload_to='Course_Thumbnail',default='default_course.jpeg',validators=[validate_image_file_extension])
course_author=models.ForeignKey(User,on_delete=models.CASCADE)
course_published_on=models.DateTimeField(auto_now_add=True)
thx in advance
any help would be appreciated.
anyone goold with django
trying to figure out how to do an sqlalchemy query in my flask view when I open a bootstrap modal
what?
why doesn't this work?
if reaction.emoji == ['8️⃣', "7️⃣", "6️⃣", "5️⃣", "4️⃣", "3️⃣", "2️⃣", "1️⃣", "0️⃣"]:
fuck
wrong channel
i have read it but some things are unclear
I want to click a button in my html which then executes a function in my flask view
>>> class User:
... def __init__(self, name, age):
... self.name = name
... self.age = age
>>> print(User("ROY", 1))
<__main__.User object at 0x7fbf62289460>
>>> class User:
... def __init__(self, name, age):
... self.name = name
... self.age = age
... def __str__(self):
... return f"User - {self.name} - {self.age}"
>>> print(User("ROY", 1))
User - ROY - 1
And similarly, the string representation will be used in the admin dashboard
Then your button needs to post data to an appropriate route. What have you done so far?
does the result take you to a new page?
yh i know
so how do i print manytomany
relationship>
no it opens a modal that I want to fill with the results of the button click
k, then just maybe use a post route as suggested above
Well after adding the relationship, makemigrations and migrate (because it uses the association table), you should then see that table in the admin dashboard
i did
what was the makemigration output
also im getting this error when
it seems i cant add whats in the basket
to the service
Are forms the only way to do post requests? or would I need some js?
You don't really need JS to post. There are lots of tutorials like this that may help with how to make the route. https://pythonbasics.org/flask-sqlalchemy/
@thorn lily
no, but from your statement, you want to send data to your backend and the trigger a modal
considering flask produces static content, i believe a post would be the best way to go on about this
Ok so I would wrap the link in a form like this
<form action="" method="post" id='myForm'>
<input type='hidden' value={{{row.value}} />
<a href="#" onclick="this.parentNode.submit();"> List item 1</a>
</form>
and then get the form value
@app.route("/", methods=['GET', 'POST'])
def page():
if request.method == 'POST':
data = get_data_for_modal(request.form['value']
but then how do i pass that data back to the template? @thorn igloo
the post route will generate the template with your data
so just add something like modal_data=data to render template
i guess
Using Flask, SQLAlchemy & Marshmallow.
When i generate a DateTime it puts it in this format:
2000-12-28T20:50:11
However when I try to update an entry with this for example:
PUT http://127.0.0.1:5000/weathers/update-date
Content-Type: application/json
{
"id" : "1",
"date" : "2000-12-28T20:50:11"
}
It doesnt work. Printing exceptions shows:
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type type is not JSON serializable
127.0.0.1 - - [28/Dec/2021 21:11:33] "PUT /weathers/update-date HTTP/1.1" 500 -****
any suggestions ?
What's the code that's generating the error? I suspect the problem is with the response it's trying to send back to your browser
just a simple print:
@app.put("/weathers/update-date") # MODIFY DATE
def weather_update_date_json():
json_data = request.get_json()
weather = Weather.query.filter_by(id=json_data['id']).first()
if weather is None:
return {"Message": "Entity with id doesnt exist"}
try:
Weather.query.filter_by(id=json_data['id']).update(
dict(
date=json_data['date']
)
)
db.session.commit()
except Exception:
print(Exception) ### <<<<<<<<
return {"Message": "Error fulfilling update request"}
return {"Message": "Record updated in DB"}
ypp
TypeError at /customer/book
Field 'id' expected a number but got ['70wPdi0O', '3BgjwlbE'].
Request Method: POST
Request URL: http://127.0.0.1:8000/customer/book
Django Version: 4.0
Exception Type: TypeError
Exception Value:
Field 'id' expected a number but got ['70wPdi0O', '3BgjwlbE'].
Exception Location: /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/db/models/fields/init.py, line 1824, in get_prep_value
Python Executable: /usr/local/bin/python3
Python Version: 3.9.6
Python Path:
['/Users/arnantaroy/Documents/GitHub/afterglow_website',
'/Library/Frameworks/Python.framework/Versions/3.9/lib/python39.zip',
'/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9',
'/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/lib-dynload',
'/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages']
Server time:
any suggestion?
I'm a little bit confused on what Serializers and Viewsets do?
me or Roy?
Oh I mean just in general
serializes allow you to put variables/json into http packages as far as im aware
no idea when it comes to viewsets
i know nothing when it comes to django
plus you aint included the package youre trying to send
if you read the log its expecting an ID and its not getting it. So i would start there
and youre trying to store it in a db?
seems kinda stupid to me, just assign an ID as primary key so it works
show the package you are trying to post
that error is from booking.service.add(request.session['basket']
@south stump
@whole crow
@upper goblet Im guessing this is a better place for django support
Ik
It’s not working out for me
I can see that lol
okay but why would you want a randomly generated primary key
that means that it could select something that already exists, which breaks 3NF
It’s a booking uuid
I tried reaching out for help in the #python channel before it went to hell on freenode and nothing but trolls there. I switched to flask and things worked so much better
That’s not the problem here though is it?
but its not a uuid its random, like i said. So it could pick the same combination
no but its a problem you could encounter in future
Yh but for now I wanna get this shit ready
which leads back to my initial point, if you just use a standard integer it will get rid of both issues
The issue here is that I don’t have Id for any of that models but it creates a model field on the migrations folder
Which is very annoying
Idk how to fix this shot
show the method for handling the post request @upper goblet
I did ?
where
Wdym show the method
Isn’t this it
oh okay my bad yea, have you tried breakpoints?
Breakpoints? What does that mean
its where you can pause code line by line, view variable states and continue/skip code
Learn how to use the Python Debugger using the breakpoint() function in this Tutorial.
🪁 Code faster with Kite: https://www.kite.com/get-kite/?utm_medium=referral&utm_source=youtube&utm_campaign=pythonengineer&utm_content=description-only *
✅ Write cleaner code with Sourcery: http...
Yh I have tried that the issue is 100% in request.session[‘basket’] I jus don’t understand django
When I clearly stated that the field is going to be manytomany
should the service not automatically be added?
How do I do that
It should be
Hey, I'm new to creating login sessions. And I wanted to try to add it to my site which uses FastAPI
I've tried https://pypi.org/project/fastapi-discord
and I got to the point where I have a refresh and an access token, but idk how to go from there
is it OIDC?
then it isn't 😉

well I got the part where I get the token
what I'm stuck on is getting the userinfo from it and creating a session so I dont need to add url params with the token in it
the user info will be there, only if you put it there 😄
are you using jwt?
also no idea what that is
how are you trying to get the info from the token?
how is the token generated?
thats what I'm asking, how do I get the info 
fastapi-discord has a token, refresh_token = await discord.get_access_token(code) where it takes the code that is returned by the discord oauth url to create an access and refresh token
there are several ways - 1) use token to access some endpoint and get the info from there, 2) use jwt to store info inside and then get it from there, when you receive it
ok, so you use token to access another endpoint, where the info is stored. When it expires, then use refresh_token to get a new token
you need to check the expiration time of the token and refresh it, when it expires
yeah but that doesnt answer my question yet 
which one?
If multiple users are logged in, how do I know which token to grab?
every user should have its own stored in the db or in cache
and you update them accordingly
generally, there are modules made for such things, as far as I remember, such that you do not need to do it manually
same question
may i know the solution
In the end I figured to put the token in the request.session, that's different per user so just request.session["token"] = "..."
But for better security, you should also hash it
hey im new in this Community im enrolling into Diploma in computer science i wanna know what should i major in and can u all show a path to teach me to like free website to do pythan
What's better for Flask/Blog app?
Having each class like Post, Pages etc and its functions in separate .py files or in one like (dashboard.py)?
i have started learning react as a beginner...when i saw the documentation of react there its written learn by practical tutorial and other learn by main concepts..so which one should i prefer ?
You all know while Downloading Anime and watching online You see a lots of advertisement and hundreds of redirects adult pop up messages by website send to you Sad for user privacy . 😭
But i created a web scraping model that' help anime lovers to watch download anime without seeing ads and all shity things and no privacy issues ...
Website Link - https://asteroidfire.pythonanywhere.com/
Repository : https://gitlab.com/Aakash-Yadav/flask-anime-downloading-web-app
pog
still waiting....
Does anyone have a solution to fix my problem, git push -u origin main takes too long
don't put large files into git. git is not meant for big files
Code please
My website is receiving get requests for css file but why is it not responding?
what do you mean?
It got fixed by itself, maybe its the server's problem, but the moment I visit my website its not loading because the server is not sending me the css
Hello, is it possible to do Authentication Token on another Backend API other than Django and send it to Django to count it as authorized?
Hey, is it better to have functions of one category (for example related to posts) in separate files like: posts.py, pages.py etc or put everything in one file like functions.py?
Do what you want basically. I prefer one file for all routes but I've never had a ton.
hello
when i run the html file normally i get this
and when i run it in flask i get this
i need help
with this
like images wont load
and then the layout like the button is in wrong place
and text is unreadable
i have looked on google and found nothing
looks like it doesn't find the css file or the newest version of it
guys I have a problem that I don't know what to put into google to find the answer
I want the customers on my website to sign up for a service, and when they sign up (submit a form) that means they signed the contract
which would be of course explained in detail in terms of service
but since I can do with the form data anything I want, which means I can fabricate any form easily
how do I prove that the user actually submitted it? That he consented to data processing and to terms of service?
using django if that makes any difference
guys could i get some consultation? im planning to chose my db for my project. i have a flask backend and a js frontend. should i chose a js based db engine or use the flask backend for db. there are alot of databases for js and seeing how i have a js frontend, should i use js databases like graphql or other popular dbs. im also way more profecient in sql based dbs but i've heard no sql is faster. also would offsetting the db operations to the backend be more beneficial?
separate files are easier to debug than one big file. keep that in mind
there's is no such thing as a js based db engine
and you cannot really interact with a database directly through a frontend
yeah nah i've learnt what graph"ql" is
it's an alternative to the REST API structure
it's not a JavaScript specific thing
an api is really just a way to interact with a backend
the backend handles the interactions to the database
you still cannot directly interact with a database through frontend only
sorry, if this is the wrong channel to ask this. does anyone know of a discord server that's about p2p networking, ipfs, etc.?
i know r/Cisco and r/networking, they may have a discord server
url(r'^swagger/$', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
quick question. I'm working on Django project and trying to figure out this particular line
How would I actually access the swagger UI o.O?
Hello i have a question
If there is somene free go prv plz
How I can inclue the h1 in the photo
Sometting like that
It didn't work
Any drag and drop HTML generators out there? Kind of like PAGE for tkinter would be what I'm looking for.
Wordpress?
in my country also popular https://tilda.cc/, basically wordpress at web GUI level as SaaS with ability to extract HTML result
Ya
Good Morning/Afternoon/Evening/Night!
I have an issue with GIT.
I've added one file __init__.py to .gitignore it after I've pushed the dummy config to GIT but if I'll do git add . __init__.py is still being added there.
How can I exclude it once for good?
trying to make a react api call. i have a link pointing to the desired url...
but my console looks like its going elswhere and obv giving an error
i have a feeling its something to do with my axios baseUrl , but im unsure on how to properly manage it.
i cant change the baseurl in axios, whats the proper way of defining a new end point
its the base url so /api/ "another endpoint"/ "id"
what seems to be happening is the "another endpoint" is just being ignored
this is my axios.js file
Hello everyone, is it a way to create a rpg in a browser with python? I heard about pyjs
Try #game-development if you haven't
Hey - can anyone answer that question: https://stackoverflow.com/questions/70518094/web-automation-save-data-in-database
greetz
Sam8 — Today at 1:54 PM
who has here implented jwt authentaction in their djano project ?
walked nearby, remembered that implemented jwt auth in django before, but saw no questions and walked away
why my flask app dos not have files that i put the with (imgs js scripts....) in the dev tools sources ?
someone ?
????
Hello guys, I have a problem (that's why I'm here). I'm working on a django website hosted by DigitalOcean, and I bought a domain name through 1&1, and both are connected (I also have an email address with my domain name). But when I send email using python using the host smtp ionos, gmail is telling me that the email is unsecured and it could be spam. The support at ionos told me on DigitalOcean to add a SFP to my domain, but it didn't changed anything
Do you guys have an idea ?
It is being picked up by gmail spam filters. This can happen to anyone. You can start by marking the email as not spam which slowly overtime should help resolve it. Or you can look into why it’s getting caught by spam filters. I use Mailtrap.io for seeing spam score of an email.
Ok but I don't know why when I hover the profile picture with the red "?" I am notified about the email address "do-not-reply@domain.com" and the name is set to Undefined
That could be from your application. Generally when you send the email it should allow you to customise the name. Maybe yours was null at the time.
This is my config on django settings
And I use EmailMessage from django.core.mail to send mail in views.py
I don’t use django, but maybe this helps you https://stackoverflow.com/questions/2111452/giving-email-account-a-name-when-sending-emails-with-django-through-google-apps
I am sending emails to users using Django through Google Apps.
When the user receives emails sent from the Django app, they are from:
do_not_reply@domain.com
when looking at all emails in the inb...
what 304 code means ?
I think it is redirect from http to https usually
or not
or it it is response to caching
that file was not modified and not needed being reloaded
oh right. 301 is redirect from http to https 😉
304 is probably caching then
The HTTP 304 Not Modified client redirection response
code indicates that there is no need to retransmit the requested resources. It is an
implicit redirection to a cached resource. This happens when the request method is
safe, like a GET or a HEAD request,
or when the request is conditional and uses a If-None-Match or a
If-Modified-Si...
Basically, it says: "here's a link to a resource. but it didn't change since you last looked at it"
hiya
Hi
trying to understand this
@app.route("/ajaxfile",methods=["POST","GET"])
def ajaxfile():
cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
if request.method == 'POST':
userid = request.form['userid']
print(userid)
cur.execute("SELECT * FROM employee WHERE id = %s", [userid])
employeelist = cur.fetchall()
return jsonify({'htmlresponse': render_template('response.html',employeelist=employeelist)})
$.ajax({
url: '/ajaxfile',
type: 'post',
data: {userid: userid},
success: function(data){
$('.modal-body').html(data);
$('.modal-body').append(data.htmlresponse);
$('#empModal').modal('show');
}
data.htmlresponse...data here is the response from the flask view right? and it's appending the 'htmlresponse' attribute. What was the point of the line above > $('.modal-body').html(data);
That is if the ajax call was a success
From your python code you can return a success or error
oh sorry I meant the line $('.modal-body').html(data); not above it
also data: {userid: userid} this is passed to the flask view on post correct and is accessed through request.form right?
It just replaces some html on the page with another.
So you python will return some html, and when your JS request gets a successful response the piece of code $('.modal-body').html(data); will set that elements content to what HTML python returned you.
$('.modal-body') is a jquery class selector so it will get the element with that class.
Ahh, I get that it's just the word data is throwing me off. because data is set to {userid: userid} but then after the success it's accessing data.htmlresponse?
Ah i see. Yeah but they are different. I guess you could name the data param of the function differently if it makes it easier for you. But success: function(data) is a callback where data contains your response from python.
Also i think success was deprecated in one of the versions. Was replaced with done() or something like that.
But should still work, as all my code uses success
Ok ok lol, figured as much but just wanted to make sure thanks.
@native tide tried to do the thing and got this error "POST /process_status HTTP/1.1" 400 -
from clicking this button
<td><span class="edit_btn"><a data-bs-toggle="modal" data-bs-target="#optionModal" id="option_link" data-id="{{ vehicle.T_Number }}">Buttton</td>
$(document).ready(function(){
});
$('#option_link').click(function(){
var t_num = $(this).attr("data-id");
$.ajax({
url: '/process_status',
type: 'POST',
data: {T_Number: t_num},
success: function(data){
$('.modal-body-update').html(data);
$('.modal-body-update').append(data.htmlresponse);
}
});
});
@app.route("/process_status", methods=("GET", "POST"), strict_slashes=False)
def process_status():
if request.method == 'POST':
T_Number = request.form['T_Number']
print(T_Number)
status = Status.query.filter_by(T_Number=T_Number).first()
garage_form = status_form(obj=status)
return jsonify({'htmlresponse': render_template('garage_response.html', garage_form=garage_form)}) ```
might be some crsf token thing actually
400 is when you send data invalid
csrf would generally be 419, but yes you should also send the csrf with the ajax.
This is how i do it normally:
$("#example-form").submit(function(e){
e.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type : 'POST',
url : '/some-url',
data:{
foo: 'foo',
bar: 'bar',
},
}).done(function (data) {
// on success
}).fail(function () {
// on error
});
});
Ahh ok thanks I'll try this
Hi everyone, When i'm send post request with raw data. I'm getting this error "detail": "JSON parse error - Expecting value: line 4 column 24 (char 95)"
But when i use HTML form its working
drf
raw data request { "Company_name": "Facebook", "Position": "Software", "Employment_type": Full-time, "Primary_Skills": VA/PT, "Skills_tag": "Nmap", "Location": "Worldwide", "available": true, "Min_salary": 20000, "max_salary": 100000, "Description": "This is a description.", "company_logo": null, "url": "https://www.facebook.com", "email": "test@facebook.com", "show_logo": true, "Highlight": false, "sticky_day": false, "sticky_week": false, "sticky_month": true }
Hey @strange charm!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
yo anyone know
how to add foreign key in html
??
so it gets the data from model
@hasty stirrup Please don't try to ping @everyone or @here. Your message has been removed. If you believe this was a mistake, please let staff know!
Can code on the subdomain have access to the main domain's Session?
Hey Memebers 👋
Anyone tried connecting LAMPP in Django in Ubuntu? ❤️
Can someone here help me to find and give me the API of an site in a dump file? Would that be possible? I can also hand out my user credentials if needed.
explain what you're trying to do?
Depends on the API, but if the database is private you would probably be breaking #rules (no. 5)
i get this error when i deploy my api in heroku
at=info code=H82 desc="Free app running time quota exhausted" method=GET path="/favicon.ico" host=covid19data-apii.herokuapp.com request_id=71862c4b-cf84-465e-ac39-bc7afb8b6d8e fwd="59.94.193.113" dyno= connect= service= status=503 bytes= protocol=https
how can i fix?
Its not private, its actually open to see what it consists of in the library, I would just like to have the API of that site if someone can give it to me in a dumpfile. As said, I can give login information
if needed
hello how do i get the image from a webpage via python
like for example in discord.com the image that pops up in the embed well i want its url
https://discord.com/
can someone help
i wanna do this in python
Hi, any idea how to redirect using headers in flask using flask_jwt_extended?
I am trying to redirect from login page to dashboard using jwt but I am unable to redirect where as I can return json but not as a web page .
hello, Where can i deploy/host my fastapi server for free other then heroku cause i finished my free dyno.
https://pythonanywhere.com/ gives 1 free instance
Host, run, and code Python in the cloud: PythonAnywhere
Do we get a domain?
to host the api
do you mean webscraping? then you need beautifulsoup
you can buy a domain separately, I suppose
I only use it for testing
they give you some domain, but not the one you want
is there free
it is something like yourusername.pythonanywhere.com
i think so
for real web project you need to pay
but it is not much - 15 euros per year for domain, 5 euros per month for the VPS
anyway i found it out ty
is it possible to just get the domain only
cause i have a vps
of course
not for free
you can try to find some discounts - sometimes they sell it for 1 euro for the first year
the error occur in line 4 try this "VA/PA" after "Primary_Skills":
Hello
in HTML is there a difference between
<input type="submit" value="Save>
and
<button type="submit">Save</button>
when dealing with forms?
because i was moving along with this django book and it used <input> in forms but started using <button> when it came to the authentication forms (sign up login..)
that's weird cuz i didnt use any java in that project
wut
sorry i thought you want to know the difference between <input type="submit" > and <input type="button" >
!codeblock
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
thanks
but i believe that they don't use button bcz it will cause some problem
In Django, how do i get grab the latest object by date and not date created?
<ModelName>.objects.order_by(<date_field>).first()
Thank you so much let me try that
What do i put in place of <date_field>. sorry im a biginner
You requested that you want to grab the latest object by date right? The <date_field> refers to the column name in database which contains that date
allBlogs = models.Blogs.objects.all()
allAuthor = models.Author.objects.all()
oneBlog = models.Blogs.objects.get(id=id)
AuthorsAllBlogs = models.Author.objects.get(id=id).blogs.all()
allBlogsserializers = serializers.Blogserializer(allBlogs,many=True)
oneBlogserializers = serializers.Blogserializer(oneBlog,many=False)
allAuthorserializer = serializers.Authorserializer(allAuthor,many=True)
Blogsserializers = serializers.Blogserializer(AuthorsAllBlogs,many=True)
data = {
"allBlogsserializers":allBlogsserializers.data,
"oneBlogserializers":oneBlogserializers.data,
"oneBlog'sAuthor": oneBlogserializers.data["author_id"],
"allAuthorserializer":allAuthorserializer.data,
"Blogsserializers":Blogsserializers.data
}
return Response(data)
Any better apprpach?
its just for learning not for production....
Hello
I got a domain in Freenom
and i was wandering how i can host my website to the domain
on my local machine
possible but not recommended
it's not recommended to host a website on your machine
yes i know
i have vps
This is what i did but it still gets the latest object in terms of date created instead of the date associated with the data
but i am not sure how to change local host to the domain name
so i am testing it out on my local machine
how can i do it?
for some reason when I append it appends twice? or rather it takes whatever was previously appended and appends it again
//this script gets the data-id from a button sends to the flask view and then appends the response to the modal body
$(document).ready(function() {
$('#option_link').click(function(){
var id = $(this).attr("data-id");
$.ajax({
data : {
ID : id,
},
type : 'POST',
url : '/process'
})
.done(function(data) {
$('.modal-body-update').append(data.htmlresponse);
}
});
event.preventDefault();
});
});
@app.route('/process', methods=['POST'])
def process():
x = request.form['ID']
return jsonify({'htmlresponse': render_template('replace.html', x=x)})
//this is the replace.html
<div class="modal-body-update">
{{ x }}
</div>
don't think that's possible unless you actually host it
hrm
How can i do it on my vps then?
I want it to grab the data from december 29, but since december 28 is the latest object, it grabs data from the latter instead.
I'm not familiar with VPSs, you're probably gonna have to look up how to point your domain to your vps
try this CovidData.objects.order_by('Date')[1]
is the data type of the first column, a Date Type? Or is it String?
Add a '-' before the order_by('Date') . I missed out this while looking at the comment earlier
Anyone?
your provider will not allow this, afaik
hmm
you mixed up all the staff in one file - it won't work
It did work
hm, ok
How can i do it in a vps?
vps on your local machine?
I usually, use docker for this
if you want to automate the deployment, there are tools like jenkins, travisci etc., which can do this from your git repo
Thank you so much. I tried order_by('-Date') and it worked.
Thanks for the idea man. I used oder_by('-Date')[0] instead tho
oh sorry i forgot the Hyphen
will they host it as well?
so i can't do it from vps?
no, these are tools for your git repo
which can help you deploy new versions, etc.
is it possible to do a custom login view using the built in obtain token just to edit the Response in django rest framework token authentication?
can't seem to figure out why im getting this error
"POST /process HTTP/1.1" 400 -
{% extends 'base.html' %}
{% block content %}
<a href ="" id="test_link" data-id="2">test</a>
<script type='text/javascript'>
$(document).ready(function(){
$('#test_link').click(function(){
var id = $(this).attr("data-id");
$.ajax({
data : {
id : id
},
type : 'POST',
url : '/process'
})
.done(function(data) {
if (data.error) {
alert('I hate tomatoes.');
}
else {
alert('I love tomatoes.');
}
});
event.preventDefault();
});
});
</script>
{% endblock %}
@app.route("/process", methods=("GET", "POST"), strict_slashes=False)
def process():
if request.method == 'POST':
print("pls work")
return jsonify({'htmlresponse': 'lol'})
any one intrested in partnership?? i am looking for app idea or opensource project to work on
oh, request must be an argument of the process function, right?
ajax passes data through request so if i wanted to access data : {id : id}, id say request.form['id']
where are you getting the request from?
ajax creates it I believe 🤷♂️
in your python code?
it passes it through the post request
yes, but where is it appearing in your python code?
you use it on this line if request.method == 'POST': , but where is it coming from?
@olive tiger $.ajax({ data : { id : id }, type : 'POST', url : '/process' })
that creates the post request and then sends it to the url for the route
I am talking about your python code
from flask import request
this is the module, which you import from flask - has nothing to do with that request. I already gave you the answer: request must be an argument of you process function
oh that was answer not a question..how would you pass/accept the request object then?
what do you mean?
I think, it should be like this: def process(request):
https://flask.palletsprojects.com/en/2.0.x/quickstart/#accessing-request-data I think he is right...
So Flask uses an import for the request an not a param
Do you get any error on the server side?
Maybe you should return a response?
*another
The 400 bad request error is all I'm getting. I set up a fresh project with a single page and the same code and it's working..so I'm thinking maybe something else is causing it?
oh, I see. Sorry for confusion @warped aurora
It's all good
Not sure but do you get your debug print in the prompt?
Yea
Hey guys
Ive did a register view in this way:
def Register(request):
serializer = serializers.UserSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
username = User.objects.get(username=serializer.data['username'])
token = Token.objects.create(user=username)
else:
print(serializer.errors)
data = {
# 'user_id':serializer.data['id'],
'username':serializer.data['username'],
'Token':Token.objects.get(user=username).key,
}
return Response(data)
Is it a good approach ?
Hi there, If any Django developer could help me with this question, I would appreciate that!
It is important if you are using DRF to build your API
It will be better to separate the DB insertion and all of your business logic from your views, you can read more about this pattern here
https://github.com/HackSoftware/Django-Styleguide
i keep getting
{
"detail": "Token not valid"
} when trying to do
jwt api authentication
And you're providing the header Authorization: Bearer <jwt token>?
and not just Authorization: <jwt token>
Does django pagination load only the set of the data tht is 10 object per page for example or it loads all data and just response with the first 10?
If it loads all data ,does that mean that Queryset slicing or limiting is better to load only a specific count of objects for performance purposes
@quick juniper @olive tiger changing type : 'POST' to 'GET' allowed the ajax call to go through, which is still a problem cause I can't send data to the route lol..progress tho
do someone have experience with hosting tensorflow dockerized project on heroku?
flask help: python in create_app from .auth import auth ImportError: cannot import name 'auth' from 'templates.auth'
Looks pretty straightforward and not related to Flask per se. What does auth.py contain?
from flask import Blueprint
views = Blueprint('auth', __name__)
^^
omg
wrong name
thanks for help
Any one?
Hey guys, I'm working on a text editor website which will basically write with voice. (Speech to Text Functionality)
I'm not able to figure how can I update just the text editor(Text Area)part without loading the whole website again and again after a speech.
I think its possible with django template if you added javascript. However, I think its better to use a js framework if possible
I already started the project on django can't change it now
any idea how can I do it in django?
I mean you can do a new front end project and send api
Ive found this, it may help
https://stackoverflow.com/questions/34774138/reload-table-data-in-django-without-refreshing-the-page
Ill check this out in sometime, thanks
Np
Hi, Can someone guide me with dj-rest-auth. I want to create api of login, logout, reset password and etc.
I tried but its asking for template
from django.urls import path, include
from rest_framework.authtoken import views
from dj_rest_auth.registration.views import VerifyEmailView, ConfirmEmailView
urlpatterns = [
path('admin/', admin.site.urls),
path('api-auth/', include('rest_framework.urls')),
path('api-token-auth/', views.obtain_auth_token),
path('dj-rest-auth/', include('dj_rest_auth.urls')),
path('dj-rest-auth/registration/account-confirm-email/<str:key>/',ConfirmEmailView.as_view()),
path('dj-rest-auth/account-confirm-email/', VerifyEmailView.as_view(), name='account_email_verification_sent'),
path('dj-rest-auth/registration/', include('dj_rest_auth.registration.urls')),
path('api/', include('api.urls')),
]```
Error
in general it means creating web sites.
Web development can be considered existing in two versions:
- Dumb version: Just use wordpress to create simple stuff in minimal amount of time but heavily limited in what you can do
- More complicated version: Any custom desires can be fulfilled with Frontend/Backend/Devops stuff, as exapmle online tools https://www.photopea.com/ or online games
In general 2nd choice is assumed here as a web development
Frontend: stands for making visual part of the web site
Backend: stands for making server side part of applications and usually means to work with databases
DevOps: means working with infrastructure of the servers as a code and automatization of development processes
Technically also, web development architecture is heavily reusable to be reattached in not just web sites but in any web connected applications, like mobile apps or desktop apps.
So we can say that web development is not really limited to web sites.
It means just about any development that as a end result hosted in servers with at least some parts having public access.
Usually web development assumes to target Linux servers(Because they are efficient in resource consumption and having free licenses), but Windows Servers exist too.
Any Software as a Service platform that exists to simplify it, in the end is just intermediate link to the same thing.
So let's conclude:
in 98% of the cases web development means to develop applications to be running in Linux Servers, with public exposure
for access to them in the form of web sites, mobile apps or any other web connected device.
I need a CTO for my startup who knows full stack web dev if anyone is interested ping me
DJANGO:
is it possible to do custom functions and call it from views and pass parameters to make the logic but outside the views file?
PURPOSE:
(To make views file more readable and reduce code duplication)
Yeah, it is possible to do it and is recommended for code modularity & readability.
Create a python file outside of the views folder in your app. Import this file inside your view file and use it inside the view as required
yes?
i want my html code to run
and its running fine
but
i want to add some script too in it using python but idk how
ok
that's a pretty unusual thing to do actually
how
but in theory you could add the brython javascript to your file
then you should be able to declaere a script block with text/python as the type
just because a client browser is not usually a place python runs
ohh but im making one project! all i have to do is make one simple calculator and i want to add some script so that i can run
can u help
?
@dim rover
https://brython.info/static_doc/en/intro.html
have a check for how to get started if you wish
as it was said using python for client side in unusual, but nobody says strict no 😉
thx for link and help
Hi! So, I have built my website using Jekyll. And I want to add clarity.ms analytics service to my website. I copied the code from clarity.ms site and after I paste the code in my project, save the file and run jekyll locally, the clarity code won't be there and the project is back to the previous state. Please help me to fix this and understand why this is happening ... thanks!
hello do somebody knows what is Post back page can u please explain?
highly likely you mean rendered page in response to POST request made by submit action of HTML form https://www.w3schools.com/html/html_forms.asp
(or sent page during the request)
So its just an action made by an a POST request to a webpage to store user credentials
it is unknown for sure. Post back page is unclear name
we can only speculate its meaning
it can be
- body of POST request for example
- Or it can be page rendered in response to POST request
- or something else?
I just proposed the closest guess I have
thx i appreciate your help
u a welcome. Highly likely I think it is 2nd choice.
In web development, a postback is an HTTP POST to the same page that the form is on. In other words, the contents of the form are POSTed back to the same URL as the form.Postbacks are commonly seen in edit forms, where the user introduces information in a form and hits "save" or "submit", causing a postback. The server then refreshes the same pa...
oh we have some similarily named definition
so according to this definition..
highly like your Post Back Page is
POST request (during HTML form for example) to exactly the same URL of the original page to receive rerendered changed page
main content is rendered to you during GET request
but when you click button, you perform POST request against the same url
everything is making a sense now thx for the info's @inland oak
https://pythondiscord.com/pages/resources/guides/asking-good-questions/ ask questions in the right way.
ok
from flask_socketio import emit, join_room
from random import randrange
from models.database_config import mongodb
from .. import socketio
from ..models.mogodb_utils import get_all_documents, create_new_room, get_roomdetails, delete_game_details
@socketio.on('createroom', namespace = 'boxit')
def createroom():
previds = [document["_id"] for document in get_all_documents(mongodb["gamedata"])]
newid = randrange(10**6, 10**7)
while newid in previds:
newid = randrange(10**6, 10**7)
gamedetails = {
"_id": newid,
"playercount": 1,
}
try:
create_new_room(mongodb["gamedata"], gamedetails)
emit('roomcreated', {'roomid': newid})
except:
emit('roomecreationerror')
@socketio.on('findroom', namespace = 'boxit')
def findroom(payload):
roomid = payload['roomid']
room_details = get_roomdetails(roomid)
if room_details['playercount'] == 1:
room_details["playercount"] += 1
delete_game_details(mongodb["gamedata"], room_details)
emit('roomfound', {'roomid': roomid})
emit('opponentjoined', {'roomid': roomid})
else:
emit('roomnotfounderror')
@socketio.on('joinroom', namespace = 'boxit')
def joinroom(payload):
roomid = payload['roomid']
join_room(roomid)
@socketio.on('killroom', namespace = 'boxit')
def killroom(payload):
roomid = payload['roomid']
room_details = get_roomdetails(roomid)
if room_details["playercount"] == 1:
delete_game_details(mongodb["gamedata"])
flask socket is not responding
no error in the terminal
const socket = io.connect(window.location.href + ':' + location.port + '/boxit');
socket.on("roomcreationerror", () => alert("Internal server error.\nTry later."))
socket.on("roomcreated", (roomid) => window.location.href = waitinglobbyurl + "?id:" + roomid)
socket.on("roomnotfounderror", () => alert("Room not found!\nEnter valid code."))
socket.on("roomfound", (roomid) => window.location.href = online + "?id:" + roomid)
const performOnLoad = () => {
document.querySelector("#join-room").addEventListener("click", onJoinRoomClick);
document.querySelector("#create-room").addEventListener("click", onCreateRoomClick);
}
const onJoinRoomClick = () => {
var roomid = prompt("Enter room id");
socket.emit('findroom', {"roomid": roomid});
}
const onCreateRoomClick = () => {
socket.emit('createroom');
}```
js code
perhaps to check Chrome Dev Tools errors also for your JS code, specifically tabs Console and Network
not possible complete lack of information in Chrome Dev Tools
no errors in dev tools*
thing bring what is there besides errors
oki wait
Connection that was not made, could not be without errors
Hi, is there an interface for django testing, which you can include to urls.py to start tests from development server and not from comandline, so you can manage everything in browser?
There is interface to do that in IDE, like VS Code
O.K. whats its name?
extension: Python Text Explorer, integrates with Unittest Pytest and Testplan frameworks
It gives visual interface in left side bar + right at where the tests are in the code
the most comfortable feature of it to run them in debug mode
which enables breakpoints stuff for debugging
Oh cool THX and is there a module to do it from admin panel?
🤔
There is interface that shows test results in Github/Gitlab and e.t.c. repositories
it is called CI/CD pipeline
automatically launches tests on every commit for example
and shows results in browser / if something goes wrong notifies by email
I am having it in Gitlab CI for example
Cool, I am thinking how to implement this in docker. I want to make a drf with js frontend, but I have to learn much about devops tools.
Xd. Thank you very much for your advice.
u a welcome
basically same thing I use. DRF + Vue.js with a plenty mix of devops tools.
Xd, I use nuxt.
@native tide what do you need help with?
.
Do you recommend any tutorials on this?
https://docs.gitlab.com/ee/ci/quick_start/ official docs should be fine
it is auto suggesting some choices interactively during its creation also
You could probably run your tests in parallel 😉
I am sure I could not. (because those aren't just tests)
stages:
- dev_build
- dev_test
- dev_push
- staging
- staging_test
- prod_build_push
build-test:
image: ${docker_image}
stage: dev_build
script:
- docker login $CI_REGISTRY -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD
- echo $CI_COMMIT_SHA > core/commit_version.txt
- docker build -t $CONTAINER_TEST core -f core/docktest
build-bundle:
image: ${docker_image}
stage: dev_build
script:
- docker login $CI_REGISTRY -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD
- docker build -t $CONTAINER_DEV --build-arg VUE_APP_BACKEND_URL=**redacted** --build-arg NODE_ENV=development core
lint:
image: ${docker_image}
stage: dev_test
script:
- docker login $CI_REGISTRY -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD
- docker run $CONTAINER_TEST lint
unit-test:
image: ${docker_image}
stage: dev_push
script:
- docker login $CI_REGISTRY -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD
- docker push $CONTAINER_DEV
trigger-downstream:
stage: staging
inherit:
variables: false
variables:
EXTERNAL_TRIGGER: "true"
trigger:
project: **redacted**
strategy: depend
integration-testing:
image: ${docker_image}
stage: staging_test
script:
- docker login $CI_REGISTRY -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD
- docker run $CONTAINER_TEST test:unit
save-as-latest:
image: ${docker_image}
stage: prod_build_push
script:
- echo $CI_COMMIT_SHA > core/commit_version.txt
- docker build -t $CONTAINER_FOR_PROD --build-arg VUE_APP_BACKEND_URL=**redacted** --build-arg NODE_ENV=production core
- docker login $CI_REGISTRY -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD
- docker push $CONTAINER_FOR_PROD
Those are tests with deployment to staging environment, running integration tests and then saving to docker registry
Publishing /Deploying a library/app I guess?
You can add global before_script to login into registry though
I could I guess
Also would make more sense to not run lint in a container I guess
why not? 🤔
it gives me less code to write in CI
one container is reusable to run different stuff. it is already reused twice
I have multiple lint jobs (formatting, unit testing), it would be faster to run them in parallel in ci
to run Lint and to Run integration testing
going to be reused even thrice, when I would run locale testing stuff
I can run tests in parallel at dev_test, and staging_test stages
I just don't have enough tests types to run in parallel yet
Yeah, I guess I have too many linters 🙂
I run isort, black, flake8, mypy, pytest and coverage iirc
maniac 😉
Yep 🙂
I don't
Not really, flake8 catches more things, like unused imports, black is just a formatter
huh. I just have black auto fix everything on file save 🤔
that's it.
Also don't use latest tag for deployment 🤔 if you're triggering your deployment using gitlab ci you won't be able to rollback it.
Not really possible in a team
I have this issue handled
I use same tag for staging env to simplify staging deployment in every commit
and I have different tags for prod env for rollback and additional purposes
I attach different tags in infrastructure repository, when it is time to make new prod deployment
Please help, my flask app is super slow for some reason, it's loading a page in like 5-10 seconds
And theres literally nothing on it, just one html page
Use Chrome Dev Tools to analyze it
run LightHouse if u wish
You have any source code to share?
That we can run/read and see what can be the cause
app = Flask(__name__)
@app.route("/")
def home():
return render_template('home.html')
if __name__ == "__main__":
app.run()```
and a html page that has `<h1>hello world</h1>`
really has nothing on it, it happened randomly like 3 days ago
This shouldn't take 5 seconds
i have 3 flask apps and they seem to all run slow
yea, no idea what is happening
its loading slower than youtube
2 things
- How is this being ran
- how are you loading the page? via
localhostor127.0.0.1are both slow?
yep, via http://127.0.0.1:5000/
im loading this through cmd, it this is what youre asking
my cpu usage is 16%, so i don't think its a problem there
what does you browser say in terms of loading time distribution
hello
on the network tab if you select the main endpoint it should break down what took what time
can someone help me with this
i.e
wait im sorry, where is this? chrome?
apparently its not flask then
You said you only have an h1 tag in your HTML 😅
also 
well put simply, we can awnser your question
bootstrap and Jquery loading is why its slow
oh yea i installed bootstrap too, just the lines that install it
flask is responding in 7ms
Try loading bootstrap from their cdn
yeah so, you're loading a load of JS that's forcing the browser to wait on it before it can fully render
are you defering those scripts?
It shouldn't take that long to load some js
I dont think so
my other extend page just has ```{% extends "layout.html" %}
{% block content %}
<h1>Hello World</h1>
{% endblock content %}
try add defer to each script tag
although the loading times from the CDNs are still horrible
and are an issue in themselves

You could actually try to just load a file from that cdn, is that link in official bootstrap docs?
it is yes
wait im quite confused right now, i copied the bootstrap code from another project that i was following with a youtube video, now i used the one from the bootstrap website,
now its like running normally, but that really doesn't make sense, why is the other one running so slow all of a sudden?
what did you change?
i just took the code from the website

Some questions don't have answers 🙂
nevermind, now its running slow again
ok what is going on exactly
i guess it is an improvement of 2 seconds
CDN moment
ig their CDNs are dying
does it actually stop the page from loading content then?
I havent added any bootstrap yet, just a <h1> tag, yes its loading the <h1> tag
let me add a button
its not loading bootstrap
its just... well a button, not a bootstrap button, a button
yeah it wont untill it actually gets the JS for it and css
which appears, bootstrap cdn is dying
try using 4.5 maybe
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
Yep, that would help 🙂
week goes by
issue persists
blinked in confusion. Do you mean he is at the same problem for a week already?
Still triying to figure out why my Ajax calls only work when type : 'GET' lol
<head>
<!-- AJAX -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<a href ="" id="test_link" data-id="2">test</a>
<script type='text/javascript'>
$(document).ready(function(){
$('#test_link').click(function(){
var id = $(this).attr("data-id");
$.ajax({
data : {
id : id
},
type : 'POST',
url : '/process'
})
.done(function(data) {
if (data.error) {
alert('I hate tomatoes.');
}
else {
alert('I love tomatoes.');
}
});
event.preventDefault();
});
});
</script>
</body>
no no, I just mean given how unusual of a tool brython is, there's likely to be more issues upcoming :p
issues will be always. it is a matter of having problem solving skills to solve them more on its own 😉
Man, fastapi is amazing
@true shale @manic frost do you know any good academic pages? So far I found this one to be pretty good enough https://varunjampani.github.io/
Varun Jampani
I installed tailwind css but the style did not come up any ideas?
opening Chrome Dev Tools to see if tailwind css file was loaded without errors for starters
(trying to click the url of the css also, by looking through the page source code)
or just actually accessing it with url
your web site url / path to tailwind css
to find if it is accessable at all
Do i need to know JavaScript for flask
no
Flask or django
Hey guys, I wanted to start with web dev in this year, I know like the basics in html, however I don't understand at all how or when to use divs, I need to learn css and some Js and I've heard of something called boostrap for html and react for js? Any path for getting started and what projects I can do to start practicing?
how can i use flask to filter sqlalchemy object by month?
If you have to ask, you should probably start with Flask. Django is more powerful but more complex. It will take you less time to finish your first project if you start with Flask
If your primary interest is in frontend, bootstrap does sound like a good next step. There's not shortage of free materials https://medium.com/javarevisited/7-free-courses-to-learn-bootstrap-for-web-designers-and-developers-5135215648f1
No matter what I do I can't seem to get the csrf token to work with my AJAX request...help 🥲
should I know grid/flex before learning bootstrap?
I'm just curious as to what knowledge I will need to have beforehand
Any tips for learning flask and sql alchemy? I got a new job that uses flask for their backend so I gotta learn it
Want help from you people
I want to start my web development course so plzz suggest me how can I start , plzz help me with the resources for web development 🙏🏻
Eivl plz help me
Hi dark wind I also want to learn web development plz help me
@reef cave We do not permit job postings in this server. Please review our rules.
Hello everyone ! First, I wish you all a happy new year. However, I need your help for javascript in django(v4.0) forms. I'd like, in a separate file, use an onchange event on a specific field of a form. Can you help me ?
I found this :
reciept=forms.ChoiceField(reciept_types, widget = forms.Select(attrs = {'onchange' : "myFunction();"}))
but it looks like the js need to be in the same html file as the form
But I need the javascript to be in a separate file
you can do this, and define your function in a separate file and then link your file to the html page
js file that is
Oh so I import js separate file into html file and define the function in attrs field form
So it'll search into the js file imported in the html
if that's how you want to think about it
Build a simple REST API to CRUD in the DB of your choice
hello everyone
i am new in this field
and i alsoo want to learn web development so plzz help me
help you with what?
help me like fronmm where should i start or what are the things that should i need for web development
I got a OperationError for the code
len(db.session.query(Detail).filter(func.date(Detail.Date_of_diagnosis) == date.today()).all())
with the error FROM detail WHERE date(detail."Date_of_diagnosis") = ?] [parameters: ('2022-01-02',)]
how can i fix it?
Can you show the full error?
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such column: detail.describtion
[SQL: SELECT detail.id AS detail_id, detail.subid AS detail_subid, detail."Symptom" AS "detail_Symptom", detail."Check_result" AS "detail_Check_result", detail."Preliminary_treatment_plan" AS "detail_Preliminary_treatment_plan", detail.describtion AS detail_describtion, detail.cost1 AS detail_cost1, detail.cost2 AS detail_cost2, detail.cost3 AS detail_cost3, detail.tag AS detail_tag, detail."Date_of_diagnosis" AS "detail_Date_of_diagnosis", detail.user_id AS detail_user_id, detail.patient_id AS detail_patient_id
FROM detail
WHERE date(detail."Date_of_diagnosis") = ?]
[parameters: ('2022-01-02',)]
(Background on this error at: http://sqlalche.me/e/13/e3q8)
please dont mind the bad variable name
You have a typo (describtion)
(sqlite3.OperationalError) no such column: detail.describtion
what a goo ide for html css and js
vs code
what line number is the error on?
it looks like you never saved the date in the session
how do i do that
did you ever post a valid form?
Hey! I am trying to create a flask request that is quite intensive in the sense that it makes some DB calls some other API calls and does some compute. So I want to do parllel processing here. How can I go about it?
which leads to the payment pae
page
and this is wat shows on the payment page
is kinda frustrating now the request works in the class
but outside of class it shows error
actually ur right for some reason it is not getting saved
@whole crow something wrong my fucking code why is not redirecting to payment
but customer/booking
html, css and JavaScript is a good starting point. in that order
Why I cant render login.html even tho it is in the same folder?
Dont ask why I use Kali with root account. Linux deploy has several problems with setuid so cant use regular user.
What I tried:
Write ./login.html and full path of HTML.
Result:
Same thing. Same error.
flask requires templates being in subfolder templates
And which function's parameter is that?
render_templete()?
yes, render_template, probably https://flask.palletsprojects.com/en/2.0.x/tutorial/templates/
@thorn igloo ok
Okay,lemme try.
I want to do parallel processing in a flask request. How can I go about it?
do you want to wait for the processing to finish before returning a response?
I am a bit confused about Vuex, Redux and similar things. Aren't they just big global variables that we're trying to avoid in properly structured applications?
It seems to me that they have the same issues: anyone can change anything at any time. And this become increasingly painful with concurrency
They are more like class with global access. So we have tied to them setters/getters/other methods
Which makes control logic in one place
DRY and much less tangled
Not really encountered concurrency issues in js.
Usually we use sync and async stuff there, in both cases I saw no problems yet
well, a class with a mutable classvar is the same as a mutable global variable
The code written without them is even worse. There is just no really good alternative.
State management in Vuex allows to continue using MVVM data flow...
But basically u a right. It does not scale well in terms of code base
Setters/getters make a difference though. A single functions to change them and to get, it is enforced usually
still, you can call these getters and setters from anywhere
Makes life easier
I feel like there isn't a way to not write spaghetti code on the frontend... I don't know what to do
It is told there is no exit in Vue at least
Except making multiple app instances
I heard react scales better
Perhaps it is solved there
React has Redux, which seems to be the same idea?
Yes
I don't know why react scales better, that is just collected rumour
I tried only vue
I think I'll try to avoid using vuex as long as I can
xD I am already prejudiced against frontend, I hope I will not become more
Going to learn some stuff to improve my Frontend anyway probably
Because there is no alternative
I tried PureScript, but that seems overkill
I will use only production ready stuff
That allows me using
Only React, Vue, Angular
And as a stretch... Some Frameworks based on those three Frameworks
JavaScript and Typescript only
hey ppl i've a trouble...
can i make an API using flask that when i do a get request then i get a json and download a file at the same time?
You should use two endpoints, one for the json and one for the file. You can include an ID as the field in the json which is then provided to the file endpoint to link the two together
i got it... it's what im doing.
I struggle with uploading my react projects on git hub?
Any good tutorials recommended?
Hello y active
How can I configure django to allow /media/ within the staic dir? I know full well this isn't standard practice, however I'm rebuilding a large application with a JS frontend and am bundling it in django's static dir so upon collectstatic, it deploys to ./public_html/. Outside of dev/debug, django only renders /admin/ and /api/, everything else is static.
The only other thing I can think of is to configure setup.py to deploy the frontend but I'm not sure how to accomplish that outside of venv/lib
I have this python snippet. and the log output is not what i expected at all... interface is a peewee.Model and g is just flask.g. g.user is a model and g.user.interfaces returns a peewee.ModelSelect object. it iterates over interfaces acting like list[Interface] models.
# Save a has a priority bug that needs to be fixed
def save(interface: db.Interface) -> int:
state = InterfaceState(interface)
if state.is_empty:
return 0
if state.is_single:
return state.set_interface()
for index, item in enumerate(g.user.interfaces):
if item == interface:
item.active = True
else:
item.active = False
with db.database.atomic():
saved = db.Interface.bulk_update(
g.user.interfaces, fields=['active'], batch_size=50)
return saved
The result from the log is
[save] [interface] [arg] <Model: Interface> main False
[save] [interface] [iter] [0] <Model: Interface> main False
[save] [before] [equal] True [active] False
[save] [after] [equal] True [active] True
[save] [interface] [iter] [1] <Model: Interface> sandbox False
[save] [before] [equal] False [active] False
[save] [after] [equal] False [active] False
[save] [saved] 2
What's weird about this is that the results show that item is selected and updated and saved with the bulk update, but when i query the database, its not updated
>>> for i in user.interfaces:
... print(i.name, i.active)
...
main False
sandbox False
>>>
I thought at first it was my logic, but i can only trace this issue to the Model.bulk_update method provided by peewee.
Hey everyone, I'm playing with JWT and FastAPI - went smooth enough for the swagger Interface, got a token and can "execute" protected routes. Now I'm trying to implement HTML templates and create users with a protected route. Create, login no problem but I stored the JWT in a cookie and can't seem to pass it back to the fast API page to authorize correctly. Question, how should I be storing it in order for fastAPI to recognize it and decode it properly?
No. Svelte can be used only for pet/home projects as maximum
Svelte has a hype to try
But it is taking super low market share (small fraction, which is less than 0.1% for sure)
The biggest drawback.. the size of community and passed years.
Svelte has really small ecosystem of libraries (or their lack of)
If u take svelte, then u can consider only on standard package, everything else u a going to reinvent.
Hell even router is not stable.
Things like Vue have. Everything. Router, state management, I18n tools, and many others. Ready solution for any common problem.
And just stability. Ensures that components will work without surprises.
When I tried svelte, I was able to break it in five minutes and due to compiler not really catching errors efficiently, I did not have even errors/logtrace to find what was wrong
As for elm, pure script....
In production ready stuff only typescript suggested as augmentation.
And according to statistics it is the most used static typing tool
And official docs to Frameworks usually mention only it
what is bootstrap for?
I have made a complete static website using tailwind(v3.0) and now i have to make this website dynamic using django. How can i do that with no mistakes , since there are many files like config and others and I don't know where to put these and all .
I have made a dynamic website with simple static website that uses pure css but not with any css framework. Can anyone help
I want to make a web login system using flask. Let's guess that I made 2 input boxes for username and password. How can I "connect" them to my code?
I had experience with PyQt and it was something like get_text() or similar (long time no use so forgot....) but what about Flask?
I don't know if this should be here, but I'm trying to open a websocket connect to a url and then print something. Here is my code:
def on_message(ws, message):
print('Hello, World!')
ws = websocket.WebSocketApp('wss://some-url, on_message=on_message)
ws.run_forever()
print('Hello, World')
But it doesn't execute the print statement. Can someone please help?
The NYT has Svelte pages running. I know of SMEs using Svelte in production. Svelte is definitely able to be production ready, whether you'd want to use it for an app the size of Facebook is a different question. I don't know any details, but "no it's not production ready" is absolutely underselling it. @manic frost
I disagree. My points still stand. That someone uses it is not changing it.
Here's a Twitter thread of companies using it in production as of 18 months ago. https://twitter.com/SvelteSociety/status/1260209026563858432?s=20
👋Who else uses @Sveltejs in production at work?
Let's make this a PRODUCTION SVELTE MEGATHREAD!! Links/stats/screenshots/videos appreciated!
#ProductionReady https://t.co/A9nbnVRDQY
201
The fact that companies use it in production demonstrates that it's production ready and is more relevant to the question "is it production ready" than the fact you had a bad experience
my main point small pool of available additional libraries
and lack of fully stable/developed core libraries (router is in beta)
and super small market share.
It's more a case of pick the right tool/framework for the right case. Svelte's origins is from data journalism, so it's perspective is going to be different when it comes to the likes of React coming from Facebook.
While it is small, it has an active community and is maintained so can be used in production
In production ready stuff only typescript suggested as augmentation.
what do you mean by "suggested"? who suggests it?
@api_view(['POST'])
def Logout(request):
request.user.auth_token.delete()
data = {
'status':'Success!'
}
return Response(data)
Whats better, to make @api_view(['METHOD']) a post or a delete or a get? or it doesnt matter
I tried PureScript a while ago. And while the language is great, the ecosystem is very young. I'm hoping it gets better over the years
for React and Vue people create tools to setup easily everything for project. Literally everything. Babel, I18n, unit testing, acceptance testing, SASS and e.tc.
Vue Cli and Create React App tools
both tools suggest augmentation only with TypeScript
plus as far as I remember docs suggest the same
Do people actually use vue-cli and create-react-app in production? 🤔
my company doesn't
why not? 🤔
Vue Cli was recently updated to 5th version to be up to date with stuff
TypeScript has first place for many years ;b
there is no doubt to it
Considering its popularity and quite often demand in jobs, higher chance to have people both knowing TypeScript than other js flavors
it should make easier to have several people working in same project / or project transferability
hi i m getting this error with webhook request : TypeError: 'NoneType' object is not subscriptable
with this project : https://github.com/hackingthemarkets/tradingview-interactive-brokers
Hey. I'm learning HTML, css and Java for freelance web development. But there's this question that always come to my mind. Should I learn these or learn a bit of wordpress? I feel like a web developer and a wordpress designers are treated the same way. Most of the free lancers are wordpress designers on sites such as fiverr. Wordpress doesn't require any coding knowledge whatsoever. Ofc I know learning web development is worth way more but I wanted to know if it's any good in freelancing,
Does someone know how to set lookup_field in DRF? I tried specifying my custom pk in a viewset and serializer's Meta class but it still generates swagger docs with the wrong field for get/put/delete by id endpoints
This depends entirely on your goals, needs, interests, etc. If your primary goal is to grab freelance work ASAP it sounds like trying your hand at WordPress might be worth it to you
Well I do have time like 8 months, an year or as long as I can get comfortable with the languages but yk, I'd feel more motivated knowing that I can do extra with that knowledge over the sites made with wordpress in terms of freelancing. As for now I feel like there's no point at it as where ever I see people are using wordpress.
DJANGO vs FLASK??👀
Please reply!
For what? Generally if you need to ask, you should probably start with Flask as it's less complicated to pick up and you can always learn Django later if you need something more powerful
Agree = True
Django is quite complex when it comes to file handling
i am trying to blur only the background of div with some child element(h1,p). But couldnt do it with pure css . help me plz
Flask give you great experience working with back-end part and after that you can learn Django easily
Display : None
how can flask admin filter by date?
its more like trying to make background little bit opaque so that element inside div become more visible and looks cool.
Sorry 😐 I'm not front-end guy
ok no worries thanks anyway
What you have to do ...?
anyone who can help me with pure css?
I want to have the admin view but want to have the newest object being added on the top
Does anyone know how to actually solve this issue? Whenever I run the system, it will pops out 404 error
You have a get route for '/'? What does the code look like?
i;m trying to make course system like udemy or some another platform
so in vid 1st field is foriegn key to get/select the course to get the video is of which course
then i tried to do stuff like django admin by radio buttons at the form
vid_of=models.ForeignKey(Course,on_delete=models.CASCADE)
Anyone know how I can print datefield in django it always prints None
@login_required
def video_upload(request):
if request.method == 'POST':
vid_of=request.POST.get('vid_of')
vid_title=request.POST.get('vid_title')
vid_desc=request.POST.get('vid_desc')
vid_video=request.FILES['vid_video']
vid_author=request.user
if Video.objects.filter(vid_title=vid_title).exists():
messages.error(request,'Title taken!')
return render(request,'index/video-upload.html')
elif len(vid_title)>55:
messages.error(request,'Title too long!')
return render(request,'index/video-upload.html')
print(vid_of,vid_title,vid_desc,vid_author,vid_video)
entryy=Video(vid_of=vid_of,vid_title=vid_title,vid_desc=vid_desc,vid_video=vid_video,vid_author=vid_author)
entryy.save()
messages.success(request,'VID ADDED SUCCESSFULLY')
return HttpResponseRedirect(reverse('home:index'))
return render(request,'index/video-upload.html')```
in print statement it's printing
Anyone know how I can print datefield in django it always prints None
<div class="input-box">
<span class="details">Course</span>
<select name="vid_of" class="inputs" required>
{% for post in user.course_set.all %}
<option value="{{post.course_title}}" name="vid_of">{{post.course_title}}</option>
{% endfor %}
</select>
</div>```
i used same way as django admin panel
but it's giving error
So no, you do not have a route for '/' if that's everything.
@app.route('/')
def index():
if not is_valid_session(request.cookies.get("session_id")):
return render_template("invalid_session.html")
return render_template('index.html')
do you mean by this?
In that case, you might need to specify the method (presumably GET)
Does anyone know how to move the world Flask to the right a little? I'm using bootstrap and i tried ml-2 and it isn't working.
tried wrapping the whole page in <div class="container">?
tried it, it kind of cuts the blue part a little
so i have a question, is it possible to make a very simple social forum with only html , no css/javascript?
Hi, is there any good and simple codebase to add Photo gallery (in which each photo can have some description when opened) compatible with Jekyll for GitHub pages?
i think i found the issue
because when "/" gets called, it checks the session cookie
but that doesn't exist until you login
so need to add an exception for that
An ugly one with simple features, maybe :)
i was thinking to do something like a study forum
would i be able to do that with only html? with just some simple interface and mainly using text and maybe images
If you include a Python framework like Flask or Django, probably
i have to do it in lamp, with apache, mariadb, php and html
Is there a good tutorial how to host a django app on local linux server and update it etc. ? I am learning django but got depressed because I can not find a way to Host an App on my rpi.
hi guys
someone knows why can't I catch the exception and print it to my front end ?
I use Django server
print() prints to the backend. You need to include it in the response object to send it to the frontend.
if django has the concept of flash like flask does, you can use that and use it in your template later.
I have a question regarding to react js frameworks, should I learn Remix or Next js
Are you running a webserver on that linux server? I think any tutorial on deploying to a linux server would work. This is a little older but generally has the same principals. https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-apache-and-mod_wsgi-on-debian-8
It's definitely possible on a Raspberry Pi if that's what you want to do. https://pimylifeup.com/raspberry-pi-django/
Hey guys we are all so worked up with django, I just wanna let you know. Whatever it is you are trying to do never give up and always take break in between
This is a great solution and simple.
I'm actually worked up with fastAPI right now, lol
Hello everyone, I need help for something I don't understand. I'm creating a website for shopping, so every product as a quantity stored in the database. I would like, when I create the form, to populate my select list with the number of product left in the database. For example, I get in the views the quantity for the product (for example : 20 products left), and when I create the form I need to populate my select with numbers between 1 and 20. Do you have a solution ? Thanks 😄
@valid void What framework are you using and what have you tried? Maybe share your codebase.
woops, sorry it's for django
I've tried absolutely nothing as I can't find any answer
I know how to populate with specific values using forms.ChoiceField(choices=variable)
But now I need this variable to be populate by integers between 1 and a number I have from my views
hmmm, i'd have to see the code to be able to help but I'm sure it's been handled as this is a very old problem. Probably just need to do a count
def productinfo(request, idp):
p = Product.objects.gets.get(pk=idp)
form = AddForm() #I need to populate the field quantity in this form
#p.quantity -> is the variable I need to populate
template = loader.get_template('project/productinfo.html')
context = {
'product': p,
'form': form,
}
HttpResponse(template.render(context, request))
ok what is your issue
class AddForm(forms.Form):
quantity=forms.ChoiceField(choices=#range between 1 and a variable, required=True)
I need to populate quantity with integers between 1 and the variable p.quantity that I got into my views
can you share your model just so I have more of an idea what you're talking about
(quantite = quantity)
(Produit = Product)
In my views.py, I got p.quantity which is an integer that shows the number of products left, and I need to store all the integers between 1 and p.quantity in my field "quantity"
this link should help
I found a solution 🙂
In my form :
And in my view I'm calling my form with qt as an argument
i have checked i dont
and plus the paypal buttons disappears wtf
Hey Guys, I'm facing a issue with my Register Page in Django. While creating a new user it is giving me an error:
permission denied for table auth_user
But the thing is registration is working fine on my localhost but not working on heroku server.
Also, the permission is denied for creating a new user.
User.objects.create_user(username=username, email=email, password=password)
if you're referring to it by name in template, you need complete_order not completeOrder
Can anyone help me how do I fix this issue?
I'm using SQLite for backend and heroku server deployment.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
wat
sorry, missed the second attachment, not sure how that works with the JS, I never touch it, but you aren't in a template there, maybe that's the issue. Can you use python templating directly in JS?
its only the url
most of the tutorials
says this
I was trying to use celery in my flask app which does prediction on two strings. but when I run the celery -A tasks worker --loglevel=INFO command I am getting Error: Invalid value for '-A' / '--app': Unable to load celery application. The module tasks were not found. I am following this documentation. I am attaching the pic for your reference below.
When I push data to HTML, I get table syntax like paragraph instead of table
Hey so if I am trying to do sprite sheets for my icons, would it still be valid to use a SVG file at that point or would I be better off using a PNG if its a sprite sheet?
Flask's Jinja2 automatically escapes html tags to you need to mark your data as safe.
{{your_data | safe}}
Hey guys I have flask app with postgres and I want to deploy it to google cloud ?
what should I use google app engine or virtual machine?
hello guys
anybody that can maybe help with some django pattern not working correctly..
anyone know how i can solve this problem? It happened suddenly and before this, there was no these errors
What error are you referring to?
If you're talking about yhe warnings, those are fine. Also, if you're referring to the 304 codes, those are also fine. The 304 http code means that there's no need for the css & js to be transmitted again because they have already been cached by the browser
https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/304
The HTTP 304 Not Modified client redirection response
code indicates that there is no need to retransmit the requested resources. It is an
implicit redirection to a cached resource. This happens when the request method is
safe, like a GET or a HEAD request,
or when the request is conditional and uses a If-None-Match or a
If-Modified-Si...
Hey guys i got a question, recently i discovered Tailwind for real and tried using it and it really good, so my question is as someone who can produce something with Vanilla CSS 100% or with Tailwind which one should i go with, in terms of client satisfaction
Hey everyone, I have a question and I would love if I could get some support on this:
I am developing my first ML API which I want to host in AWS Lambda. I have figured everything out but I am missing something important: How will logging work?
Currently I am using a filehandler and locally, logs are written in a log file. How will that work with aws lambda?
you should just log to stdout rather than a file, then you can see the logs in CloudWatch
Hi, how is it possible to print a response in a flask app to the terminal (i.e. to see payload for a route to help with debugging)?
@civic dragon have you tried google
the very first answer on there
clearly has the same situation as you are in
if you are unsure about the actual information given there, we would be happy to help you understand it
its also useful to be able to find information on your own, helping you learn to do it is actually the most helpful thing we could do for you arguably
Thanks Charlie! That sounds like a plan.
@native tide I agree with you. I actually went through a few search results and wasn't successful. It's primarily b/c I'm new to python/flask (I usually deal with JS/Node) and the app I'm working with isn't a simple hello world app (possible I might be trying to do things in the wrong place/file), so I'm getting confused and decided to ask here. You're right though...I need to get better at finding helpful google results and figuring out how to apply the info.
Is django-tailwind the best way to get up and running with Tailwind v3.0 in Django? The JIT features and extended flexibility look really amazing
I have this endpoint but I keep receiving this, but why?: https://paste.pythondiscord.com/olakawuqih.sql
Code: https://paste.pythondiscord.com/fayidideda.py
(print statements was for debugging)
hello web community, how to add security in simple way to my flask app? Thanks a lot
@uneven plume you can't json serialize the Request object
What does that mean?
@uneven plume you are having {"request": request} and request is <starlette.requests.Request...> which you can't use in json
and what fastapi does - it returns json
so it tries to covert your dict to json and it just can't
So what should I do instead?
what do you expect to have in the response?
The token
for exmaple like this:
from pydantic import parse_obj_as, BaseModel
from starlette.requests import Request
from starlette.responses import JSONResponse
class ResponseModel(BaseModel):
token: str
@app.get("/show_token")
async def show_token(
request: Request,
token: str = None
): # noqa: B008
"""Show the refresh token from the URL path to the user."""
response = dict()
if token:
response["token"] = token
return parse_obj_as(ResponseModel, response)
else:
return JSONResponse(
status_code=404,
content={"message": "No token found"}
)
👍
