#web-development
2 messages · Page 192 of 1
it's not padding-block, it's just padding
ok
thx
.autorize button {
background: #232222;
color: red;
border-color: red;
padding: 10px;
text-align: center;
font-size: 13px;
border-radius: 12px;
}
```How to put this text
in the center of the screen
Create a new div element,Wrap up your code and make It as the parent element of the button using ID attribute and give a value, Make a CSS ruleset for ID and add "text align: center;" It should work.
If you want to save code In ur code editor use "<!-- WRITE ANYTHING INSERT CODE OR SAVE CODE -->"
thx
Your welcome, hope 🙏 this helps.
Hey guys i have to make a api at work. Where i have to connect to a mongodb database. It should take JSON as request like {"status" : "panding"} and api should respond data from mongo where Status is pending. How do i do it .? What should i use ?
So first of all I have an idea for a website. Lets say you are a content creator and you want to find a clip where youtuber 'A' says something like "Hello everyone", "Bye"...
To do this my app would need to first gather all the youtube videos of a channel. Then it would need to get the subtitles of every single video. That would require a lot of API calls, let's say like 500. What would be the fastest way to do this?
Would I need to make some sort of load balancing across multiple servers?
Or can a client make all these API calls fast enough
Also would be great if I can display the first results while the other API calls are happening
Where can I practice CSS on artificial tasks?
Or rather, apply CSS so that the page doesn't look like crap.
I often go to a random page, go to Firefox's "Style Editor" in dev tools and mess around.
Only issue with that is A) copyright issues B) it breaks YouTube TOS and C) not all videos have subtitles
Yes I thought about that and I'm making this only for learning purposes
That doesnt change anything im afraid
Well especially on the breaking TOS side of stuff
What if I use their official API?
You can download the captions
It's the video side of it thats the issue
You cant do that via the api
Ye I'm not planning on downloading the videos, just the captions
In that case is should be okay
Also for C I'll also have to think about that, maybe they can auto generate the captions
Hello. I'm trying to make spanish dictionary but I don't know how to make database. Does anyone have an any idea how I can do this?
I dont know too
I mean, we can't teach you via chat but there are lots of tutorials and such out there.
To start, look up how to use python and sqlite together. That'll be the lowest barrier to working with a db.
where can i find a database online for free?
A database of what?
Or are you looking for a database that you can use to store your own data?
yeah i wana store data ther
there
its not that serious tho i just wana test a project
like i dont care about security or anything
There are many databases you can use
Postgresql, mysql, mssql, etc.
yeah i know them all
the thing is
how can i use it online
like how can i save the data online
not on my pc
is there a way to do it for free?
even for just a couple of rows or smth
Uh well, there are some online free hosting things
https://supabase.io is something I've used before
It's rather nice
thanks dude
Does anyone here know how to publish a Flask + Socket.io website? (I can't seem to find any help online)
def comment_approve(request, pk):
comment = get_object_or_404(Comment, pk=pk)
comment.approve()
return redirect('blog:post_detail', pk=comment.post.pk)
# removing comments
@login_required
def comment_remove(request, pk):
comment = get_object_or_404(Comment, pk=pk)
post_pk = comment.post.pk
comment.delete()
return redirect('blog:post_detail', pk=post_pk)
post_detail.html
{% for comments in post.comments.all %} <br />
{% if user.is_authenticated or comment.approved_comment %} {{
comment.created_date }} {% if not comment.approved_comment %}
<a class="" href="{% url 'blog:comment_remove' pk=comment.pk %}">Delete</a>
<a class="" href="{% url 'blog:comment_approve' pk=comment.pk %}">Approve</a>
{% endif %}
<p>{{comment.text|safe|linebreaks}}</p>
<p>Posted By:{{comment.author}}</p>
{% endif %} {% empty %}
<p>No comments posted</p>
{% endfor %}
</div>
class Comment(models.Model):
post = models.ForeignKey(
Post, related_name='comments', on_delete=CASCADE) # comments for the posts.
author = models.CharField(max_length=200, null=True)
Text = models.TextField(null=True)
created_date = models.DateTimeField(auto_now_add=True)
approved_comment = models.BooleanField(default=False)
# function to approve comments.
def approve(self):
if self.approved_comment == True:
self.save()
def get_absolute_url(self):
return reverse("blog:post_list")
getting this error, how can i pass the correct pk in my comment_remove function
fixed , please ignore . Thanks
Could someone please suggest a decently built flask project I could look at that follows a structure similar to the following:
> proj
> FlaskApp
> etc...
> ClientApp (react, vue, svelte, etc)
> etc...
``` I've been looking all over github but what I can't find anything
I already have this question in #help-mango but wanted to ask short version here does flask not render anything that is in {{variable}} in template?
It does not render anything that is in {# your commented out things #}
Plus u can use general html comments <!--- stuff --->
The {{ variable }} thing is rendered, it is expected you will pass it into template
Nevermind as stated #help-mango I found solution by a bit of googling
using {%raw%} solves problem
That is wrong
<!DOCTYPE html>
<html lang="en">
<head>
<title>My Webpage</title>
</head>
<body>
<ul id="navigation">
{% for item in navigation %}
<li><a href="{{ item.href }}">{{ item.caption }}</a></li>
{% endfor %}
</ul>
<h1>My Webpage</h1> {{ a_variable }}
{# a comment #}
</body>
</html>
Let me better frame my question, how to make flask to ignore all {{}} because I am using those for vue js templates
Percentage symbol is used for loops and other stuff
So do not render with jinja2
Disable jinja2 usage
No I actually need to pass few lists to javascript
I found using {%raw%} tells flask to treat underlying text as raw text
That solves my problem
This is wrong solution involving dirty hacks
I mean it is working 
Fetch data properly with flask rest api end point that returns json data
So not use Jinja 2 at all, since u a already with frontend framework
I have not actually get decided Everything thing but yes lists should be fetched from an api my current implementation is very dirty
is there a way to get the query parameters as a string like so ?a=5&b=6 from the request object in django?
found it, request.GET.urlencode()
any django dev here ?
Is there anyway to access localhost via WebServer ?
for example your runnning django, app, and can you send request to localserver ?
@sinful stone shoot
not a django dev, just a guy who likes it
I installed ckeditor, its textarea works both in admin and in template, but when i open it in template, syntax highlighting doesn't work... What can be the reason?
Here is example, language highlighting doesn't work...
https://shrt-url.ml/paste/zone/ocf3Ap
you mean, send a request to localhost?
Hey there, I am working on a project where I am using React as my frontend and Django as my backend. However, I am stuck at the part of authentication users, are sessions still valid in react ? Since if I am not wrong react will mostly interact with the backend with some sort of API. If sessions aren't the way to go, is there any other simplified explanation for authentication?
Ok I want to use google API but for that it need to authorize access to my data: now to do that the I have read the documentation from https://developers.google.com/gmail/api/quickstart/python#step_3_run_the_sample but it doesn't seem to open the window for the authorization and there is nothing in the document stating what you should do ? The script is same as the documentation also it doesn't create a json file
yes
but on clients machine not localhost on server
Hey, can anyone recommend a way to deal with rate limits please? found a couple of decorators but they seems quite bad
you want to get around rate limits, or you want to set rate limits
Hi, can python build a media server? I want to build a video on demand website
this is a rough schema for a messenger website in django,
do you have any suggestions?
(and i know what m2m is, i did it for convinence)
what is the meaning of having "sender" and "delete_for"
will be they not having the same values?
for django if i want to create custom user models do i need to make another app inside the project ?
question: can i have a python-flask web server at my home sever instead upload my proyect to a public server?
do i need something like apache for python?
Yes, make new app to organize ur project.
how do i show two way communication on a website ?
im trying to simulate payment gateway system so i wanna send info from payment gateway to "bank".
something similar to socket programming i guess
guys how do i change the inputted text location on an input feild
like i wana type from right to left instid of left to right
Hello, I have a question about the ScrollY.
Is it possible to have it in % instead of pixel, because when I change of pc it changes and some effects of my site work differently
u a supposed to save dependencies with pip freeze > requirements.txt
when you download your project, you are supposed to reinstall them back with pip install -r requirements.txt
preferably in virtualenv
polluting global venv is bad thing to do if it is your main dev PC
class ProductMovement(models.Model):
movementId = models.AutoField(primary_key=True)
timestamp = models.DateTimeField(auto_now=True)
fromLocation = models.ForeignKey(
'Location', on_delete=SET_NULL, null=True, blank=True, related_name='from_location')
toLocation = models.ForeignKey(
'Location', on_delete=SET_NULL, null=True, blank=True, related_name='to_location')
product = models.ForeignKey(
'Product', on_delete=SET_NULL, null=True, blank=True)
quantity = models.PositiveIntegerField(default=1)
This is my model for product movement, I want to get sum of quantities by filtering toLocation
Can anyone help?
something similar to
ProductMovement.objects.filter(toLocation__name__contains="newyork").Sumof(quantities)
is there a way to create a one to one database relationship in django
yes
Hello, can anyone help me to show a dropdown list from in forms.
does not appear
I think you may need to wrap {{ form.role_field }} in an <option></option tag
I'm not completely sure though
You might need a for tag
I tried this one nothing <div class="mb-4">
<label class="my-1 me-2" for="role">Role</label>
<select class="form-select" id="role" aria-label="Default select example">
<option selected>{{ form.role_field }}</option>
</select>
</div>
how do I paste here as code format. LOL
```html
code
```
okay thanks
Oh, then I'm not sure, sorry
sender is obviously the person who sent the message and delete for is those users that deleted the message like the delete for me in whatsapp
you have a typo in your code, @vernal lotus
Check how you spell field everywhere
for instance "role_filed" in your screenshot
oh yeah thanks
😉
but
so it wouldn't show cause it didn't exist
you corrected the typo and set up the options?
<div class="mb-4">
<label class="my-1 me-2" for="role">Role</label>
<select class="form-select" id="role" aria-label="Default select example">
<option selected>{{ form.role_field }}</option>
</select>
</div>
yes already bro
How can I link an external css file to an html file? I followed what the Django documentation is saying, but it doesn’t seem to get applied
Hey, @vernal lotus I think next thing is looking at the docs it says that choices needs to be a tuple of tuples, and you're passing a list of tuples. Maybe try that change next.
Don't know about Django specifically, but let's say in your HTML template file you'd do this: <link rel="stylesheet" href="/path/to/mystyle.css">
Quick question. I'm going through Corey Schafer's Flask tutorial, and in video 2 he's making a template for each route in his main .py file. My question; is a separate template needed for each route/page, or can a given template be used for multiple routes/pages if necessary/convenient?
video in question: https://www.youtube.com/watch?v=QnDWIZuWYW0
In this Python Flask Tutorial, we will be learning how to use templates. Templates allow us to reuse sections of code over multiple routes and are great for serving up dynamic HTML pages. Let's get started...
The code for this series can be found at:
https://github.com/CoreyMSchafer/code_snippets/tree/master/Python/Flask_Blog
The code snippets...
Totally fine to use same template for multiple routes/pages. You could have a route for "viewcoolthing1" and "viewcoolthing2" have same template but you fetch the content differently.
Thanks!
now it can show. but there is additional character when I put into the option
probably just extra in your template
<div class="mb-4">
<label class="my-1 me-2" for="role">Role</label>
<select class="form-select" id="role" aria-label="Default select example">
<option value=""{{form.role_field}}""> </option>
</select>
</div>
<option value=""{{form.role_field}}""> </option> should be <option value="{{form.role_field}}"> </option>
get rid of the extra around {{}}
done
and now?
here
can you post code somewhere more convenient than screenshots?
pastebin, repl.it, something like that
can you show the code you have now for the field then
okay wait
<div class="mb-4">
<label class="my-1 me-2" for="role">Role</label>
<select class="form-select" id="role" aria-label="Default select example">
<option value="{{form.role_field}}"> </option>
</select>
</div>
and you still see extra characters?
yes
inspect the drop down and see .. something in your choices value might be ending the string early with an extraneous "
even better than inspect, which the browser will attempt to correct, choose "view source" instead to see the raw output
also, I think "role_field" here is outputting the WHOLE select .. you shouldn't need to be so manual with your template
so my guess is role_field has a bunch of html in it you don't expect
okay bro i'll investigate the extra characters.
what is the best way to have a function happen every x amout of time in django?
there is a module called django-cron
Or Celery (or similar) for more time-consuming tasks.
it's not time consuming, it's just I want it to run every hours or so
the actual function takes like 4 seconds to run, cos it fetches some info from elsewhere, and updates it in the db
4 secs is quite a lot; if function fetches sth for external source for me it seems that you should use Celery Beat or separate Python script called by Cron.
Hello,
Anyone can help me with saving a auth_user to different table.
The scenario is somethin like this.
from auth_user there have first_name and last_name then I want to save into User_Profile table and the field is full_name
Here is my views.py
from .models import User_Profile
def save_user_form(request, form, template_name):
data = dict()
if request.method == 'POST':
if form.is_valid():
form.save()
save_user_profile()
data['form_is_valid'] = True
username = form.cleaned_data.get('username')
raw_password = form.cleaned_data.get("password1")
user = authenticate(username=username, password=raw_password)
else:
data['form_is_valid'] = False
context = {'form': form}
data['html_form'] = render_to_string(template_name, context, request=request)
return JsonResponse(data)
Im using flask to make a inventory system. How can i use a variable in a url_for? I want to dynamically change the image based on if a user is logged in or not. src="{{url_for('static', filename='img/ico/workoff.png')}}"
I've another quick question. In Corey Schafer's Flask tutorial (https://www.youtube.com/watch?v=QnDWIZuWYW0), he's set up a main flaskblog.py file with routes inside it that utilize an unique html file as a page template for that specific route (for example; the "about" page's about.html). Each individual route's html file contains extension code {% extends "layout.html" %} that references layout.html, which is where the bulk of the page's html code that builds the pages of the website (I can see why; one main template keeps code DRY and minimize the effort necessary to make changes). I'd like to make sure I understand this: flaskblog.py is going to use route code to access about.html, which extends layout.html, and build a page that's mostly code from layout.html, with an extension from about.html? That 3-step pathway; flaskblog.py--> about.html --> layout.html is the path the computer uses to build the page?
In this Python Flask Tutorial, we will be learning how to use templates. Templates allow us to reuse sections of code over multiple routes and are great for serving up dynamic HTML pages. Let's get started...
The code for this series can be found at:
https://github.com/CoreyMSchafer/code_snippets/tree/master/Python/Flask_Blog
The code snippets...
#main.py
from flask import Flask, render_template
from flask_socketio import SocketIO
app = Flask(__name__)
app.config['SECRET_KEY'] = 'vnkdjnfjknfl1232#'
socketio = SocketIO(app)
@app.route('/')
def sessions():
return render_template('session.html')
def messageReceived(methods=['GET', 'POST']):
print('message was received!!!')
@socketio.on('my event')
def handle_my_custom_event(json, methods=['GET', 'POST']):
print('received my event: ' + str(json))
socketio.emit('my response', json, callback=messageReceived)
if __name__ == '__main__':
socketio.run(app, debug=True,host='0.0.0.0', port=8042)
<!--session.html-->
<!DOCTYPE html>
<html lang="en">
<head>
<title>Flask_Chat_App</title>
</head>
<body>
<h3 style='color: #ccc;font-size: 30px;'>No message yet..</h3>
<div class="message_holder"></div>
<form action="" method="POST">
<input type="text" class="username" placeholder="User Name"/>
<input type="text" class="message" placeholder="Messages"/>
<input type="submit"/>
</form>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.7.3/socket.io.min.js"></script>
<script type="text/javascript">
var socket = io.connect('http://' + document.domain + ':' + location.port);
socket.on( 'connect', function() {
socket.emit( 'my event', {
data: 'User Connected'
} )
var form = $( 'form' ).on( 'submit', function( e ) {
e.preventDefault()
let user_name = $( 'input.username' ).val()
let user_input = $( 'input.message' ).val()
socket.emit( 'my event', {
user_name : user_name,
message : user_input
} )
$( 'input.message' ).val( '' ).focus()
} )
} )
socket.on( 'my response', function( msg ) {
console.log( msg )
if( typeof msg.user_name !== 'undefined' ) {
$( 'h3' ).remove()
$( 'div.message_holder' ).append( '<div><b style="color: #000">'+msg.user_name+'</b> '+msg.message+'</div>' )
}
})
</script>
</body>
</html>
error is it says method not allowed on requested url when i press send
hey I'm doing web development in django and bootstrap and I'm having some issues with my code, do you guys mind if I send it in here. I am new to django so I could use some help
I'm getting this error when trying to access the new model
here is my views.py
here is my urls.py
if you need any more information from me, please ask and I will provide it
i need alot of help haha
Hey trying to make a website with django for my bot, how should one get started with it ?
if anything please tag
you dont need django. you can use and learn django but its hard and difficult to learn because its really systematic. use flask or pyramid to build a website.
hey guys, in flask, if you're using flask_sqlalchemy. How can you store the filtered user class in the session like django.
i have this view
@auth.route('/login', methods=['POST','GET'])
def login():
if request.method == 'POST':
form = LoginForm()
if form.validate_on_submit():
user = Users.query.filter_by(username=form.username.data).first()
if not user:
return redirect('/login')
else:
user.is_active = True
login_user(user)
return redirect(f'/{user.username}/home')
else:
return render_template('login.html', form=LoginForm())
how can i do this
@auth.route('/user')
def userQuery():
return str(user.email)
just seamlessly add the user into the session. do i need to use cookies or somthing and access those? or is there a actual add to session function thats safe
If using Flask-Login, you can get access to the current user(as an object) using the "current_user" variable(accessible both in the routes and templates)
thank you sm man
thanks
Exception Value: Invalid block tag on line 32: 'elif', expected 'empty' or 'endfor'. Did you forget to register or load this tag?``` please some hep me with this error
In template C:\Users\Raghava\Desktop\django_project\blog\templates\blog\home.html, error at line 32
Invalid block tag on line 32: 'elif', expected 'empty' or 'endfor'. Did you forget to register or load this tag?
22 : {% endfor %} {% if is_paginated %} {% if page_obj.has_previous %}
23 : <a class="btn btn-outline-info mb-4" href="?page=1">First</a>
24 : <a
25 : class="btn btn-outline-info mb-4"
26 : href="?page={{ page_obj.previous_page_number }}"
27 : >Previous</a
28 : >
29 : {% endif %} {% for num in page_obj.paginator.page_range %} {% if page_obj.number
30 : == num %}
31 : <a class="btn btn-info mb-4" href="?page={{ num }}">{{ num }}</a>
32 : {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
33 : <a class="btn btn-outline-info mb-4" href="?page={{ num }}">{{ num }}</a>
34 : {% endif %} {% endfor %} {% if page_obj.has_next %}
35 : <a
36 : class="btn btn-outline-info mb-4"
37 : href="?page={{ page_obj.next_page_number }}"
38 : >Next</a
39 : >
40 : <a
41 : class="btn btn-outline-info mb-4"
42 : href="?page={{ page_obj.paginator.num_pages }}"```
you didnt endif the last if statement {% if page_obj.has_next %} on line 34
im getting an error saying TypeError: 'Users' object is not callable
Can you show the code causing the error?
@auth.route('/user')
def userQuery():
user = current_user()
return str(user)
i wanted to get the current user and return it so that it will get rendered
Traceback (most recent call last):
File "C:\Python310\Lib\site-packages\flask\app.py", line 2464, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Python310\Lib\site-packages\flask\app.py", line 2450, in wsgi_app
response = self.handle_exception(e)
File "C:\Python310\Lib\site-packages\flask\app.py", line 1867, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Python310\Lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "C:\Python310\Lib\site-packages\flask\app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "C:\Python310\Lib\site-packages\flask\app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Python310\Lib\site-packages\flask\app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Python310\Lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "C:\Python310\Lib\site-packages\flask\app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Python310\Lib\site-packages\flask\app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "H:\webdev\python stacks\flask\im bored\src\views\auth.py", line 49, in userQuery
user= current_user()
File "C:\Python310\Lib\site-packages\werkzeug\local.py", line 375, in <lambda>
__call__ = lambda x, *a, **kw: x._get_current_object()(*a, **kw)
TypeError: 'Users' object is not callable
the Users object is my user's credidentals orm class
current_user is an instance of your User class so you can't call it as a function. Instead
return current_user
oohhh okay gotcha. that works just fine
thank you mateeee
its hard finding information about flask and its extensions
Usually, you can google the extension and you'll find its documentation at a url like <flaskext>.readthedocs.io
oh yeah ik about the docs
i just didnt read it properly
its just that
it didnt give much information on how the flask_login.current_user works or what it really is in reality
like the docs dont tell anything about how it can be used
it simply says " a proxy for the current user"
Yeah, I get you. The extensions docs can be tricky sometimes
Hi all,
What visual studio code extensions are good to install for coding node.js?
Thank you @swift wren
But I get this error now please some one help me Reverse for 'user-posts' not found. 'user-posts' is not a valid view function or pattern name.
Hey @buoyant geode!
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:
it quite litrally says it there
'user-posts' is not a valid view function or pattern name
where did you write user-posts
carefully check and make sure you spell it correctly
so that it matches with the url or view that you created
also why are you using django
there's no point unless there's money on the line
thanks started yesterday , thanks very much
Thank you @swift wren Im just learning django for backend development started recently
how do you pass two arguments to a Jinja filter:?
just add another /
Hi all, I am trying to build a django web-application where I need to create a PDF invoice using a template that I created in excel. Now I can't convert and display it unsing django. Please Help
Ok I am new web development, I am getting this error while using flask jinja2.exceptions.TemplateSyntaxError: expected token 'end of print statement, got for css file div {background-color: #1e1e1e;} and html code <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>PlayGames</title> <link rele="stylesheet" type="text/css" href="{{url for('static', filename='style.css')}}"> </head> <body> <h1> Hello world </h1> <p> python! </p> </body> </html> how do I solve this error
please tag to reply
<link rele should be <link rel
same error
should be url_for not url for
thanks but why does it give the desired background ? I am sorry
because your HTML does not have no div
try:
<div class="home">
<h1> Hello world </h1>
<p> python! </p>
</div>
style.css
.home {
background: red;
}
thanks but is doesn't seem to work it should have a background color
check debug console
see if there any errors on /style.css
should be returning a status code of 200
it returns the code: "GET /static/style.css HTTP/1.1" 404 what does that mean
It means that your flask server isn't able to find the requested file
Check that you entered the correct location of the file and restart the server
Ok what I actualy had to do was specify using {{url_for('static', filename='style.css')}}
what is server side rendering? Generate pieces of html and send to front-end which requests them using js or something? Hybrid SSR SSG?
Thank for all your help @muted scaffold and @past cipher
which is better? Gatsby or Next.js? 😄
i would ask about python, but it doesn't work in browser. Idk where I should start with react, and what kind of a toolchain i should pick. I'd rather get it right, since assumably it's a pain to change it afterwards?
normally frontend frameworks would run on the browser and generate HTML
SSR -> do this on the backend
so, basically
Does someone know whats this? Some friend posted it to me (ping me thx)
guys, any idea on how i would make a flask app that can get a discord.py bots data in a seperate app? i guess some kind of discord api
so i have something like ```py
def apps(client):
myapp = Quart(name)
def init(self, client):
self.client = client
@myapp.route("/")
async def home(self):
print(self.client)and i need client in home, but im getting an error TypeError home() missing 1 required positional argument: 'self'```
how would i be able to use self in home?
anyone know how to fix this please => from Occupy.models import Clique
ImportError: cannot import name 'Clique' from partially initialized module 'Occupy.models' (most likely due to a circular import)
OSError: [Errno 98] Address already in use
i ran flask run and then suspended it by pressing ctrl+c
but when i try to run again i get this error
this should probably help:https://stackoverflow.com/questions/34457981/trying-to-run-flask-app-gives-address-already-in-use @next vessel
idk why this err is coming
Ok I want to add a background color using css only to a image, the image should be on the left side but it gives me this,. HTML code: <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>PlayGames</title> <link type="text/css" rel="stylesheet" href="{{url_for('static', filename='style.css')}}"/> <div class="home"> <marque><image src="{{url_for('static', filename='image/Logo.png')}}" width="200" height=auto/></marque></left> </div> </head> <body text="red"> <p>hello</p> </body> </html> css file: .home{background-color: #1e1e1e; margin: auto; width: 800px; }
you have to py await self(result) not the other way around also Only asynchronous (defined with async def) functions can be awaited. Whole idea is that such functions are written special way what makes possible to run (await)
@native tide
app = Flask(__name__)
@app.route("/")
async def home():
return "Hello! This is the main page <hi>HELLO<hi>"
if __name__ == '__main__':
app.run(debug=True)```
the code is this
@royal quail
do ```py
from flask import Flask
app = Flask(name)
@app.route("/home")
async def home():
return "Hello! This is the main page <hi>HELLO<hi>"
if name == 'main':
app.run(debug=True)``` go to your port and do /home at the end it should return but if you default page to be that then don't change anything I have run the file form my side it works perfectly fine here:
ok can you tell me what output your getting it the terminal, It should be like this
@native tide
@royal quail bru my mom took my laptop I'll try tomorrow and say...
ok
Hey, in which cases is python better for web dev then lets say javascript?
it's hard to make a claim about the whole python language compared to the whole javascript language. it depends on what you want to build, which web framework you want to use, etc.
Ok, so in your opinion there are no advantages to be pointed out
I mean like there has to be something that really sets python a part from the whole node.js/react.js stack when it come to WEB DEV
for me there are plenty advantages but it's mainly related to the language itself (exceptions for type problems, ecosystem ...) and the django framework being a brilliant choice, but there's no real advantage of one language over the other for the entire web dev stack, apart from perhaps javascript working in frontend and backend so you need to learn one language less
Yeah well that was my point, it seems like its all too good to be true with JavaScript, so why would anyone or any company choose to build with python and javascript when they could just go full on JS
that was my initial dilemma anyway since I am a beginner its a bit confusing you know
When it comes to choices like that I can't reason correctly - since I am new to coding in general
you're in a python discord so people will probably be partial to python/django/flask here. I like these things too but I think going full js makes a lot of sense
That being said, I've never used node in the backend and work full time as a web dev using django
There is no chance in hell I will leave python for JS, I am only asking this kinds of questions to know upfront how to manage my career in the future because I plan to only work with python, i tried JS and it is not good for me (i don't wanna use stronger language)
the only thing i like is python so I am like now eliminating all options that will get me to mandatorily learn other languages
maybe its not a good approach and narrow sighted but hey thats me I like what I like and its python and I don't like what I don't like and that is other languages... 😛
Once you get more comfortable with python you may find yourself less averse to learning a new language. And it will be pretty hard to get into web development without getting familiar with javascript
Trying to learn many languages as a beginner would be pretty hard though, I think.
Yeah I get it, but I have a clear and very precise goal set for me
and that is to learn as much python as possible and to get paid $2.300 a month remote job and thats it, there is no javascript for me, no need, Im not after 100k/year jobs or buiding my webb aps or react native mobile apps etc.. im a simple person 😄
what will your day-to-day look like in your end goal role
@app.route("/dashboard")
async def dashboard():
if not await discord.authorized:
return redirect(url_for("login"))
even if i am authorized i am still getting redirected to login but why and i am using heroku is that the reason?
help!
get up open pycharm write python code get paid $550 per week, i own my place so no rent so that money is really good for me in this cheap country in east europe
no particular field/sector/niche in mind?
whatever pays me that $550 per 40 hour week without asking to learn another language kind of niche 😛
Idk what that is yet but things always end up nic
fair enough
anyone know how to fix this ??? django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency Occupier.0001_initial on database 'default'.
sounds like a pretty new database, are you fine just recreating the db and rerunning your migrations?
not sure how these happened out of order though..
hello why I am getting this error?
django.db.utils.ProgrammingError: relation "manage_user_customuser" does not exist
LINE 1: ...pp", "manage_user_customuser"."is_superuser" FROM "manage_us...
I am going to create superuser and it cannot
class CustomUser(AbstractUser):
is_level3appsupp = models.BooleanField(default=False)
is_sysdbad = models.BooleanField(default=False)
is_compops = models.BooleanField(default=False)
is_level2supp = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=True)
I want to get around (apologies for the late reply!!)
How to register user without password then send email password
Generally that is bad practice, if you want passwordless you'd be better off implementing 2fa system i.e. Google authenticator
still the same err
a random string you mean?
Anyone learning or new to Django and want to learn together? Maybe do a small project or two?
there are no err though
Hey do you think I need to know class based views before learning django rest framework?
you could remove a bit of them with
class="div-1 div-2" and e.t.c.
multicomibining into one
I know
But I need different attributes for each one
CSS is fun btw
then a bit of proper templating jinja2 blocks
Looking for a flask developer: We are planning to take part in Data Day Hacks on the 8th of October weekend. We are 2 people already- we have worked on ML web apps beforel, and we know ML. We plan to build a ML web app. PM me if you'r interested and you know flask.
What’s that?
copy paste from official jinja2 guide: template inheritance
base_template.html
<!DOCTYPE html>
<html lang="en">
<head>
{% block head %}
<link rel="stylesheet" href="style.css" />
<title>{% block title %}{% endblock %} - My Webpage</title>
{% endblock %}
</head>
<body>
<div id="content">{% block content %}{% endblock %}</div>
<div id="footer">
{% block footer %}
© Copyright 2008 by <a href="http://domain.invalid/">you</a>.
{% endblock %}
</div>
</body>
</html>
child_template.html
{% extends "base.html" %}
{% block title %}Index{% endblock %}
{% block head %}
{{ super() }}
<style type="text/css">
.important { color: #336699; }
</style>
{% endblock %}
{% block content %}
<h1>Index</h1>
<p class="important">
Welcome to my awesome homepage.
</p>
{% endblock %}
thus we separated one thing into two files
{% block head %}
{{ super() }}
<style type="text/css">
.important { color: #336699; }
</style>
{% endblock %}
first {% %} opens section to declare inheritance
{% endblock %} ends the section
everything in between is inserted into base template
{% is a... function def sort of for jinja2, {% endblock is a return from function
Anywhere I can read more about it?
Does this have something to do with Python?
directly
all python frameworks have it enabled by default
plus some javascript frameworks have it similiarily too (Svelte)
Oh. Sorry for being a noob, I’m just starting out with html …
no worry. everybody starts one day
it was not like I was any better when I just started
hell, I am still everywhere just starting
going to be k8s noob soon
kBs?
DevOps tool for coolest application deployment
Oh.
I will be able to update application with zero-down time, and scaling application between multiple servers with zero downtime
or just replicating app between servers, and having controller whatching them being alive, replacing with another replica if it died
yes
You can use Python(Jinja2) with Html+CSS + with limited simpliest javascript
as a more enterprise solution....
Python is used as a REST API that returns JSON data
and for frontend u use proper frontend framework with HTML+CSS+Cool javascript level
and just fetch data from your python frameworks with requests for json data
you can make html button with only HTML+CSS
I’m talking about functionality
for simple solutions python framework would be enough
Ok.
frontend framework is wished when you use javascript extensively
it is just better way to use javascript
Btw, just a random question: are there any Python UI libraries that I can design stuff using CSS?
I heard PyQt can do that, but I’m not sure…
not knowing, I am going only to start using desktop stuff soon
Oh, ok.
Could anyone make an estimate on how long it would take to develop a MU* game engine?
MU* meaning like a mud, a text based game that works on text input in a web browser.
I am an intermediate programmer, self taught, and it's quite an ambitious goal because my skill level isn't quite there to make something that complex, but it's my passion and I want to try.
Hey @haughty kettle!
It looks like you tried to attach file type(s) that we do not allow (.js). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a.
Feel free to ask in #community-meta if you think this is a mistake.
why
console.log("js is alive")
function Magic() {
Cookies.get('x')
//gets the cookie named x
let clicks = Cookies.get('x')
//variable called clicks is made
clicks++
//clicks+1
document.getElementById("number").innerHTML = clicks;
Cookies.set('x', clicks, {
expires: 700000000000000000000000000,
path: '/'
});
//it is saved
if (clicks == 10) { alert("You are a begginer clicker") }
if (clicks == 100) { alert("you are a pro clicker") }
if (clicks == 1000) { alert("you are a tired clicker") }
if (clicks == 10000) { alert("never gonna give up") }
if (clicks == 100000) { alert("how") }
if (clicks == 100000) { alert("really if you reach 10,000,000 i will change your score to 0") }
if (clicks == 10000000) { Cookies.remove("x", { path: '/' }
)}
}
var x = setInterval(weird, 3000)
function weird(){
Cookies.get('x')
let clicks = Cookies.get('x')
console.log(clicks)
if (clicks > 1000) {
clicks++
document.getElementById("number").innerHTML = clicks;
Cookies.set('x', clicks, {
expires: 700000000000000000000000000,
path: '/'
});
}
}
var x2 = setInterval(weird2, 1000)
function weird2(){
Cookies.get('x')
let clicks = Cookies.get('x')
console.log(clicks)
if (clicks > 2000) {
clicks++
document.getElementById("number").innerHTML = clicks;
Cookies.set('x', clicks, {
expires: 700000000000000000000000000,
path: '/'
});
}
}```
function taxes(){
console.log("Sorry,But now you got taxes")
clicks-100
}
var x3 = setInterval(weird3, 100)
function weird3(){
Cookies.get('x')
let clicks = Cookies.get('x')
console.log(clicks)
if (clicks > 5000) {
clicks++
document.getElementById("number").innerHTML = clicks;
Cookies.set('x', clicks, {
expires: 700000000000000000000000000,
path: '/'
});
}
}
function double1(){
if(clicks>100){
Cookies.get('x')
let clicks = Cookies.get('x')
clicks++
document.getElementById('d').remove();
getElementById("number").innerHTML=clicks;
Cookies.set('x', clicks, {
expires: 700000000000000000000000000,
path: '/'
});
}
}
//it is logic you musy understand
//this file is tottaly made by myself```
help im getting errors
(context REACT)``` js
let [drones, set_drones] = useState([]);
let [goingUp, setGoingUp] = useState(false);
let nextUrl = null;
let get_drones = async () => {
let response = await fetch(http://localhost:8000/drones/?limit=4);
let data = await response.json();
nextUrl = data.next;
set_drones(data.results);
};
let handleScrollBottom = async () => {
if (window.innerHeight + window.scrollY >= document.body.offsetHeight) {
// you're at the bottom of the page
if (nextUrl !== null) {
let response = await fetch(${nextUrl});
let data = await response.json();
nextUrl = data.next;
// let allData = drones + data.results;
// set_drones(data.results);
// console.log("next data", ...data.results, data.results);
}
}
};
useEffect(() => {
get_drones();
window.addEventListener("scroll", handleSc
rollBottom);
}, []);```
how to add the new json dict in drones variable i am doing the infinite scroll with pagination and it send me next url so that i can sent new GET request
django anyone?
@stark tartan I think you can do
set_drones(prev => [...prev, ...data.results])```
Hi, I'm using Django and have a social media platform where there are posts by users
Users can react to posts, every time there's a reaction I send a notification out
If the post is liked once
example: A liked your post
I don't want to send a notification again if A decides to unlike and like it or A unlikes it and someone else likes it
Do I store an extra field in the model as first_notification - boolean?
I wasn't sure if this is the best way 😅
yee
this part isnt very clear
Try rephrasing it maybe
do you know how to change my django default error?
Oh okay
User A made a post
Now user B liked his post I send a notification to user A that "User B liked your post"
But if user B unlikes it and likes it again I don't want to send the same notification again and spam the user
Can anyone suggest me how can i implement "video calling features" where user can record screen and take screen shot?
I was searching some API to integrate with my django project.
oh im terrified if i delete the DB something worse would happen
anyone has idea on serverless deployment using zappa
i need some help
I made one of these as my first foray into python. It is a very large undertaking. It depends what you want to accomplish.
I want to make a mu* to the fullest.
Has anybody tried showing a nested serializer in a view?
Django keeps telling me the field in the serializer doesn't exist
i did the deployement using the zappa flask applications @brave stag
i'm getting
botocore.exceptions.ClientError: An error occurred (AccessDenied)
Any idea about this?
issue related to s3 access and deployement , in aws you will find the aws deployement role add them to your IAM user then it will be solved @brave stag
this will help you https://www.codingforentrepreneurs.com/blog/aws-iam-user-role-policies-zappa-serverless-python @brave stag
Btw is ListAPIView even appropriate for nested serializers?
is this normal?
im following a flask tutorial right now and the guy doesn't have any errors but i do
That looks like a warning where each class must be spaced by 2 lines
Though you can fix those issues using a formatter like black
it says its an unexpected argument, im not sure what's wrong
im following the video to the dot seems to work the that guy
yeah you could set a variable "interacted = True" once userB interacts with the post, and set the condition that if interacted = True dont send the notification
Lg you can have a look on WEB RTC from Google API
It's a fun project, so good luck!
anyone know a responsive mit license chat app template? i could not find it
how do webservers handle multiple requests at the same time? do they have multiple instances of the same program?
well. they talk to the socket. so you have to use somethign like uwsgi, gunicorn etc
I think generally a childprocess is spawned when a request is received.
im sorry idek what those are
when will the memory be freed up?
I don't have enough experience with this sorta stuff to help you with that
ill try
i.e. point nginx and it and run your flask app with it or something
you will lose a few weekends and a lot of hair
think of it as php-fpm
actually im storing a file as BytesIO but not deleting it in any part of my program even if its useless after the request has been served... will i need to delete it from memory the child process u mentioned terminates?
or will it hog up the memory lol
uhh wot
nah dw i will look into it
In not sure, but afaik if you use memory in a child process and then that child process gets killed it should clean all used memory up
its that easy in a way. but ramps up. i.e. you have to pass logs through it
how does it know when to kill the child process
you kill it
wat
or it kills itself once it's done
ye there's even settings for that
the config can get big.
there's weird names for params
voodoo stuff
doesnt Flask handle all that
na uwsgi. id stick with that. its easy. there's others. gunicorn.. lots i think
plus asgi is coming in now due to async
but uwsgi is a good place to start
Flask idk, but I was responding to your more general 'webservers' question ;)
I've never used flask
sorry
ye. it's like that at first. then you know
no no its not your mistake
and you have to help others
thats how u learn ig
so really you will start with this
uwsgi --http :9090 --wsgi-file foobar.py
but it will get long with lots of params
so you will need the config file
myapp.ini
and just pass it the config
then you have a service which starts it on boot
so you can just kill that service if you want. or restart it. like you would nginx
then in nginx. you create a reverse proxy. and point it to the socket that uwsgi makes
there's lots of tutorials online
to start. find a good tutorial and copy and paste.
do that for about a year each time you need to run an app. and some bits will start to fall into place
well currently i just want to know what happens in the backend of backend and to know if Flask handles all that
is flask async yet?. try sanic
kinda. it's hard to answer that
you tried sanic?
hmm, thanks for the recommendation
Can anyone suggest me how can i implement "video calling features" where user can record screen and take screen shot?
I am trying to do it in my django project
in python, flask, how can i increase the session expiration time?
i need the webpage to be "live" at least 1 hour or 2
Heyo I needed some help with APIs, I am not sure how to access an API even though I am looking at it's networking panel. Some help would be appreciated. I can dm them the image of the network panel
i need help
if (clicks >= requiredclicks){
document.querySelector("#levelupbtn").style.visibility = "true";
}
else{
document.querySelector("#levelupbtn").style.visibility = "false";
}
why doesnt that work
true and false are not valid values for the visibility property.
https://developer.mozilla.org/en-US/docs/Web/CSS/visibility
ty
What do you mean by "live"? Can you elaborate?
you mean once u close the program u want it to still be running?
there is an internal clock that stop a webpage to continue working and send you to login again, i need to increase that time to 1 or 2 hours instead 15 minutes
could be session time but i am not sure
Can you expand on "continue working"?
My understanding right now is a user logs in, 15 minutes later they refresh the page and is logged out. You don't want them logged out after this 15 minutes.
Thanks a lot
it worked
but I'm getting a new error now
Status check on the deployed lambda failed. A GET request to '/' yielded a 502 response code.
any idea how to solve this?
scenario:
i login, then have a 30 minutes meeting, page ask to login agan so i login agaain
other meeting for 30 minutes ... and login again
work for 2 hours, excellent, no problem
lunch an login again
phone for 20 minutes and LOGIN AGAIN
if i increase that time to 1 hour i just need to login 1 time that day
is it possible?
myjs.js:22 Uncaught TypeError: Failed to set the 'max' property on 'HTMLProgressElement': The provided double value is non-finite.
at HTMLImageElement.doonclick (myjs.js:22)
var level = 1;
var multiplier = 1;
var levelplusone = level + 1;
var prestige = 0;
var clicks = 0;
var rebirth = 0;
var requiredclicks = level * 250 + multiplier * 50;
let l = document.querySelector("#progresslabel > label");
l.innerHTML = "Progress to Level " + levelplusone;
let levelupbutton = document.querySelector("#levelupbtn > img");
document.querySelector("#cookieimg > img").addEventListener("click", doonclick);
let progress = document.querySelector("#progress > progress");
function doonclick() {
level = localStorage.setItem("level", level)
clicks = parseInt(localStorage.getItem("clicks")) + multiplier;
console.log(clicks);
console.log(requiredclicks);
progress.value = clicks;
progress.max = requiredclicks;
localStorage.setItem('clicks', clicks);
if (clicks >= requiredclicks){
document.querySelector("#levelupbtn").style.visibility = "visible";
}
level = parseInt(localStorage.getItem("level"))
}
function loaddata() {
console.log("Loading Data...");
if (!localStorage.getItem("clicks")) {
localStorage.setItem("clicks", 0)
}
clicks = parseInt(localStorage.getItem("clicks")) + multiplier;
level = parseInt(localStorage.getItem("level"))
progress.value = clicks;
requiredclicks = level * 250 + multiplier * 50;
progress.max = requiredclicks;
console.log("Success!");
if (clicks >= requiredclicks){
document.querySelector("#levelupbtn").style.visibility = "visible";
}
else{
document.querySelector("#levelupbtn").style.visibility = "hidden";
}
}
function clearalldata() {
localStorage.clear();
}
function levelup() {
}
i get error
myjs.js:22 Uncaught TypeError: Failed to set the 'max' property on 'HTMLProgressElement': The provided double value is non-finite.
at HTMLImageElement.doonclick (myjs.js:22)
Uncaught TypeError: Failed to set the 'max' property on 'HTMLProgressElement': The provided double value is non-finite.
at loaddata (myjs.js:40)
at onload ((index):7)
Are you using any extensions that handle login and authentication?
Somewhere in that code you're setting NaN to the progress' max and/or value. NaN is not a finite value. You might want to check whether you're actually setting a Number!
someone please help => django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency Occupier.0001_initial on database 'default'.
has anyone used ratelimiter lib and had any issues with ```py
@RateLimiter(max_calls=1, period=1)
?
this dosnt seem to do anything
yes, and session, cookies, encryption ant stuff
Never used it but your syntax does look correct. And that's right before the function that is being called a lot?
You don't want to decorate a function that itself is going and making a bunch of calls, that won't do anyting.
This will only rate limit your function from being called too frequently.
So in your logic, make sure the function to do the fetching against the API is the one decorated. This won't work around a function that itself is the thing setting up a loop to do calls as fast as it can.
Understand what I mean?
cool
within my function, the calls were doing during a loop
as I was decorating the function, it wasnt applying to the calls within the loop
ah yeah, you want to move whats in that loop to a func itself and ratelimit THAT
from ratelimiter import RateLimiter
rate_limiter = RateLimiter(max_calls=10, period=1)
for i in range(100):
with rate_limiter:
do_something()```
ah yes, with the context managert
this is what I had to do, and what worked
great
🙂 thanks for getting back to me though!
you could also decorate do_something()
at its def
you're welcome! glad you figured it out
from . import views (what does the . mean here)
does have experience working with SSO in Django?
I've Flask which doesn't have the same tight coupling with the database, and just created an sqlite file backed database for a very small app, but is there a more elegant way to handle SSO users?
I don't know django. Wouldn't you use SAML for single sign-on?
Anyone looking for a coding buddy? To motivate each other to code and not give up
I do use SAML.
I'm really just talking myself through this question.
Can you store Django users in a cookie based session without messing up the admin backend, which I thought relied on the Users table for reasons.
Relative import, from where your project is running.
"The dot (.) symbol after in an import statement of the form from . import your_module is a Python syntactical element for relative imports. It means “look for the module in your current folder”. The current folder is the one where the code file resides from which you run this import statement."
What's the extension? Maybe there's a way to set it via the extension.
Someone from stackoverflow showed me this benchmark comparation https://www.techempower.com/benchmarks/#section=data-r20&hw=ph&test=db&c=e, Are python web frameworks bad for web applications?
short story: no
the longer story: yesn't kinda,....
python simply is not as performant as some other languages, this is due to a lot of reasons but that is not really important here, however what python has is an extremely large ecosystem of libraries to help with web applications, especially apis where the raw performance has a negligible impact on real world performance
not to mention the speed of development you get with python compared to languages like cpp or rust
there's a good reason why python is used extensively in the backends
that said, you probably dont want to use python to serve static files
plus. most web apps aren't especially cpu bound
and if they are, you can usually offload that stuff to something more performant

hello sorry to ask ask stupid questions but after hours and hours on tutorials and youtube I want some insights from actual python django programmers for example:
I want your opinion - if you were to tell a total newbie how to learn django on step (10) and step (1) was to learn lets say python variables and data types, what would you say steps 2-9 would be please your own words and insight it'd mean a lot to me
Hello,
Anyone knows Scrapy ?
Hi, I'm trying to implement hashtags in my django app
I have a message model with a field like this
And this is the HashTag model
hash_tag = models.CharField(max_length=140, primary_key=True)
And I'm setting the hashtags to the message like this
hash_tags_list = Functions.extract_hashtags(message["message"])
hash_tags = [HashTag.objects.get_or_create(hash_tag=ht) for ht in hash_tags_list]
messageObj.hash_tags.set(hash_tags)
messageObj.save()
But this errors out
django.db.utils.IntegrityError: insert or update on table "messaging_message_hash_tags" violates foreign key constraint "messaging_message_ha_hashtag_id_068959e9_fk_messaging"
DETAIL: Key (hashtag_id)=((<HashTag: HashTag object (skills)>, True)) is not present in table "messaging_hashtag".
Tho I can find the HashTag object (skills) in my messaging_hashtag table
Been stuck with this for a while now :/
django error has anyone seen before?
been trying to fix it for 3 hours... finding right locations for all the templates and indexs etc....
Fixed with this
hash_tags = [ HashTag.objects.get_or_create(hash_tag=ht)[0] for ht in hash_tags_list ]```
get_or_create returns a tuple which contains the object and a flag on whether the object was created or not, so something like: (obj, created)
Hi, there is Scrapy dev or expert !?
How do I give an image a variable name? and use it in CSS and change the width and height?
anyone know
Hey can someone suggest a site or YT vid where I can learn Django?
I would suggest the official tutorial. https://docs.djangoproject.com/en/3.2/intro/tutorial01/
also a pretty good blog for Django stuff: https://simpleisbetterthancomplex.com
Thx I had to make a project using django
I watched mosh but his tutorial didnt help much if at all
I honestly find most videos aren't helpful compared to reading and doing, unless they're stuff like conference talks
TIL django is multithreaded by "default" that's cool
Anybody has any example on how to make a one-to-many serializer on DRF? Mine keeps saying the "many" field isn't recognized
In my case, suppose you have those:
class Album(models.Model):
album_name = models.CharField(max_length=100)
artist = models.CharField(max_length=100)
class Track(models.Model):
album = models.ForeignKey(Album, related_name='tracks', on_delete=models.CASCADE)
order = models.IntegerField()
title = models.CharField(max_length=100)
duration = models.IntegerField()
class Meta:
unique_together = ['album', 'order']
ordering = ['order']
def __str__(self):
return '%d: %s' % (self.order, self.title)
I'm serializing borth
But in my case, the tracks field isn't recognized
Don't let that fool you. It's a monolith. There's a GIL. don't use it for everything. i.e. run crons as separate python files don't go using the management commands and blocking your admin users
class TrackSerializer(serializers.ModelSerializer):
class Meta:
model = Track
fields = ['order', 'title', 'duration']
class AlbumSerializer(serializers.ModelSerializer):
tracks = TrackSerializer(many=True, read_only=True)
class Meta:
model = Album
fields = ['album_name', 'artist', 'tracks']
anyone know of a responsive mit licensed chat template? i need it for a chat app but can't find one
I don't know why the serializer can't accept new fields
The code you have shared looks ok, how are you trying to use the serializers?
I have a custom serializer for each of them but idk what type of view I should use
If it's ListAPIView or something else
The view you choose is dependent on what you actions you want to be able to do with the serializer. This is a helpful reference if you haven't come across it before: https://www.cdrf.co/
The best way to understand Django REST Framework class-based views and serializers is to see it in Classy DRF (based on CCBV), so pick your version and jump in at the deep end.
Hello, everyone where i can ask a question about django python framework?
I need help with tampletes
Hi guys. I just picked up Flask. Now I'm racking my brain on how to make radar chart in Flask. Last few months I did picked up Dash. Should I use these two together? Or is there any other options? Any pointers?
so i wanted to host my app on pythonanywhere and the thing is it works when i launch it from vscode but it doens't wanna work on their server
here's the one im launching from my local pc
their's
anyone here please
2021-09-29 12:38:57,545: Error running WSGI application
2021-09-29 12:38:57,546: ModuleNotFoundError: No module named 'flask_app'
2021-09-29 12:38:57,546: File "/var/www/ewalaureatnh_pythonanywhere_com_wsgi.py", line 16, in <module>
2021-09-29 12:38:57,546: from flask_app import app as application # noqa
Hi, I have a question. I create a website with html and css. Does anyone know how I get a game I made with html5 on this website? 🙂
I have a video blob in javascript and i am working on django server.
How can i compress my video blob in front end and then upload to django
Gamemaker studio 2.3
By using this you can add
I dont have that.
Did you make a game or want to make a game for html5 platform
i have already maked a game
i have a html5 file rn
Hire a front-end developer
umm I am trying to type
py manage.py runserver
but it shows [Errno 2] No such file or directory
Any fixes?
its very obvious
there is no manage.py file in your cwd
so make sure you cd to it
and how we do it(I have no idea in web development)
To add on to this, if it's list or detail view then the serializer should work. However, if you're trying to make a Patch, post or put request, I'd recommend using a different serializers that has all fields without defining serializer method field.
its not web dev but basic computer literacy (for a programmer)
when you execute commands in terminal they are run in a directory called cwd
so the command py manage.py runserver you are telling python to run manage.py file present in the cwd with a command line argument runserver
ohk
are you on windows or linux?
windows
do you know how to open cmd in a directory?
yea
I see
then run the command again
it worked thx
So i have this in django:
2 dbs, db A have the user, groups etc of django, db B have some other data
2 apps, app A only hace acess to db A and app B only have acess to db B
In app B i want to block some views depending on the user using a decorator.
Problem: app B doesnt have acess to db A that have the users info
can i route this somehow through app A?
Hello everyone, i want a solid tutorials to builds rest api with django
anyone have idea on serving django static files using zappa
@brave stag 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!
Any advance ideas for Website (Django project )
How about a tool that you need.
Should be able to use tokens for this.
Big reason for tokens is for sharing access to multiple platforms/services.
you question is too vague
i think i'm missing something in code, nvm
imma check again and if i get the same error i'll post it here
what does meta charset does in html
are you referring to <meta charset="UTF-8">? It specifies the encoding. It's always utf-8. https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta#attr-charset
it tells the browser how the html page is encoded
when it comes down to it, html is just a bunch of bytes
im new to html so ;-;
well what does it change
if i put it or not
i know its a character set but i dont understand why
or whats its concept
if you leave it your browser tries to figure out the encoding from the response headers and then falls back to a default
which I think is usually utf-8
i dont understand what u said right now ;-;
it usually won't change anything whether or not you include it
I think 99% of everything web related is going to use utf-8
got it
I have two models: Application and ApplicationFiles
Application has many Application Files.
On Application Page there are multiple application files associated to that application. On Detail Page i just want to delete some specific application file. It deletes the file but redirect is not working. Anyone here for help?
Views.py
class ApplicationFileDeleteView(LoginRequiredMixin, View):
def post(self, request, *args, **kwargs):
ApplicationFile.objects.filter(id=self.kwargs['pk']).delete()
return redirect('applications:application', pk=self.kwargs['application_id'])
Urls.py
app_name = 'applications'
urlpatterns = [
path('new/', ApplicationCreateView.as_view(), name='new'),
path('applications/', ApplicationListView.as_view(), name='applications-list'),
path('applications/int:pk/', ApplicationDetailView.as_view(), name='application'),
path('applications/int:pk/update', ApplicationUpdateView.as_view(), name='application-update'),
path('applications/int:application_id/files/int:pk/delete/', ApplicationFileDeleteView.as_view(), name='attachment-delete'),
]
How can I see which button was clicked?
hi guys. I'm having trouble improving myself. I learned most topic about python but it's like I can't go forward. I deciI need a mentor .
So ı've decided ı need a mentor. Is there anyone who can help?
My choice django or flask is better for me
simply put
text is internally a lot of binary
an encoding is how to turn that binary into human readable letters
hold up let me get an example
okayy ty btw
so like 🔥 in UTF-8
is ð¥ in ASCII (an older encoding)
in binary they are the exact same
just a long chunk of 0s and 1s
most everything uses UTF-8 nowadays
so what does it change?
basically.
IF you were to change the encoding manually you’d see something different
but for the web it’s mostly a curiosity nowadays
so pretty much putting meta charset utf8 is like just translating it into normal words
thats all
kiiiind of?
a complete answer would go into the history of encodings, but that’s the gist of it
thanks for explaining this to me ;-;
em can i dm u in the future if i needed something to understand
in html
nope, sorry, don’t do DMs
just ask here or in #❓|how-to-get-help
okay thanks
oh yeah ur a helper i didnt see ;-;
helpers dont accept dms
hope u have a good day
you too! 👋
Hey @foggy bramble!
It looks like you tried to attach file type(s) that we do not allow (.mkv). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a.
Feel free to ask in #community-meta if you think this is a mistake.
Can you share what you have and where you want to detect which button was clicked?
Does Django share any state between requests? I assume it's multi threaded running w/ gunicorn or w/e. Would I run any into issues with different threads accessing the same object from a factory function?
do I figure out how to make a thread safe singleton or just eat the cost of recreating an ldap connection for each request
the core ldap3 instance appears to be thread-safe when using a certain connection strategy, so I think it's just my wrapper class I'm worried about
you mean, Django itself?
then yes
seems like it's mostly mitigable
but you wouldn't have to worry about that, right
only about your own thread safety
Has anyone secured a FastAPI app with just an API key rather than something like OAUTH?
https://git.pydis.com/pixels does that (the API key is provided after Discord OAuth, but you don't need to do that, that's a project specific thing)
Hey everyone, I am trying to set up a development environment for building HTML/JS and my goal is to mirror the service I want to upload my HTML/JS code to but they use template rendering variables like
@customer.full name@
and I cant for the life of me figure out how to get this to work on a http server set up with python. The closest I got was Flask & Jinja with a custom variable start and end string but that wont let me put spaces in the variables. Does anyone have any idea how I can accomplish template rendering with spaces in the variable names using a python http server?
It's not as documented as it should be. https://github.com/tiangolo/fastapi/issues/142#issuecomment-563274226
wym by "dont use it for everything"?
why do you have spaces in variable names? that only leads to pain.
I am not the one who put them there, the web application I am using will pass variables into the HTML / JS file and the variables from that application use spaces. I am trying to mimic the environment so I can easily copy my HTML / JS files up to it without having to replace variable names
I reread your question, sorry, I get it now. Uh are the spaces consistent?
All I can imagine is tempale your things w/ Jinja and do some custom string interpolation/replacement.
I seemed to maybe have figured it out using the chevron module (a mustache implementation for python)
but it feels a little janky lol
I may have figured it out using the chevron module (an implementation of mustache for python) and using that to load a file and pass it back to flask but it feels a little janky
hey need help with scss in django
what does this do in html
<meta name="" content="">
for example like what
<meta charset="UTF-8">
<meta name="description" content="Free Web tutorials">
<meta name="keywords" content="HTML, CSS, JavaScript">
<meta name="author" content="John Doe">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
when you search something on google the crawlers usually crawl this meta section and rank according
wlc
in flask, we use request.form.get() to get the value of a POST request. what is the equivalent of that in Quart? cause it looks like that .form is a corutine and doing get on it raises :TypeError: 'coroutine' object is not iterable
<td>
<p id="2"></p>
<script>
var d = new Date();
var weekday = new Array(7);
weekday[0] = "<img src="Butter.jpg" width="250">";
weekday[1] = "<img src="" width="250">";
weekday[2] = "<img src="" width="250">";
weekday[3] = "<img src="" width="250">";
weekday[4] = "<img src="Chiffon.jpg" width="250">";
weekday[5] = "<img src="" width="250">";
weekday[6] = "<img src="" width="250">";
var n = weekday[d.getDay()];
document.getElementById("2").innerHTML = n;
</script>
</td>```
I can't get the images to appear for some reason
can someone direct me to a flask course for free?
oh nice, he even updated it recently
thank you!
his screenshot shows python 3.9.6 version
I want to make search command for my discord of a site using selenium
(site doesnt have search result url site or search.button)
codes:
driver = webdriver.Chrome()
driver.get('link/search')
searchbox = driver.find_element_by_xpath('/html/body/div/div/div/div[7]/nav/div/div[3]/div/div[1]/input')
what to do? help pls
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
what?
its just a search engine
does that mean discord music bots are also breaking laws?
Judge Dredd (1995) Hollywood Pictures, Cinergi Pictures and Edward R. Pressman Productions; Stars: Sylvester Stallone, Diane Lane, Max von Sydow, Jurgen Prochnow, Joan Chen, Armand Assante. Directed by Danny Cannon. Music: Alan Silvestri Distribution: Hollywood Pictures
yes: https://rythm.fm/
Judge Dredd 1995
yeah i know about this
their hosting is very bad
due to the bot is been part of like A LOT servers
will add it to my watchlist
I'm launching Django migrate and for some reason tables don't appear
django-backend | django.db.utils.ProgrammingError: relation "token_blacklist_outstandingtoken" does not exist
django-backend | LINE 1: INSERT INTO "token_blacklist_outstandingtoken" ("user_id", "...
Here's the issue
And here is my settings.py file with the installed apps:
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"rest_framework",
"rest_framework_gis",
"rest_framework_simplejwt",
"rest_framework_simplejwt.token_blacklist",
"corsheaders",
"django_filters",
"drf_yasg",
"api.apps.ApiConfig",
"users.apps.UsersConfig",
]
If I wanted to pass some data from react frontend to django backend, through an apiview, would I have to make an axios post request to the apiview url, and then do something like request.get(data=data) in the actual apiview function in views.py?
there's much more to python that's all. my feeling is if you're smart enough to use django, you're smart enough not to. It's good to think separate services for a number of reasons.
hello, i've just started a flask project. in my __init.py file i also wanna setup and initialize my connection to an api that i am going to use.
should i put the api stuff like it's required arguments in the create_app() function?
or do i have to do something else
hello guys, what it is the best package to audit django app?
redo makemigrations @surreal portal
root@d454b11f26bd:/app# python manage.py makemigrations
No changes detected
According to this, it should work?
Can someone shine a light on me ? 🙂
https://stackoverflow.com/questions/69392376/change-value-of-dropdown-in-django-forms
That means that you have no models
Yeah and that one is supposed to come with rest_framework_simplejwt
That's probably bc I'm already using an already instanciated db
Which is weird
Any way to force migrations on the DB?
any good beginner-friendly tutorial of Django channels?
django help please
getting this mess of an error, and cant figure out why!!
NoReverseMatch at /note/2/update
Reverse for 'update_note' with no arguments not found. 1 pattern(s) tried: ['note/(?P<pk>[0-9]+)/update$']
note_detail.html
{% extends 'private_notes/base.html' %}
{% block content %}
<div class="notes" style="display:flex">
<div class="note">
<a href="">
<h3>{{note.title}}</h3>
<small>{{note.pub_date}}</small>
<p> {{note.note_text}} </p>
</a>
</div>
</div>
<a href="{% url 'update_note' note.id %}"> <h2>Update</h2> </a>
{% endblock %}
update_note.html
{% extends 'private_notes/base.html' %}
{% block content %}
<h1>Update Note</h1>
<form action="{% url 'update_note' %}" method="POST">
{% csrf_token %}
<input type="text" name="note_title" value="{{note.note_title}}">
<textarea name="note_text" id="note_text" cols="30" rows="10">
{{note.note_text}}
</textarea>
<input type="submit">
</form>
{% endblock %}
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
path('note/<int:pk>', views.detail, name='detail'),
path('new_note', views.new_note, name='new_note'),
path('note/<int:pk>/update', views.update_note, name='update_note'),
path('login', views.login, name="login"),
path('register', views.register, name="register"),
path('logout', views.logout, name="logout"),
]```
the control flow looks simple enough. I click on the update link in note_detail.html. That should search in the urlpatterns for note/pk/update, which it does find. Then it should execute the associated function. I don't understand what's the issue here?
lol sussy baka
whaat?
im not likely to be online when someone responds, so please tag me so I can check the chat. Thanks!
tomi tokko.
solved it. Dumbass mistake.
✌
what are you building?
im trying to learn class based views
so just quickly built a note-making app where I can experiment with them
🙂
any other project using django or drf?
yea I built a few
not drf
dm if you wanna be in touch
how you make the front end?
hath se
thats nice
Hey guys. I'm starting to learn Django. Anyone know of any good resources? I know Python thoroughly, but haven't tried web development in Python yet. In terms of Web Dev, I know the basics (HTML, PHP, JS, etc) so it doesn't have to be totally introductory.
Oh there's a resource list under #welcome my bad 😄
https://docs.djangoproject.com/en/3.2/
official docs have tutorial "first steps"
Cool 🙂
I've worked through those, yeah. Thinking of getting into something more advanced
thanks!
u a welcome. if you seek more advanced Django stuff...
there are books from
to
excellent! Thank you very much.
How to do the button with this color
Is this what you want? https://developer.mozilla.org/en-US/docs/Web/CSS/gradient/linear-gradient()
https://cssgradient.io/ if you want a visual constructor
yes thx
Hello,i'm with a problem with my my api in django. So when i try to acess the endpoint i got this error:
what i suppose to do, i've checked my serializer and its everything allright with them
here my models and serializer
model
serializer
and this error appears in all routes
line 11 of the views?
Yes
ok let me try
it worked, but i dont undesteant why this heppended, the many argument its not for a many to many relation?
No see the thing is when you are doing
Class.objects.all()
It is returning a queryset and not a single object , if you had done
Class.objects.get(nome='pikachu')
It would have returned a single object
So whenever you are using all() to get data
Make sure to pass many=True in serializer
Np
I have a notice model that creates s notice (it contains title, description and date). I would like to schedule notices to be created at certain dates. Basically, I mean using another model I want to schedule and create the notices at that date specified.
How would I do this? What's the easier road to achieve this? All I can think of is rabbitmq and celery. And i don't even know how it would create s notice at a dynamic date.
Hi im trying to make verification page for my site in quart but i when it comes to verify solution keys i get 2 seprate keys and i dont know how to fix that, my code is:
@app.route("/verification", methods=['GET', 'POST'])
async def verification():
response = requests.get('https://captchaAPI.pythonanywhere.com/api/img').json()
random_image = response["url"]
solution = response["solution"]
if request.method == 'POST':
input_sol = (await request.form)["cptc"]
if input_sol == solution:
print('Nice')
print(solution)
print(input_sol)
else:
print('Invalid captcha')
print(solution)
print(input_sol)
return await render_template("verify.html", random_image = random_image, solution = solution)```
and here is output in console
I am new to web development and Im hoping someone can help explain when is a good time to use asynchronous programming or not?
I see async await in a lot of different code bases, but im not entirely sure when you would want to use asynchronous functions.
this looks like you re-request the captcha once the POST request comes in, so you will get a different captcha code, no?
asynchronous programming is very useful for web apps when you for example have some long-running task that shouldn't interrupt the rest of your application from running
for instance, imagine your web app makes a call to some other app which waits with the response until some job has finished, if you made an asynchronous request there, everything else in your app could keep running
ah ok i see. So if my application pings some other api, i would probably want that to be an async function?
Yes, so do i need request before?
you already request it in GET, so ideally you would want to store it e.g. in the request session to have it stick around for the next request
(assuming you have request session storage set up)
no sorry I worded that a bit oddly, it's hard to generalize when you want to use an async way of calling stuff. i can give you one example from my work, i maintain an API which deals with tons of concurrent requests, and that API writes some data it retrieves via the request to two backend databases. now all the calls to the backend databases are asynchronous and while we're waiting on the databases to save away the data the app can continue doing other stuff. before I rewrote it to be async, it was really sluggish since every request had to wait for the backing databases to save it away
i don't
oh
wait
ok, that makes sense. Would you say most web applications use some sort of async programming?
i would guess most newer apps do, yes. but there's also excellent frameworks that aren't completely async, such as django or flask, so it's really a matter of what you want to do
I accualy don't but i found example of cookie session
from quart import session
...
@app.route('/')
async def index():
return await render_template(
'index.html',
colour=session.get('colour', 'black'),
)
@app.route('/colour/', methods=['POST'])
async def set_colour():
...
session['colour'] = colour
return redirect(url_for('index'))```
I never used sesstions that much
if i am using django as my framework, do i need async?
yep, but that examlpe does look like what you want
if you are just learning web development, then probably not. you will know when you need async
Ok thanks
I am running CentOS Linux release 7.9.2009 and I have python 2.7.x installed. I need some instruction on installing py 3.9.x
Just remove old one
how will i know when i need to use async? when the app is running slow hahah?
and install it using apt
when you want to make the most out of your CPU cores :D
It should install newest by default
I want to use all the CPU cores! ha. ok cool, well thank you for the explanation.
centos doesn't have apt, I think yum is the package manager there
is that 2009 in the version for the year 2009? in that case you will probably not have much luck with installing python 3.9. but you can use something like pyenv to get you a python 3.9 interpreterhttps://github.com/pyenv/pyenv
Oh sorry, didn't know that. I meant that all linux systems have apt
following this to install 3.9.x on CentOS box: https://computingforgeeks.com/install-latest-python-on-centos-linux/
SSL issue for many 2.7 users lol
Hello guys, is there a way to change as like this value.
That is from auth_user table. i want to show the True status to "Active"
True = Active
False = Inactive
nevermind I got it
Running a Django app on py 2.7.x now all of a sudden getting this error:
SSLError(SSLError(1, u'[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed
my domain certs are all up-to-date.
some good and easy resources to learn web scraping any site?
Well, first mistake @amber cobalt - Python 2.7 😆
@glad pendant I know, I know...slap me for this. It's legacy stuff.
I'm afraid if I use 3.9, Django and even my codebase will need to be overhauled since many things have changed.
I tried: r = requests.post('https://foo.com', data, verify=False) but newer apps are not passing SSL whereas older ones (Java based) are validating
research about beautifilsoup, requests and selenium
just tried htmx with sanic. plays nice... https://github.com/byteface/htmxtest/blob/master/app.py
import requests
from html5_parser import parse
sites = [] # add webpages here
for SITE in sites:
try:
r = requests.get("https://"+SITE)
some_html = r.content.decode("utf-8")
root = html5_parser.parse(some_html, treebuilder='dom')#, return_root=False)
print(root)
# print(type(root)) # a domonic Document
# print([str(el) for el in root.getElementsByTagName("a")])
# print(page)
except Exception as e:
print('Failed to dl page', e)
from django.core import files
from io import BytesIO
import requests
url = "https://example.com/image.jpg"
resp = requests.get(url)
if resp.status_code != requests.codes.ok:
# Error handling here
fp = BytesIO()
fp.write(resp.content)
file_name = url.split("/")[-1] # There's probably a better way of doing this but this is just a quick example
your_model.image_field.save(file_name, files.File(fp))```
how is my model intaking `files.File(fp))`? so that I may use this picture
```py
fp = BytesIO()
fp.write(resp.content)
print("name:", i, "files:", files.File(fp), "file:", fp)
u.photo.save(i, files.File(fp))```this is what its printing out for me `files.File(fp)`
name: myfile files: file: <_io.BytesIO object at 0x7flee65b3810>```
it does save a file on my server but not accessible for me to open as a image
I would have to read that file from my server through BytesIO?
Anyone else shooting themselves with the LetsEncrypt SSL cert issue today?
I bet everyone thought it was py issue...haha - just go out and buy a $10 cert folks.
Anyone could help me with https://stackoverflow.com/questions/69392376/change-value-of-dropdown-in-django-forms?noredirect=1#comment122650391_69392376 ?
im trying to update my dropdown (which is in my django forms ) with the id that gets passed.
For example
views.py
def company_agents_detail(request,company_id):
list = loggedin_view(request)
how can I parse the data from a response?
the flask api returns a string (not using jsonify function).
I've tried to use r.dict_ to find anything that might help, but the data seems being wrapped by ClosingIterator
How can I extract the string?
Thanks
Figure it out, I should use ".data"
I was making a library app in django, and I configured urls so that localhost:8000 would redirect to localhost:8000/catalog/
but now I'm making a new app, and the home link still redirects to /catalog automatically?!!
how did you do it
like so (in project's urls.py):
from django.views.generic import RedirectView
and then append this line to urlpatterns
path('', RedirectView.as_view(url='catalog/', permanent=True)),
okay
so
if you’re sure that that’s not in your new project any more
could you try this
open the website in incognito/private mode and see if you still get redirected?
which is what you want, right?
do you have a view matching that route?
like, localhost:8000 should render the home page
yeah, I do
are you sure your server is running
its running
Oh and also
this things happening on edge
but not on brave
or chrome
on them the apps running fine
"Maybe you used a "permanent" redirect? Browser can remember those..." I got this from another server
yeah but
that’s why I said use incognito mode
so cached responses wouldn’t be used
but this is clearly wrong
since the same URL is resolving on other browsers
oh its working now
on edge I mean
can I somehow clear last day's cache in browser?
lmaoo I cleared the data and its working now
this was trippy
Maybe a stupid question, but how easy is it to implement JavaScript API's such as WebGL / three.js for smooth animations when programming with Django? Should I rather look for a Django specific alternative to do animations?
I'm thinking of trying similar animations to the animations as seen on this website:
https://patrickheng.com/
I.e. my question isn't how easy is it to do animation, but rather if it would be acceptable for me to use JS APIs such as three.js and WebGL while developing with Django/Python.
"acceptable"...?
how would you do animations with Django
So my question is basically, can I use Three.js alongside Django? Three.js would handle the animation side of things using JS.
I'm not familiar with that library, but I don't see why not
@vestal hound or are those two things mutually exclusive? I would think that it should be able to put Three.js in the static folder, since it's basically just a JS API? Or am I being stupid
they handle fundamentally different things, right
not really.
but
ultimately
it's just a JS script
that you can use in your HTML templates/files
yw 👋
Can you use arrayfields for db models when using MySQL with django?
@client.ipc.route()
async def get_avatra_client(data):
print(data)
print(client.user.avatar_url)
return client.user.avatar_url``` Why if i do something like this it jump me error?
resp = await handler(request) File "C:\Users\Mateusz\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\ipc\server.py", line 209, in handle_accept raise JSONEncodeError(error_response) discord.ext.ipc.errors.JSONEncodeError: IPC route returned values which are not able to be sent over sockets. If you are trying to send a discord.py object, please only send the data you need.
how to fix it?
@app.route("/dashboard")
async def dashboard():
guild_count = await ipc_client.request("get_guild_count")
guild_ids = await ipc_client.request("get_guild_ids")
icon = await ipc_client.request("get_avatra_client")
try:
user_guilds = await discord.fetch_guilds()
except:
return redirect(url_for("login"))
same_guilds = []
for guild in user_guilds:
if guild.id in guild_ids:
same_guilds.append(guild)
return await render_template("dashboard.html", guild_count = guild_count, matching = same_guilds,av=icon)```
Hello I'm currently developing a web app that uses react for the frontend and django for the backend. While developing, I used django-cors-headers package to communicate with my frontend but how can I set up everything for production. Thank you in advance. Any help is very welcome.
This is what I used so far:
CORS_ORIGIN_ALLOW_ALL = False
CORS_ORIGIN_WHITELIST = (
'localhost:3000',
)
what tutorial or guide should i follow to learn django? i am quite new to python i followed this whole tutorial https://www.youtube.com/watch?v=rfscVS0vtbw and some of the intermediate tutorial.
This course will give you a full introduction into all of the core concepts in python. Follow along with the videos and you'll be a python programmer in no time!
Want more from Mike? He's starting a coding RPG/Bootcamp - https://simulator.dev/
⭐️ Contents ⭐
⌨️ (0:00) Introduction
⌨️ (1:45) Installing Python & PyCharm
⌨️ (6:40) Setup & Hello Wor...
so my question is, what website/video should i use to learn django for beginners like a tutorial which will explain everything in details because most tutorials go so fast like the tech with tim one, he assumes that we know what and how databases work and how to make servers etc