#web-development

2 messages · Page 192 of 1

main grail
#
.autorize button {
    background: #111;
    color: red;
    border-color: red;
    padding-block: 10px;
    text-align: center;
    text-decoration: none;
    font-size: 13px;
    border-radius: 12px;
}``` How to larger space between the border and the text
calm plume
#

it's not padding-block, it's just padding

main grail
#

ok

main grail
calm plume
#

Uh, wdym

#

It'll apply to any <button class="authorize">Some text</button>

wheat flare
wheat flare
wheat flare
#

Your welcome, hope 🙏 this helps.

wise kite
#

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 ?

dry obsidian
#

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?

dry obsidian
#

Or can a client make all these API calls fast enough

dry obsidian
manic frost
#

Where can I practice CSS on artificial tasks?

#

Or rather, apply CSS so that the page doesn't look like crap.

calm plume
#

I often go to a random page, go to Firefox's "Style Editor" in dev tools and mess around.

quick cargo
dry obsidian
quick cargo
#

That doesnt change anything im afraid

#

Well especially on the breaking TOS side of stuff

quick cargo
#

You can download the captions

#

It's the video side of it thats the issue

#

You cant do that via the api

dry obsidian
quick cargo
#

In that case is should be okay

dry obsidian
karmic kayak
#

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?

main grail
#

I dont know too

warm igloo
#

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.

native tide
#

where can i find a database online for free?

calm plume
#

Or are you looking for a database that you can use to store your own data?

native tide
#

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

calm plume
#

Postgresql, mysql, mssql, etc.

native tide
#

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

calm plume
#

Uh well, there are some online free hosting things

#

It's rather nice

native tide
weak mulch
#

Does anyone here know how to publish a Flask + Socket.io website? (I can't seem to find any help online)

nova pewter
#
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

nova pewter
#

fixed , please ignore . Thanks

native tide
#

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
rough garnet
#

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?

inland oak
#

The {{ variable }} thing is rendered, it is expected you will pass it into template

rough garnet
#

Nevermind as stated #help-mango I found solution by a bit of googling

#

using {%raw%} solves problem

inland oak
inland oak
# rough garnet using {%raw%} solves problem
<!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>
rough garnet
#

Let me better frame my question, how to make flask to ignore all {{}} because I am using those for vue js templates

inland oak
#

Percentage symbol is used for loops and other stuff

inland oak
#

Disable jinja2 usage

rough garnet
#

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

inland oak
#

This is wrong solution involving dirty hacks

rough garnet
#

I mean it is working yert

inland oak
#

So not use Jinja 2 at all, since u a already with frontend framework

rough garnet
#

I have not actually get decided Everything thing but yes lists should be fetched from an api my current implementation is very dirty

dapper tusk
#

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()

sinful stone
#

any django dev here ?

native tide
#

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

foggy bramble
#

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

vestal hound
stable oak
#

Sr can I ask about how to create checkout in e-commerce 'django'

#

Document or video

low moat
#

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?

royal quail
native tide
#

but on clients machine not localhost on server

wraith prawn
#

Hey, can anyone recommend a way to deal with rate limits please? found a couple of decorators but they seems quite bad

warm igloo
#

you want to get around rate limits, or you want to set rate limits

silver radish
#

Hi, can python build a media server? I want to build a video on demand website

cerulean badge
#

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)

inland oak
#

will be they not having the same values?

manic crane
#

for django if i want to create custom user models do i need to make another app inside the project ?

orchid olive
#

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?

zealous oar
hasty path
#

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

native tide
#

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

half eagle
#

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

olive patrol
#

How can I access a CharField's value in Django?

#

Nevermind, figured it out

inland oak
#

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

steel reef
#
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)

native tide
#

is there a way to create a one to one database relationship in django

steel reef
#

yes

vernal lotus
#

Hello, can anyone help me to show a dropdown list from in forms.

#

does not appear

calm plume
# vernal lotus

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

vernal lotus
#

how do I paste here as code format. LOL

calm plume
vernal lotus
#

okay thanks

calm plume
cerulean badge
warm igloo
#

you have a typo in your code, @vernal lotus

#

Check how you spell field everywhere

#

for instance "role_filed" in your screenshot

vernal lotus
#

oh yeah thanks

warm igloo
#

😉

vernal lotus
#

but

warm igloo
#

so it wouldn't show cause it didn't exist

vernal lotus
#

it did not put into the into the dropdown

warm igloo
#

you corrected the typo and set up the options?

vernal lotus
#
<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>
vernal lotus
olive patrol
#

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

warm igloo
#

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.

warm igloo
trail mirage
#

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?

#

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...

▶ Play video
warm igloo
vernal lotus
warm igloo
#

probably just extra in your template

vernal lotus
#
<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>
warm igloo
#

yeah, you have double "

#

the first set self-closes

vernal lotus
calm plume
#

<option value=""{{form.role_field}}""> </option> should be <option value="{{form.role_field}}"> </option>

warm igloo
#

get rid of the extra around {{}}

warm igloo
#

and now?

vernal lotus
warm igloo
#

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

vernal lotus
#

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>
warm igloo
#

and you still see extra characters?

vernal lotus
#

yes

warm igloo
#

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

vernal lotus
#

okay bro i'll investigate the extra characters.

glacial yoke
#

what is the best way to have a function happen every x amout of time in django?

warm igloo
#

there is a module called django-cron

native tide
glacial yoke
#

the actual function takes like 4 seconds to run, cos it fetches some info from elsewhere, and updates it in the db

native tide
vernal lotus
#

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)
gentle ingot
#

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')}}"

trail mirage
#

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...

▶ Play video
dense cloak
#
#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

inland oak
#

U need to initialize your db again, migrating command will do it, and then to create super user again

python manage.py migrate
python manage.py createsuperuser

#

Saving test/dev db is a really bad taste. Better to init from zero/config/whatever

native tide
#

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

#

if you need any more information from me, please ask and I will provide it

native tide
#

i need alot of help haha

royal quail
#

Hey trying to make a website with django for my bot, how should one get started with it ?

#

if anything please tag

swift wren
#

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

jovial cloud
swift wren
#

no way

#

thats a thing

#

flask_login.current_user

#

thats really cool

buoyant geode
#
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 }}"```
swift wren
#

you didnt endif the last if statement {% if page_obj.has_next %} on line 34

swift wren
jovial cloud
swift wren
#
@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

jovial cloud
swift wren
#

oohhh okay gotcha. that works just fine

#

thank you mateeee

#

its hard finding information about flask and its extensions

jovial cloud
swift wren
#

oh your right

jovial cloud
swift wren
#

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"

jovial cloud
idle birch
#

Hi all,

What visual studio code extensions are good to install for coding node.js?

buoyant geode
#

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.

lavish prismBOT
#

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:

https://paste.pythondiscord.com

buoyant geode
#

complete traceback

swift wren
#

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

manic crane
buoyant geode
#

Thank you @swift wren Im just learning django for backend development started recently

past cipher
#

how do you pass two arguments to a Jinja filter:?

mystic vortex
#

@eternal blade

#

her e

#

here

swift wren
#

just add another /

muted scaffold
#

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

royal quail
#

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

past cipher
royal quail
past cipher
#

should be url_for not url for

royal quail
#

thanks but why does it give the desired background ? I am sorry

past cipher
#

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;
}
royal quail
past cipher
#

check debug console

#

see if there any errors on /style.css

#

should be returning a status code of 200

royal quail
muted scaffold
#

Check that you entered the correct location of the file and restart the server

royal quail
tardy heron
#

what is server side rendering? Generate pieces of html and send to front-end which requests them using js or something? Hybrid SSR SSG?

royal quail
#

Thank for all your help @muted scaffold and @past cipher

tardy heron
#

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?

vestal hound
#

SSR -> do this on the backend

#

so, basically

tardy heron
#

so SSG = javascript generating html. SSR = jinja 😄

#

?

sharp goblet
#

Does someone know whats this? Some friend posted it to me (ping me thx)

native tide
#

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

pastel vessel
#

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?

manic crane
#

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)

next vessel
#

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

royal quail
native tide
#

idk why this err is coming

royal quail
#

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; }

royal quail
# native tide idk why this err is coming

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

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

royal quail
royal quail
#

@native tide

native tide
#

@royal quail bru my mom took my laptop I'll try tomorrow and say...

woeful remnant
#

Hey, in which cases is python better for web dev then lets say javascript?

meager anchor
#

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.

woeful remnant
#

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

meager anchor
#

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

woeful remnant
#

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

indigo kettle
#

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

woeful remnant
#

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... 😛

indigo kettle
#

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.

woeful remnant
#

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 😄

topaz wigeon
mystic vortex
#
@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!

woeful remnant
topaz wigeon
woeful remnant
#

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

topaz wigeon
#

fair enough

manic crane
#

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'.

indigo kettle
#

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..

vernal lotus
#

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

#

models.py

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)
wraith prawn
vernal lotus
#

How to register user without password then send email password

tribal python
#

Generally that is bad practice, if you want passwordless you'd be better off implementing 2fa system i.e. Google authenticator

native tide
candid meteor
native tide
#

Anyone learning or new to Django and want to learn together? Maybe do a small project or two?

#

there are no err though

true kernel
#

Hey do you think I need to know class based views before learning django rest framework?

dusty moon
#

my first ever <div> hell

#

i have so much divs cuz i know only flex box

inland oak
#

class="div-1 div-2" and e.t.c.

#

multicomibining into one

dusty moon
#

I know

dusty moon
#

CSS is fun btw

inland oak
#

then a bit of proper templating jinja2 blocks

short ingot
#

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.

dusty moon
inland oak
#

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 %}
        &copy; 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

dusty moon
#

What is the (% %} thing?

#

Like {% endblock %}

inland oak
# dusty moon What is the (% %} thing?
{% 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

dusty moon
#

Anywhere I can read more about it?

dusty moon
#

Does this have something to do with Python?

inland oak
#

all python frameworks have it enabled by default

#

plus some javascript frameworks have it similiarily too (Svelte)

dusty moon
#

Oh. Sorry for being a noob, I’m just starting out with html …

inland oak
#

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

dusty moon
#

kBs?

inland oak
dusty moon
#

Oh.

inland oak
#

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

dusty moon
#

Cool

#

So, wait… basically I can use Python with html css?

dusty moon
#

Cool

#

Should I though?

inland oak
#

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

dusty moon
#

Oh.

#

So only APIs? I can’t do simple stuff like make an html button do stuff?

inland oak
dusty moon
#

I’m talking about functionality

inland oak
#

for simple solutions python framework would be enough

dusty moon
#

Ok.

inland oak
#

frontend framework is wished when you use javascript extensively

#

it is just better way to use javascript

dusty moon
#

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…

inland oak
#

not knowing, I am going only to start using desktop stuff soon

dusty moon
#

Oh, ok.

native tide
#

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.

haughty kettle
#

helllo

#

can y help me out

lavish prismBOT
#

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.

haughty kettle
#

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

stark tartan
#

(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

night sequoia
#

django anyone?

indigo kettle
#

@stark tartan I think you can do

set_drones(prev => [...prev, ...data.results])```
graceful flax
#

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 😅

true kernel
true kernel
#

Try rephrasing it maybe

night sequoia
true kernel
#

depends on the error

#

show me

#

explain in some detail , whats the issue?

graceful flax
# true kernel this part isnt very clear

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

shut bloom
#

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.

manic crane
brave stag
#

anyone has idea on serverless deployment using zappa
i need some help

dense slate
native tide
#

I want to make a mu* to the fullest.

surreal portal
#

Has anybody tried showing a nested serializer in a view?

native tide
#

It is my dream before I leave earth one day.

#

@dense slate

surreal portal
#

Django keeps telling me the field in the serializer doesn't exist

zealous sage
#

i did the deployement using the zappa flask applications @brave stag

brave stag
zealous sage
#

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

surreal portal
#

Btw is ListAPIView even appropriate for nested serializers?

spiral blaze
#

is this normal?

#

im following a flask tutorial right now and the guy doesn't have any errors but i do

surreal portal
#

Though you can fix those issues using a formatter like black

spiral blaze
#

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

true kernel
stark tartan
dense slate
cerulean badge
#

anyone know a responsive mit license chat app template? i could not find it

modern edge
#

how do webservers handle multiple requests at the same time? do they have multiple instances of the same program?

native tide
#

well. they talk to the socket. so you have to use somethign like uwsgi, gunicorn etc

torn junco
modern edge
native tide
#

ye can take a long time to understand

#

read about wsgi and asgi

#

and set one up

torn junco
native tide
modern edge
native tide
#

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

modern edge
#

or will it hog up the memory lol

modern edge
#

nah dw i will look into it

native tide
torn junco
native tide
#

its that easy in a way. but ramps up. i.e. you have to pass logs through it

modern edge
#

how does it know when to kill the child process

native tide
#

you kill it

modern edge
#

wat

torn junco
native tide
#

ye there's even settings for that

#

the config can get big.

#

there's weird names for params

#

voodoo stuff

modern edge
#

doesnt Flask handle all that

native tide
#

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

torn junco
modern edge
#

ah

#

well

#

shit

#

lol

torn junco
#

sorry

native tide
#

ye. it's like that at first. then you know

modern edge
#

no no its not your mistake

native tide
#

and you have to help others

modern edge
#

thats how u learn ig

native tide
#

so really you will start with this

#

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

modern edge
native tide
#

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

modern edge
#

well currently i just want to know what happens in the backend of backend and to know if Flask handles all that

native tide
#

is flask async yet?. try sanic

modern edge
#

how can it not be concurrent

#

every web app should be concurrent

#

no?

native tide
#

kinda. it's hard to answer that

#

you tried sanic?

modern edge
#

hmm, thanks for the recommendation

shut bloom
#

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

orchid olive
#

in python, flask, how can i increase the session expiration time?
i need the webpage to be "live" at least 1 hour or 2

stiff karma
#

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

native tide
#

i need help

#

if (clicks >= requiredclicks){
document.querySelector("#levelupbtn").style.visibility = "true";
}
else{
document.querySelector("#levelupbtn").style.visibility = "false";
}

#

why doesnt that work

outer apex
native tide
#

ty

outer apex
native tide
#

you mean once u close the program u want it to still be running?

orchid olive
#

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

outer apex
#

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.

brave stag
orchid olive
native tide
#

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)

outer apex
outer apex
# native tide i get error

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!

manic crane
#

someone please help => django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency Occupier.0001_initial on database 'default'.

wraith prawn
#

has anyone used ratelimiter lib and had any issues with ```py
@RateLimiter(max_calls=1, period=1)

#

?

#

this dosnt seem to do anything

orchid olive
warm igloo
# wraith prawn has anyone used ratelimiter lib and had any issues with ```py @RateLimiter(max_c...

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?

wraith prawn
#

gotcha

#

i think ive figured it out

warm igloo
#

cool

wraith prawn
#

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

warm igloo
#

ah yeah, you want to move whats in that loop to a func itself and ratelimit THAT

wraith prawn
#
from ratelimiter import RateLimiter

rate_limiter = RateLimiter(max_calls=10, period=1)

for i in range(100):
    with rate_limiter:
        do_something()```
warm igloo
#

ah yes, with the context managert

wraith prawn
#

this is what I had to do, and what worked

warm igloo
#

great

wraith prawn
#

🙂 thanks for getting back to me though!

warm igloo
#

you could also decorate do_something()

#

at its def

#

you're welcome! glad you figured it out

wraith prawn
#

thats sample code, mine isnt a def within the loop

#

just code

warm igloo
#

figured

#

best of luck on rest of your project though

wraith prawn
#

thanks!

#

this is pretty much the final piece of the puzzle

brave jolt
#

from . import views (what does the . mean here)

tepid lark
#

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?

native tide
#

Anyone looking for a coding buddy? To motivate each other to code and not give up

tepid lark
#

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.

warm igloo
# brave jolt from . import views (what does the . mean here)

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."

outer apex
dense ridge
echo summit
#

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

tepid lark
#

plus. most web apps aren't especially cpu bound

#

and if they are, you can usually offload that stuff to something more performant

echo summit
woeful remnant
#

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

modern pivot
#

Hello,
Anyone knows Scrapy ?

graceful flax
#

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 :/

dim wolf
#

django error has anyone seen before?

been trying to fix it for 3 hours... finding right locations for all the templates and indexs etc....

graceful flax
#

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)

modern pivot
#

Hi, there is Scrapy dev or expert !?

silk moon
#

How do I give an image a variable name? and use it in CSS and change the width and height?

#

anyone know

ancient ridge
#

Hey can someone suggest a site or YT vid where I can learn Django?

tepid lark
ancient ridge
#

Thx I had to make a project using django

#

I watched mosh but his tutorial didnt help much if at all

tepid lark
#

I honestly find most videos aren't helpful compared to reading and doing, unless they're stuff like conference talks

wooden ruin
#

TIL django is multithreaded by "default" that's cool

surreal portal
#

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

native tide
surreal portal
#
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']
cerulean badge
#

anyone know of a responsive mit licensed chat template? i need it for a chat app but can't find one

surreal portal
#

I don't know why the serializer can't accept new fields

lilac solar
surreal portal
#

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

lilac solar
#

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/

latent lava
#

Hello, everyone where i can ask a question about django python framework?

#

I need help with tampletes

tidal jay
#

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?

desert estuary
#

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
signal notch
#

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? 🙂

shut bloom
#

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

shut bloom
#

By using this you can add

signal notch
#

I dont have that.

shut bloom
signal notch
#

i have a html5 file rn

shut bloom
#

Then see documentation of that game engine

#

If its crossplatform u will get info

ancient ridge
#

umm I am trying to type

#

but it shows [Errno 2] No such file or directory

#

Any fixes?

cerulean badge
#

its very obvious

#

there is no manage.py file in your cwd

#

so make sure you cd to it

ancient ridge
wicked hare
# surreal portal If it's ListAPIView or something else

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.

cerulean badge
#

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

ancient ridge
#

ohk

cerulean badge
#

are you on windows or linux?

ancient ridge
cerulean badge
#

do you know how to open cmd in a directory?

ancient ridge
cerulean badge
#

then do it in the directory where manage.py file is

cerulean badge
#

then run the command again

ancient ridge
#

it worked thx

native tide
#

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?

candid elk
#

Hello everyone, i want a solid tutorials to builds rest api with django

brave stag
#

anyone have idea on serving django static files using zappa

lavish prismBOT
#

@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!

stark tartan
#

Any advance ideas for Website (Django project )

dense slate
dense slate
#

Big reason for tokens is for sharing access to multiple platforms/services.

next vessel
#

Email validator is not showing error messages

#

any clue why isn't this showing up?

thorn igloo
#

you question is too vague

next vessel
#

i think i'm missing something in code, nvm
imma check again and if i get the same error i'll post it here

simple garden
#

what does meta charset does in html

tepid lark
simple garden
#

yes

#

what does it do

#

@tepid lark

tepid lark
#

it tells the browser how the html page is encoded

#

when it comes down to it, html is just a bunch of bytes

simple garden
#

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

tepid lark
#

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

simple garden
#

i dont understand what u said right now ;-;

tepid lark
#

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

simple garden
#

got it

foggy geode
#

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'),
]

olive patrol
#

How can I see which button was clicked?

abstract gazelle
#

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

vestal hound
#

text is internally a lot of binary

simple garden
#

well what does it do

#

like what does it change

vestal hound
#

an encoding is how to turn that binary into human readable letters

#

hold up let me get an example

simple garden
#

okayy ty btw

vestal hound
#

is 🔥 in ASCII (an older encoding)

#

in binary they are the exact same

#

just a long chunk of 0s and 1s

simple garden
#

yes i get it

#

but dosent it do that automatically

vestal hound
#

most everything uses UTF-8 nowadays

simple garden
#

so what does it change?

vestal hound
#

IF you were to change the encoding manually you’d see something different

#

but for the web it’s mostly a curiosity nowadays

simple garden
#

so pretty much putting meta charset utf8 is like just translating it into normal words

#

thats all

vestal hound
#

a complete answer would go into the history of encodings, but that’s the gist of it

simple garden
#

thanks for explaining this to me ;-;

#

em can i dm u in the future if i needed something to understand

#

in html

vestal hound
simple garden
#

okay thanks

#

oh yeah ur a helper i didnt see ;-;

#

helpers dont accept dms

#

hope u have a good day

vestal hound
lavish prismBOT
#

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.

outer apex
tepid lark
#

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

vestal hound
#

then yes

tepid lark
#

seems like it's mostly mitigable

vestal hound
#

only about your own thread safety

tepid lark
#

yay, singletons

#

I think I've got it now. just needed to ramble a bit

wide compass
#

Has anyone secured a FastAPI app with just an API key rather than something like OAUTH?

calm plume
# wide compass Has anyone secured a FastAPI app with just an API key rather than something like...

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)

GitHub

Pixels is an introductory API from Python Discord for painting on a collaborative canvas. - GitHub - python-discord/pixels: Pixels is an introductory API from Python Discord for painting on a colla...

dense solar
#

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?

tepid lark
wooden ruin
tepid lark
dense solar
#

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

tepid lark
#

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.

dense solar
#

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

sudden gulch
#

hey need help with scss in django

simple garden
#

what does this do in html
<meta name="" content="">

sudden gulch
#

they are description to your page

#

usually used for seo

simple garden
#

for example like what

sudden gulch
#

<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

simple garden
#

ohhh

#

so its like search engine

#

got it thanks

sudden gulch
#

wlc

pure barn
#

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

buoyant moat
#
            <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
native tide
#

can someone direct me to a flask course for free?

inland oak
#

oh nice, he even updated it recently

native tide
#

thank you!

inland oak
#

his screenshot shows python 3.9.6 version

native tide
#

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

lavish prismBOT
#

5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.

native tide
#

its just a search engine

#

does that mean discord music bots are also breaking laws?

inland oak
inland oak
native tide
#

looks cool

inland oak
native tide
#

their hosting is very bad

#

due to the bot is been part of like A LOT servers

native tide
surreal portal
#

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",
]
glacial yoke
#

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?

native tide
marble gorge
#

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

cerulean dock
#

hello guys, what it is the best package to audit django app?

cerulean dock
surreal portal
#
root@d454b11f26bd:/app# python manage.py makemigrations
No changes detected
#

According to this, it should work?

hallow yacht
glacial yoke
surreal portal
#

That's probably bc I'm already using an already instanciated db

#

Which is weird

#

Any way to force migrations on the DB?

sonic island
#

any good beginner-friendly tutorial of Django channels?

true kernel
#

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 %}
#

urls.py

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"),
]```
true kernel
light ore
#

lol sussy baka

true kernel
#

im not likely to be online when someone responds, so please tag me so I can check the chat. Thanks!

true kernel
#

solved it. Dumbass mistake.

sonic island
sonic island
true kernel
#

im trying to learn class based views

#

so just quickly built a note-making app where I can experiment with them

sonic island
sonic island
true kernel
#

not drf

#

dm if you wanna be in touch

sonic island
true kernel
sonic island
dusky field
#

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 😄

dusky field
#

Cool 🙂
I've worked through those, yeah. Thinking of getting into something more advanced

#

thanks!

inland oak
#

there are books from

dusky field
#

excellent! Thank you very much.

main grail
#

How to do the button with this color

main grail
#

yes thx

honest tartan
#

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

#

serializer

#

and this error appears in all routes

native tide
#

@honest tartan can you show your views.py file

honest tartan
#

sure

native tide
#

And try once

honest tartan
#

line 11 of the views?

native tide
#

Yes

honest tartan
#

ok let me try

#

it worked, but i dont undesteant why this heppended, the many argument its not for a many to many relation?

native tide
#

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

honest tartan
#

ahhh i see

#

thanks

native tide
#

Np

west arrow
#

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.

zealous smelt
#

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

wispy niche
#

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.

meager anchor
meager anchor
#

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

wispy niche
#

ah ok i see. So if my application pings some other api, i would probably want that to be an async function?

zealous smelt
meager anchor
#

(assuming you have request session storage set up)

meager anchor
# wispy niche ah ok i see. So if my application pings some other api, i would probably want th...

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

zealous smelt
#

oh

#

wait

wispy niche
meager anchor
#

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

zealous smelt
# meager anchor (assuming you have request session storage set up)

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

wispy niche
meager anchor
meager anchor
zealous smelt
amber cobalt
#

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

wispy niche
zealous smelt
#

and install it using apt

meager anchor
#

when you want to make the most out of your CPU cores :D

zealous smelt
#

It should install newest by default

wispy niche
meager anchor
meager anchor
zealous smelt
amber cobalt
#

SSL issue for many 2.7 users lol

vernal lotus
#

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

vernal lotus
#

hello anyone can help me to remove asterisk when using cripy forms

#

TYA

amber cobalt
#

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.

paper scaffold
#

some good and easy resources to learn web scraping any site?

glad pendant
#

Well, first mistake @amber cobalt - Python 2.7 😆

amber cobalt
#

@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

native tide
native tide
native tide
# paper scaffold some good and easy resources to learn web scraping any site?

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)

haughty turtle
#
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?

kind lark
#

hey

#

does anyone know where I can find a discord accounts creation date?

amber cobalt
#

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.

hallow yacht
heady ore
#

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"

true kernel
#

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?!!

true kernel
#

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)),
vestal hound
#

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?

true kernel
#

ah alright

#

this one says page cant be found

vestal hound
true kernel
#

no?

#

i want my app to run

#

normally

vestal hound
#

do you have a view matching that route?

true kernel
#

like, localhost:8000 should render the home page

true kernel
vestal hound
true kernel
#

Oh and also

#

this things happening on edge

#

but not on brave

#

or chrome

#

on them the apps running fine

vestal hound
#

well

#

then something’s wrong with Edge

true kernel
#

"Maybe you used a "permanent" redirect? Browser can remember those..." I got this from another server

vestal hound
#

that’s why I said use incognito mode

#

so cached responses wouldn’t be used

vestal hound
#

since the same URL is resolving on other browsers

true kernel
#

yeah so in brave's incognito its still running fine

#

idk what to make of that

true kernel
#

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

vestal hound
#

yeah in general if stuff from the past lingers

#

try in incognito

#

or ctrl f5

dusky field
#

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.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.

vestal hound
#

how would you do animations with Django

dusky field
#

So my question is basically, can I use Three.js alongside Django? Three.js would handle the animation side of things using JS.

vestal hound
dusky field
#

@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

vestal hound
#

they handle fundamentally different things, right

vestal hound
#

but

#

ultimately

#

it's just a JS script

#

that you can use in your HTML templates/files

dusky field
#

awesome

#

cool

#

thank you!

vestal hound
#

yw 👋

glacial yoke
#

Can you use arrayfields for db models when using MySQL with django?

main grail
#
@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?

main grail
#
@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)```
compact crane
#

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',
) 
native tide
#

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...

▶ Play video
#

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

graceful flax
#

Hi I'm building a social app backend using DRF and I've posts in them and there are other APIs that do operations on posts

#

Posts can be deleted