#web-development

2 messages · Page 224 of 1

earnest parrot
#

thanks for the help though!

inland oak
formal rapids
#

Why is my flask application sending insane amounts of post methods? Everytime i make a post the next time it doubles? (When i refresh the page and make post requests it resets)

deft crow
#

'session': <SimpleLazyObject: <function AuthenticationMiddleware.process_request.<locals>.<lambda> at 0x0000026E97ABC8B0>>

#

how to get the REAL session id?

tough forge
#

Hi guys, we currently develop a free hosting control panel and we want to support Python as well.

#

What is the standard procedure to install additional python versions on a server (debian, ubuntu). Do you use pyenv?

#

Each site user (ssh user) should be able to install it's own needed python version

wheat verge
#

how to change timezones in django

#

I have a field in my data base which gives the current time but the time is not from my timezone

past cipher
#

I am using allauth and receiving the error: SocialToken matching query does not exist.. Has anyone experienced this? I have triple checked the site ID and its correct

#

I can login fine with google. But when I use this code below, I retrieve the error above:

token = SocialToken.objects.get(account__user=request.user, account__provider='google')
dusk sonnet
#

Hey, is there a way to pass a variable or something to a base template? (django)

lavish prismBOT
#

Hey @manic crane!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

manic crane
#

discord said the message is to long

lavish prismBOT
#

Hey @manic crane!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

wheat verge
#

is there a way to reset all the values of a collumn everytime a server starts?

merry merlin
grand orbit
#

using Django & Jinja to make an html page, is it possible to share a python variable directy to a JS script inside that html page ?

return render(request,'report.html',{'users':users})

report.html:

<script src="{% static 'data.js' %}"></script> <-- how to access `{{users}}` from inside `data.js`?
merry merlin
surreal palm
#

Related to this: since Electron ships with chrome, I've thought about doing the same, but not with chrome.
Is there a lightweight browser that can be freely shipped with an app?

timber jungle
#

Flask:

For an Input box text ,
can i check in real time if a string is entered correctly and show a flashing message in html ?

Or should this check based on regex, to be done on the input box?
<input type="text" id="uname" name="uname" pattern="[a-zA-Z0-9]+" minlength="4" maxlength="10">

astral grail
#

and for smaller amount of data, there's also escapejs that can be embedded directly inside a <script> tag

astral grail
#

which may be necessary for more complex validation patterns

obtuse robin
#

anyone know why the db commit is not working..?

#

it prints up to the current user stuff

#

but not to the search form

#

idk whats wrong with the commit

dim plume
#

I am trying to render css and js on my flask server but it does not render it
How can i solve this?

obtuse robin
#

how are you connecting your files?

#
<link rel="stylesheet" href="{{ url_for('static',filename='css/style.css') }}">
<script src="{{ url_for('static',filename='js/myscript.js') }}"></script>
#

is how i usually do them

#

for flask

timber jungle
cloud path
#

does anyone know why it doesn't add the thing in the database?

#

that's the color of how usually should appear, but it turns into it just with syntax errors

#

i dunno why it's all the same color above

dense slate
somber flicker
#

please i am building a rest api server in python with fastapi and i have this error.
ImportError: cannot import name 'Entreprise' from partially initialized module 'schemas' (most likely due to a circular import) Can anyone help me?

dense slate
#

Maybe you have a circular import?

somber flicker
#

yes... but i don't know how to fix it

dense slate
#

Circular import means you're importing aa module into one file, but then that same file is trying to import from the original file so it is stuck in an importing loop

#

So look to see if you are importing one file into the other and then back again - if that makes sense

#

Sometimes you can be importing A into B, and then B into C, but C is imported into A, so it still creates a circle

#

You'd have to show relevant code for more help.

somber flicker
#

this is my __init__.py file where I import all the other files.
now in each file on /schemas I do from schemas import Pole, User or (...) as needed

#

it is in the schemas folder that I have this error not in the others

warped aurora
#

Anyone use selenium wire?

stable bear
#

what are some of the main services that allow hosting of a web application?

timber jungle
#

i created a plain html file and it said it was free
000webhost com

or the free tier Oracle Cloud?

ionic raft
# wheat verge I have a field in my data base which gives the current time but the time is not ...

I'd encourage reading up about how time zones work in Django: https://docs.djangoproject.com/en/4.0/topics/i18n/timezones/

That said, I've been using Django for just under a year now and I'm finally starting to get clear about it. Your comment about the field in the model brings to mind the difference between a naive DateTime field and a timezone aware one. One approach I've taken is to use default=timezone.now() within the model itself.

However, where things get really interesting is understanding how timezone awareness plays out for an application that is used by users in different timezones. How you want to approach this will depend on your use cases; which is why there isn't one simple answer for you. For example, will you be using these DateTime fields for date calculations? How do you want DateTime fields to display to users?

dense slate
timber jungle
timber jungle
warped aurora
#

Need some help logging into and navigating a page. I was using selenium before but they've since added csrf tokens to the page and now I'm having a problem. Not sure how to grab to csrf for the current session and pass it with the driver

wicked pier
#

I can't get Flask auto reloading to work. It says it's reloading, but the template doesn't change

#

Like if I add text somewhere in the template and save, it doesn't show up until I refresh the page

outer apex
timber jungle
#

Is it possible in Flask to have a flash message

And in the html file, for an input text box

jinja to search for a regex and show a flask flash message if the regex is not matched?

tame wagon
#

is there any good resource for learning selinium for web scraping?

#

also, I heard scrapy is WAY faster but it doesn't load javascript so you can't interact with javascript components

#

is there a workaround or is selinium the only option in that case?

unkempt temple
#

selenium is the best option if you would like to simulate javascript

#

you can use headless mode to speed things up a bit

velvet goblet
#

As far as django tutorials go is there a difference between watching Sentdex or Corey Schafers?

dusk sonnet
#

Hey, im getting a ValueError (Cannot query ... must be 'user' instance) and im not sure how to resolve it.

@login_required
def watchlist(request):
    params = {}

    try:
        get_wl = Watchlist.objects.get(wl_username=request.user)
        params["wl_items"] = get_wl.wl_listing.all()
        #print(get_wl.wl_listing.all())
    except Watchlist.DoesNotExist:
        pass 

    if request.method == "POST":
        if request.POST.get("wl_btn") == "Add to Watchlist":

            watchid = request.POST["watchid"]
            listings = Listing.objects.get(id=int(watchid))

            try:
                get_lst = Watchlist.objects.get(wl_username=request.user) # Line that triggers the error
                get_lst.wl_listing.add(listings)
            except Watchlist.DoesNotExist:
                user = Watchlist(wl_username=request.user)
                user.save()
                get_lst = Watchlist.objects.get(wl_username=user)
                get_lst.wl_listing.add(listings)

            return redirect("index")

    return render(request, "auctions/watchlist.html", params)
manic crane
#

my post model was working fine before now im getting this error => ```insert or update on table "Occupy_post" violates foreign key constraint "Occupy_post_occupier_id_27a10cf1_fk_Occupier_occupier_id"
DETAIL: Key (occupier_id)=(1) is not present in table "Occupier_occupier".

#
# a post can only have one user
#a post can only belong to one clique
    # filters posts so only published posts are avaible in the home screen.
    class PostObjects(models.Manager):
        def get_queryset(self):
            return super().get_queryset().filter(status = "posted")
    options = (
        ('draft' , 'Draft'),
        ('posted' , 'Posted'),
    )
    clique = models.ForeignKey(Clique, on_delete=models.CASCADE, related_name='cliques', blank=False)
    content = models.TextField(max_length=400,null=False, blank=False,)
    caption = models.CharField(max_length=400,null=False, blank=False,)
    posted = models.DateTimeField(default=timezone.now)
    occupier = models.ForeignKey(Occupier, on_delete=models.CASCADE,related_name='clique_posts',default=1)
    status = models.CharField(max_length=12, choices=options, default='posted')
    objects = models.Manager() # default manager
    postobjects = PostObjects() # custom manager

    class Meta: 
        ordering = ('-posted',)

    def __str__(self):
        #returns caption
        return self.caption`````
grand orbit
deft crow
#

hello i wanna ask something, currently im working for discord bot website
i wanna shown user profile picture from a url i have, so i made:
<img src="{{ AvatarUrl }}" width="25px" height="25px" class="rounded-circle">
but i get
<img src="(unknown)" width="25px" height="25px" class="rounded-circle">
how to fix this?, AvatarUrl is https://cdn.discordapp.com/avatars/838640428060246046/0615fcf08cc119d886a90fae81e4d2fd.png?size=2048

ruby sorrel
#

hello everyone 🙂 noob here,
trying to understand javascript

do you guys know what's the difference between these three loops?

myObj = {
    "color": "maroon",
    "fruit": "durian",
    "month": "april",
    "nick name": "greg"
}

for (let key of Object.keys(myObj)) {
    console.log(key, myObj[key]);
}

for (let key in myObj){
    console.log(key, myObj[key])
}

Object.keys(myObj).forEach((key) => {
    console.log(key, myObj[key])
})
torn ledge
#

My flask command is suddenly not working

#

this error pops up: 'flask' is not recognized as an internal or external command,
operable program or batch file.

#

I already added it to path

#

python and site packages

#

i even uninstalled and installed it

#

flask runs fine on my web-app but dosent work in command prompt

ruby sorrel
#

maybe it is installed on a venv?

whole spear
#
           // some code here
            if (agent) {
                // move the agent
                console.log(input[i], input[i].move, input[i]["move"])
                if (input[i].move) {
                    console.log(input[i], i)
                    let moveDirection = input[i]["move"];
                    // some code here as well
#

on the first console log it prints everything fine

#

but on the second input[i] and i become undefined

#

how can i solve it?

#
        for (let i = 0; i < input.length; i++) {
            let agent = this.getAgentById(input[i].id);
            if (agent) {
                // move the agent
                console.log(input[i], input[i].move, input[i]["move"], i)
                if (input[i].move) {
                    console.log(input, i)
                    let moveDirection = input[i]["move"];
                    // let moveDirection = [0,0]
                    let i = agent.i + moveDirection[0];
                    let j = agent.j + moveDirection[1];
                    if (i >= 0 && i < this.gridSize && j >= 0 && j < this.gridSize) {
                        this.moveAgent(agent, i, j);
                    }
                }
            // the rest
}
}
#

so heres more complete picture

cerulean badge
#

Django
how do i validate unique constraints in serializers? I have this

            models.UniqueConstraint(
                fields=["time"],
                condition=~models.Q(status="L"),
                name="unique_not_cancel_time",
            )
ionic raft
small coral
#

!rule 9

lavish prismBOT
#

9. Do not offer or ask for paid work of any kind.

zealous oar
#

Hi 👋
Did anyone tried to integrate the Paypal webhook with Django Rest Framework to accept payment?
I think the Paypal docs are messy and I have no idea what have to do as a back-end, so if anyone tried that before, please provide me with useful links/tutorial

hexed mica
#

Can I add uid to my model after the model has already been migrated ?

grizzled mirage
#

Django:
How can I use two different kind classes from an abstract class in the foreign Key?

hollow dune
#

has anyone had experience with websockets? and have you made a server/client combo?

could you show/tell me how you did it and

does anyone know how I can make a websocket server class?

dense slate
#

It doesn't have great SSL support though.

hollow dune
#

ill have a see tomorrow

finite lake
#

Guys, what program is recommended to building front-ends with python?

#

(or is that not even a thing?)

bronze palm
#

well you can do it with django templates but thats basicly just html with special tagging

cinder whale
outer blaze
#

Flask is very buggy in chrome, where it randomly doesn't import the style.css file while in firefox it seems to be working completely fine. Any ideas of whats wrong

inland oak
#

U a supposed to use nginx for that

#

Nginx as reverse proxy to flask gunicorn.
Plus it serves static files

outer blaze
#

oh then how would you do that

inland oak
#

Google tutorial?

#

Flask mega tutorial has it I think

outer blaze
#

yea ill try that thanks

simple phoenix
simple phoenix
cinder whale
whole sierra
#

does anyone know how to keep scroll position with htmx

#

?

mystic depot
#

does anyone know how i would just extract this part of the text?

#

someone pls @ me if they know

dusk sonnet
#

Hey, sort of a stupid question but how do i create this "-----" in django? currently mine just automatically picks the first category until the user specifies

#

i want the default to be "-----" which isnt a category instead of "Toys"

sterile trellis
#

I have an div tag which i want to apply a border, but it is getting applied to its padding as well!
So how can i apply a border only to the element and not its padding

whole sierra
#

can anyone help me with django/htmx/css issue I'm having??

remote echo
fossil shard
gusty gate
#

Hi all,
I work on an API with FastAPI which adds game cards entries to a mongoDB with file upload for front and back images of the game card.
Should I split the file upload and the create endpoint for creating a game card? The workflow would basically type all the infos into a form, add the images and create the card. But what is best practice for adding File Upload?
Is it better to split this into two api calls for error handling?
thanks 🙂

late trail
#

(Django)How can I get only the rest Api views in Django(static files?)? I want to share my API.
Thanks

meager valve
#

Hey I created this in Flask, I want to display the progress while processing the uploaded file. is that possible with jinja2?

rigid laurel
#

Not a real progress bar. If you know how long it's likely to take then you can fake it with some js

plush trench
#

what are all the must know python technologies to work in a company that uses python programming language

manic crane
#

i want to migrate me removing a field of my models but i keep getting this error => ValueError: Field 'occupiers' expected a number but got ''.

#
#A clique can have many users. 
#A clique can have many posts.
    class CliqueObjects(models.Manager):
        def get_queryset(self):
            return super().get_queryset().filter(level='public')
    options = (
        ('private', 'Private'),
        ('public', 'Public')
    )

    name = models.CharField(max_length=200, null=False, blank=False,default='')
    created_at = models.DateTimeField(auto_now_add=True)
    occupation = models.CharField(max_length=90,null=False,blank=False,default='')
    level = models.CharField(max_length=10, choices=options, default='public')

    objects = models.Manager() # default manager
    cliqueobjects = CliqueObjects #custom manager

    def __str__(self):
        return self.name ````
compact glacier
#

Hello! making an web app with Django. in Frontend trying to make buttons that can see only owner of Topic using Django Template Language.

{% block content %}
    <div>
        {% if user.username is topic.owner %}
            {{ user.username }} is the owner of {{ topic }}
        {% elif user.username == topic.owner %}
            {{ user.username }} is the owner of {{ topic }}
        {% else %}
            {{ user.username }} is not the owner of {{ topic.owner }}
        {% endif %}
    
        {% if user.username == topic.owner %}
            {% buttons %}
                <a href="{% url 'learning_logs:new_entry' topic.id %}" class="btn btn-primary" role="button">Add new entry</a>
                <a href="{% url 'learning_logs:delete_topic' topic.id%}" class="btn btn-danger" role="button">Delete Topic</a>
                <a href="{% url 'learning_logs:change_public' topic.id %}" class="btn btn-outline-secondary" role="button">public {{ topic.public }}</a>
            {% endbuttons %}
        {% endif  %}
    </div>

    {% for entry in entries %}
        <div class="card mb-3">
            <h4 class="card-header">
               {{ entry.date_added|date:'M d, Y H:i' }} {# '|' фильтр применяющий дальше формат даты. !Регистр имеет значение #}
                {% if user.username == topic.owner %}
                    <a href="{% url 'learning_logs:edit_entry' entry.id %}" class="btn btn-outline-warning btn-sm">edit entry</a>
                    <a href="{% url 'learning_logs:delete_entry' entry.id %}" class="btn btn-outline-danger btn-sm">delete entry</a>
                {% endif %}
            </h4>

            <div class="card-body">
                <p>{{ entry.text|linebreaks }}</p> {# linebreaks следит чтобы все разрывы текста присутствовали на самом деле #}
            </div>

but its not works.
1 screenshot is how it works now

#
    """Тема изучаемая пользователем"""
    text = models.CharField(max_length=200)
    date_added = models.DateTimeField(auto_now_add=True)
    owner = models.ForeignKey(User, on_delete=models.CASCADE)
    public = models.BooleanField(default=False)

    def __str__(self):
        """Возвращает строковое представеление модели"""
        return self.text```

Topic Model. User model is default to Django
compact glacier
inland oak
#
python ./manage.py compilemessages
 ---> Running in bb9b1dfa036a
Traceback (most recent call last):
  File "/usr/local/lib/python3.8/site-packages/django/apps/config.py", line 244, in create
    app_module = import_module(app_name)
  File "/usr/local/lib/python3.8/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'quotas'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "./manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line
    utility.execute()
  File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute
    django.setup()
  File "/usr/local/lib/python3.8/site-packages/django/__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/usr/local/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate
    app_config = AppConfig.create(entry)
  File "/usr/local/lib/python3.8/site-packages/django/apps/config.py", line 246, in create
    raise ImproperlyConfigured(
django.core.exceptions.ImproperlyConfigured: Cannot import 'quotas'. Check that 'gill.contrib.quotas.apps.QuotasConfig.name' is correct.
The command '/bin/sh -c python ./manage.py compilemessages' returned a non-zero code: 1
ERROR: Service 'worker' failed to build : Build failed

Migrating django from 3.0.8 to 3.2, I started to have random module import to fail. Any ideas what can be wrong? I checked already the name, looks fine.

#
from django.apps import AppConfig


class QuotasConfig(AppConfig):
    name = 'quotas'
INSTALLED_APPS = (
      'gill.contrib.quotas',
)
meager valve
#

how do I redirect after returning response in flask?
Tried threading
RuntimeError: Attempted to generate a URL without the application context being pushed. This has to be executed when application context is available.

native tide
#

Traceback (most recent call last):
File "C:\Users\Documents\python sublime\b.py", line 2, in <module>
from selenium.webdriver.keys import Keys
ModuleNotFoundError: No module named 'selenium.webdriver.keys'
[Finished in 334ms]

#

how to solve this error

feral spindle
#

Was the module selenium.webdriver.Keys instead?

fickle basin
#

hello, what the best way to create a model of products that will have other models in relation with it ?

inland oak
glass wren
#

i'm working on a project(bugtracker) in django and was wondering if this was an alright 'app' structure for it?
project, ticket and users are ~~models ~~ apps and i'm not quite sure if base would be a good addition to merge them all together, since it's an app?
i also don't quite understand app in django, is it just a reusable module or is there anything more to it?

ruby sorrel
#

hello everyone 🙂 noob here,
do you guys know how to use React?
how do i loop through the contents of a list and put them in my jsx?

const listItems = [
    "apple",
    "banana",
    "grapes",
    "petchay",
    "apardor"
]

function List(){
    return(
        <ul>
            {listItems.map((li) => {
                return (
                    <li>{li}</li>
                )
            })}
        </ul>
    )
}

this works but i get error saying please use prop key what

glass wren
ruby sorrel
glass wren
ruby sorrel
#

yes i'm reading now. it looks like how keys are with objects? so in my example.

function List(){
    return(
        <ul>
            {listItems.map((li.actualItem) => {
                return (
                    <li>{li.actualItem}</li>
                )
            })}
        </ul>
    )
}

?

#

nope lol

#

wait keys are supposed to be given as an attribute property to the element, and as a parameter to the function?

#

here we go this got rid of that error

function List(){
    return(
        <ul>
            {listItems.map((li, text) => {
                return (
                    <li key={text}>{li}</li>
                )
            })}
        </ul>
    )
}

not sure if im doing it right though

runic furnace
#

I'm using Flask with SQLAlchemy, when creating a user I want to create some sort of object which stores all their settings from the program (not the user credentials), what would be the best way to accomplish this?

#

I thought that if I were to put that in the user class the class would get to big once the application expands

#

Maybe create another separate settings class?

#

Does anyone know a good way to solve this?

ruby sorrel
runic furnace
#

yes I think

ruby sorrel
#

you can also just use the same table for now and move the columns to a new table in the future. if it deoes become needed

runic furnace
#

yeah, SQL is a bit hard for me

#

but storing in the same table would be the easiest route

#

on the other hand maybe doing it good the first time would prevent a lot of work down the road

glass wren
#

if that is the case then a relationship between two tables might be what you're looking for, like bregue suggested

#

something like this

#

one thing i've learned from SQL tables is:
Normalize it until it hurts, Denormalize it until it works 🤣

quasi forge
#

can flask build a very good quality website?
can flask replace javascript + css? thank you

frank shoal
#

no.

#

But you could vendor css and javascript libraries using npm/yarn

fickle basin
#

anyone up for 10 mn ?

patent glade
#

If I wanted to implement a DOM api for python

#

Something which you could work with using the same function calls, the same structure

#

Walk the same walk as with any standard vanilla javascript, in the important ways

#

Where do I start?

#

What I've done so far is implement a Node class, inheriting from an EventTarget class

#

And then numerous subclasses of Node including Element, CData (Text, Comment, Instruction, Doctype), Document, and Attr

#

A NodeList class to represent a Node's childNodes attribute and an Element's children attribute

#

And a NamedNodeList class to contain the values of an element's DOM attributes

#

And I think that's it. Does all that check out?

idle berry
#

how can i make my flask website do this?

sand gull
#

I was working with Django/Wagtail when I ran into this error message
'NoneType' object has no attribute '_inc_path'
Does anybody know how to fix this?

ripe wagon
#

!

gentle jasper
#

and sends the data by rest api

idle berry
native tide
#

:'/

idle berry
#

ah damn. thanks

native tide
#

:>

meager valve
#

How to redirect with delay from backend in general? instead of using Js

native tide
#

which framework you're using?

meager valve
native tide
#

ok idk.. nvm 😂 ||(if it was django.. i could have been of some help.. :"/ )||

#

let's wait for someone who knows .. :")

meager valve
meager valve
native tide
#

:")

#

for redirect in django

#

u can use

#

!d django.shortcuts.redirect

lavish prismBOT
#

redirect(to, *args, permanent=False, **kwargs)```
Returns an [`HttpResponseRedirect`](https://docs.djangoproject.com/en/stable/ref/request-response/#django.http.HttpResponseRedirect "django.http.HttpResponseRedirect") to the appropriate URL for the arguments passed.

The arguments could be:

• A model: the model’s [`get_absolute_url()`](https://docs.djangoproject.com/en/stable/ref/models/instances/#django.db.models.Model.get_absolute_url "django.db.models.Model.get_absolute_url") function will be called.
 • A view name, possibly with arguments: [`reverse()`](https://docs.djangoproject.com/en/stable/ref/urlresolvers/#django.urls.reverse "django.urls.reverse") will be used to reverse-resolve the name.
 • An absolute or relative URL, which will be used as-is for the redirect location.
 
 By default issues a temporary redirect; pass `permanent=True` to issue a permanent redirect.
native tide
#

yes ^

meager valve
# native tide yes ^

will that work if I have already returned response and run this in threaded process to redirect?

native tide
meager valve
native tide
#

🤔 well.. it's like in django.. u make function for redirecting ( to a website) or rendering (any html file) so inside that function u can do whatever u want

#

but at this point.. i'm not sure if that function can be async.. cuz i never tired to do it.. lemme search on google... lol

native tide
cerulean badge
#

I need help on design decisions, I am making a resume builder webapp with free and paid templates, my questions is should I be generating pdf on server side and send to frontend or just send the html and css of the template to frontend and let them handle the conversion? (Converting html to pdf seems like very heavy task to be done on the backend but I think I can do it asynchronously using celery and send the user an email with the pdf attachment) what do you suggest?

nimble berry
# idle berry ohh.... idk anything about js... any way that it can be done with flask or other...

don't be discouraged, that is not a prompt made by js, it is the browsers built in authentication prompt

it is usually configured directly in the configuration for the web server or using an .htaccess file in a content directory
but there is a way to do it using flask (in your case, other frameworks can of course also do it) as well using: https://flask-httpauth.readthedocs.io/en/latest/

the most common type of http authentication is the one called basic authentication, one of the most impotent things to remember with this is that it is very insecure if not used over TLS/SSL (https:// urls)
you can read more about http authentication works here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication
from the above link:

Security of basic authentication

As the user ID and password are passed over the network as clear text (it is base64 encoded, but base64 is a reversible encoding), the basic authentication scheme is not secure. HTTPS/TLS should be used with basic authentication. Without these additional security enhancements, basic authentication should not be used to protect sensitive or valuable information.

#

@gentle jasper and @native tide, you probably also want to check http authentication mentioned above

nimble berry
# meager valve will that work if I have already returned response and run this in threaded proc...

you can't redirect using the http protocol after you already sent other data in response to a request as redirecting that way is a 3xx http response
if you have not closed the html <head> tag yet you can use html redirect to accomplish what you want
if that option isn't feasible due to that restriction you could go with redirecting using javascript anywhere in the page
for information on all the three above mentioned methods: https://developer.mozilla.org/en-US/docs/Web/HTTP/Redirections

bold star
#

Any of yall who can help in web scrapping data?
I am new to python

olive canopy
#

I want to provide the content of a log file to a webpage, with it updating the new lines as they get added (I do have access to the process that logs into the file, so I could do it directly if possible) but preferably without the webpage refreshing and removing selections/scrolling back up/down etc..
Does anyone know of a way how I could potentially do this?
I've been searching but haven't really found anything.. hmmmm

Ping if you have an idea thanks

nimble berry
bold star
#

a requests lib tutorial may help

#

I want to scrap nba stats

#

I need to scrap data from the NBA site and then code it in such a way so that I can see any players stats from any year but i cant do that 😢

nimble berry
meager valve
#

I'm attempting to upload a file, process it, and then download it. To do this, I submitted a POST request to the server at the '/upload' route, and the server should redirect to the download page after processing the uploaded file.
However, the difficulty is that it experiences response timeouts as a result of the processing large file.
I tried multithreading, but even with that, you can only respond to a request once, so you can't redirect once you have respond a request in a separate process Thread.

How can I redirect as soon as the uploaded file has been processed?

versed lotus
meager valve
versed lotus
# meager valve > redirect first to a progress page, and once done, get redirected further to th...

the way it's done. when you upload a file, you start a background process and immediately redirect to a progress page. usually those job runners have some kind of ID that represent the job that is running in the background, so you would pass that ID along to the progress page.
once there, you can regularly (javascript?) check with the job id, if the task is finished or not. and once finished, have the browser redirect to the downloads page (with javascript as well, probably).

#

there are other ways of course.

meager valve
versed lotus
#

uhm possibly? that would require websockets probably, but still javascript on the frontend

#

you could do without javascript, and just start the job after upload, store the job id in database or something, immediately redirect to the download page, and list all finished files and still-in-progress files... simple F5 would then update the list

hybrid patio
#

Hello guys

#

I have simple question

#

I use VSC and Django FM

#

Someone give me advice witch theme is the best for this FM? thx

native tide
nimble berry
hard whale
#

Flask or fastAPI for webdev newbie? quick answer:)

inland oak
#

Django for mid

#

FastAPI for expert ;b

hard whale
inland oak
#

Flask is microframework that will train you from zero doing everything on its own. A bit more healthy for beginners I think

#

Django and FastAPI both frameworks of battery included approach, A lot of stuff out of the box. Better to try microframework like Flask first before diving into them. U will have better understanding what u use then

rigid laurel
#

FastAPI doesn't have to be async and often isn't

hard whale
#

Hmm, I started with FastAPI and it feels quite comfortable to work with

rigid laurel
#

If it's a good for for your project, then start with FastAPI

inland oak
#

Then go with it then 😉 FastAPI looks 20% cooler

mortal ledge
#

Quart is an async implementation of Flask.

inland oak
#

real project use FastAPI or Django I think

#

Flask is a bit useless because.... it has no... advantages

rigid laurel
#

There's a lot of legacy flask applications because it used to be the easiest way to spin up a quick rest API, but not any more really

inland oak
hard whale
#

I saw many job offers for django devs but from my IT insides large companies move to FastAPI these days 🙂

#

Just faster to deploy

mortal ledge
inland oak
#

It has really hard compatibility within its own libraries

#

they aren't really correlated with each other

#

Authors assume the person would use compatibility mode with Flask

#

and it works... and not works. Just lucky chance

mortal ledge
inland oak
#

I am serious 😉

#

that's the only reason

#

anything flask has, Django or FastAPI can do better

hard whale
#

And flask logo is ugly

mortal ledge
mortal ledge
inland oak
hard whale
#

edit more!

#

😄

inland oak
native tide
#

Is there some guide on how do I set up quart? Because I think I set it up wrongly

inland oak
hard whale
#

😄

hard whale
native tide
native tide
hard whale
#

Probably

#

What you wanna do?

inland oak
# native tide Ain't Quart just async Flask?

Quart is failed attempt to make async Flask. Which you don't need nowdays anyway. Quart was invented because Flask made slow work in the past to introduce asynciness.
But Flask 2.0 is ASYNC already. And yeah FastAPI is Async which is more mature anyway, so if u wish async, use FastAPI

native tide
hard whale
#

Wen in these regards fastapi is teh same lol

#

But nicer logo

native tide
native tide
hard whale
#

Mostly yes

native tide
hard whale
#

I know that big companies use either django or fastapy

native tide
#

But I'm too lazy to switch aaaaa

hard whale
#

so if you want to get a job, fastapi might be a better choice

native tide
#

Hold up let me see if fastapi has a better tutorial

hard whale
#

fastapi looks 99% the same

#

fastapi has a lovely tutorial

#

trust me

#

i started with flash, couldn't run a server for 3 days

#

tried fastapi, server is up in 30 min

#

20 of those 30 min i was scratching my butt and making myself a cup of tea

native tide
native tide
hard whale
#

I'm a newbie and I don't know all the stuff under the hood but some large international banks use fastapi for their apps

#

and they say "oh you know django, cool you suffered much, enjoy fastapi now coz we need to build and deploy FAST"

#

there must be some core reason why they moved to fastAPi in the end

hard whale
#

It will take time to understand how all this work BUT at least it will work

native tide
hard whale
#

Just dont forget to up your venv

#

Same here, flask was my first go to

native tide
#

Tho I'm using the fastapi article tutorial thing

hard whale
#

But after 3 days of pain I was suggested this

#

And oh Lord

native tide
hard whale
#

It is lovely

#

Now i'm struggling with my app creating db in venv instead of project folder

stable bear
#

what are the most popular hosting services for web apps?

grizzled mirage
#

Django question:
I have two models (Chat and User).
Chat and User have a Many-To-Many relationship.

How can I check if a users exists to add them to the Relationship in Chat? What Response is possible if it doesn't exists?

candid meteor
#

if yeah, then add it

grizzled mirage
#

and if not? How can I validate that @candid meteor

#

/ give a correct Response

candid meteor
#

it will return False lol

grizzled mirage
#

Yeah I know that. But how can I tell the user (via. rest api) that the user didn't exist

grizzled mirage
#

I have users in a Chat object.
If I try to use for user in data['users']: it'll give me a key error bcs users is not in the request. How can I validate that users is in the json req

candid meteor
#

like

#

data.json()['users']

stable bear
#

for a flask web application, do sqlite databases work in aws elastic beanstalk?

rigid laurel
#

No - it wouldn't because you get "new" instances of your app spinning up and down which would mean you lose the information

#

you need the database to exist on some remote server

stable bear
#

my web app takes up the whole screen of a small screen, but only half of the screen of a larger screen
how do i write some code so that it takes up the same proportion of the screen on any device?

native tide
#

im fucking stupid 💀

worn crystal
#

First off, hello, if this needs to be moved to another channel please let me know
I'm trying to deploy my webapp to azure and i ran into some trouble on my db migration. I'm following this tutorial https://docs.microsoft.com/en-us/azure/app-service/tutorial-python-postgresql-app?tabs=flask%2Cwindows%2Cvscode-aztools%2Cterminal-bash%2Cazure-portal-access%2Cvscode-aztools-deploy%2Cdeploy-instructions-azportal%2Cdeploy-instructions--zip-azcli%2Cdeploy-instructions-curl-bash
and i got to step seven pretty easily but for some reason it's telling me it cannot import frontend(frontend.py is my flaskapp but idk if that is something that is causing the issue) and then it's telling me that there is no such command as db. If anyone could help me out then that'd be great 🙂
Also, including the current issue and an issue i had earlier with flask_app not being defined(i think i fixed it with an export)export FLASK_APP=frontend.py
also, this is the command i'm using to do the db migration flask db init

#

or is my understanding of the db migration tutorial wrong and do i have to look up another way to deploy my flask app to azure?

timber jungle
worn crystal
#

okay, I renamed it and am deploying again. hopefully it works fine this time

#

i'm following the tutorial loosely if that makes a difference? I have my own code and project that i'm trying to upload. I'm just following along the steps needed to bring my stuff online

timber jungle
worn crystal
#

@timber jungle it was saying the same thing but this time it could not import "app"

#

could this be the issue?

timber jungle
#

did you set the env variable to the new name of the file?

worn crystal
#

when i ssh into my server i navigated into the proper directory with my app.py and exported it export FLASK_APP=app.py so i think it should be okay but I'll reupload and try again with that.
btw when i tried what i first said in this message it gave me a lot of errors and this was the last thing that was actually legible sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) could not translate host name "test-server" to address: Name or service not known

timber jungle
#

you will have to solve every error encountered.
It may be a one of the reasons why it fails.

worn crystal
#

:/

#

thank you for the help so far

dense slate
#

Anyone used GraphQL with Django/python and seen that a query is called once but the associated resolvers in Django are actually run 3 or 4 times? react + apollo/graphql/graphene + django

#

I can't seem to track down how that's happening.

nimble berry
winter hearth
#

Does anyone know why Flask's Blueprints.. are called blueprints?

manic crane
#

i make new models and my django migrations wont apply for some reason ?

serene prawn
dense slate
serene prawn
#

depends on graphql library you're using

dense slate
#

graphene_django

#

I'm actually just realizing too that some of my resolvers are running without them being called on the FE.

#

I called one query just now, ran it correctly, but another query also ran (according to django) without signaling in my chrome debug tools that it was called (no console logging)

#

Resolvers under the same query class don't automatically run together right? Or can one trigger another?

elder rover
#

how to set maximum per day user can fill the slot and from where i need to start and how to set functions user can fill up to 10 times then the slot is locked. thank you

#

class BookingSettings(models.Model):
# General
booking_enable = models.BooleanField(default=True)
confirmation_required = models.BooleanField(default=True)
# Date
disable_weekend = models.BooleanField(default=True)
available_booking_months = models.IntegerField(default=1, help_text="if 2, user can only book booking for next two months.")
max_booking_per_day = models.IntegerField(null=True, blank=True)
# Time
start_time = models.TimeField()
end_time = models.TimeField()
period_of_each_booking = models.CharField(max_length=3, default="30", choices=BOOKING_PERIOD, help_text="How long each booking take.")
max_booking_per_time = models.IntegerField(default=1, help_text="how much booking can be book for each time.")

#

This is my view

deep wing
#

Has anyone had this error? I'm doing an automation with selenium and python, and the 'ul' variable works in the interactive mode of the terminal, but in the code it doesn't.

WebDriverError@chrome://remote/content/shared/webdriver/Errors.jsm:183:5
NoSuchElementError@chrome://remote/content/shared/webdriver/Errors.jsm:395:5
element.find/</<@chrome://remote/content/marionette/element.js:300:16


#

HELP

native tide
#

!resources

lavish prismBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

native tide
#

!django

#

!TAGS

lavish prismBOT
#
Available tags

» type-hint
» venv
» voice-verification
» windows-path
» with
» xy-problem
» ytdl
» zip

manic crane
#

trying to migrate and keep this error => django.db.utils.ProgrammingError: relation "Occupy_clique" already exists

keen zephyr
#

Hello there! I'm trying to make a Flask-based API hosted on Heroku. I have a global method that creates responses and it looks the following way:

def response(body = None, code = ResponseCode.SUCCESS, message = "") -> flask.Response:
    if message == "":
        if code == 200:
            message = "Success"
        elif code == 404:
            message = "Not Found"
    else:
        message = message
    response =  jsonify(body)
    response.status_code = code;
    response.headers.add_header('message', message)
    print('Responsing with:\nMessage: ' + str(message) + '\nCode: ' + str(code) + '\nBody: ' + str(response.data) + '\n')
    return response

And so, when I have to handle some request I do the following:

@api.post('/some-route')
def some_route():
  # Do some stuff here
  return response({'some_key': 'some_value', ... })

Such thing causes H17 error on Heroku when responding.
Here is the description of H17 error in detail: https://devcenter.heroku.com/articles/error-codes#h17-poorly-formatted-http-response

somber seal
#

Does anyone know if there is a way to run PyCharm over web like VSCode?

nimble berry
# somber seal Does anyone know if there is a way to run PyCharm over web like VSCode?

VSCode is written in TypeScript which is then transpiled to JavaScript which can both run in the browser and on the desktop using Electron
PyCharm on the other hand is written mainly in Java, which will be a lot more work to port over to be able to run it on the client side within the browser nowadays (java applets are dead since quite a while back, and good riddance for that)

cerulean badge
#

I have models Resume and Education, and education have a fk to resume, I need some suggestions for the urls. I have the urls for list and detail view for resume - /resumes/, /resumes/<int:resume_pk>/ and for education list i have /resumes/<int:resume_pk>/educations/, what url do you suggest for the education detail view? i can do /resumes/<int:resume_pk>/educations/<int:education_pk>/ and then take the education pk to get the education object, here resume_pk is unnecessary and may make confusion, or i could just remove it and now the url is not as obvious as before, /resumes/educations/<int:education_pk>/

hushed glacier
#

is anybody here good at typescript?

drifting flare
#

If I want to set up a website where the user can upload an excel file and Python script will run to process that data to return another excel file, how can I do that?

arctic bluff
#

hi guys not sure if this is the right place but could someone explain what this means

#

[<Element h3 at 0x1034a7a10>]

#

im trying to scrape the text of this element

#

but get this on print

serene prawn
arctic bluff
#

i dont suppose you know how i can get the text from that element?

serene prawn
#

probably something like element.text

arctic bluff
#

!code

#
ebay = r.get(f'https://www.ebay.co.uk/sch/i.html?_from=R40&_nkw=ps5&_sacat=139971&rt=nc&LH_Sold=1&LH_Complete=1')

tree = html.fromstring(ebay.content)

sales = tree.xpath('//*[@id="srp-river-results"]/ul/li[2]/div/div[2]/a/h3')
print(sales.text)

#

print(sales.text)
AttributeError: 'list' object has no attribute 'text'

#

that is my code and that is the error i get below

#

lmk if this is the wrong channel as idk if web scraping counts as web development

mortal ledge
arctic bluff
#

is there another way to do it without xpath that wouldnt run into this issue

#

with .text i get error

mortal ledge
#

It isn't an issue. It seems that tree.xpath returns a list whether there is one or many elements found. In your case all you need to do is print(sales[0].text) and you will get the result you want.

arctic bluff
#

been doing this for hours

#

trying to google and couldnt find

hard whale
#

Ayo guys anyone has experience with SQLModel for FastAPI? I heard it collapses pydantic and sqlalchemy into same one file aka easyer to work with sql

#

Is it really that good?

#

I use 2 separate files now and sintax differences are a bit confusing

mortal ledge
# arctic bluff you are an absolute legend, thank you SO much

Idk about legend. If you want a more robust solution. Instead of just print element [0], iterate through the sales list.

for sale in sales:
    print(sale.text)

This will give you the same result, but if you did have many elements it would print each of them.

arctic bluff
#

thank you!

arctic bluff
#

it might be a problem with the site when im changing product tbf

#

is there any other way to get information without the xpath

#

as i need a different xpath depending on the user input

#

or possibly just take a screenshot of the whole page that the user inputs tbf

mortal ledge
#

List index out of range means that the you are trying to index an element that doesn't exists. So if you list has one element and you my_list[1] it will throw that error. If you are getting that error with [0] it means that you are getting an empty list.
If you use my second solution,for sale in sales. then this wont be a problem, it simply wont print anything. Another solution is to first test the list to make sure it is not empty:

if len(sales) > 0:
    print(sales[0])
else:
    print("nothing found")
arctic bluff
#

sweet

#

is it possible to take a screenshot, send it and then delete it straight after?

arctic bluff
#

ok nws, thank you anyway youve saved me for a lot of this project

mortal ledge
#

My pleasure!

rigid mist
#

Is there a way to run a python file (on the pc running the flask server) through a button on my website?

frank shoal
rigid mist
# mortal ledge What does the file do?

Well, I don't have any particular function there right now. Although I've tried to just open a picture to check if I even can start a file through a button, but it runs each time I save the python, and not when I click the button. If that makes sense?

rigid mist
frank shoal
#

you mean from html?

rigid mist
#

Yes, both from html and in the flask part of the server python file (if there is anything I need to fix there).

frank shoal
#
<button onclick="runFile">Run</button>

<script>
async function runFile(event) {
  event.target.disabled = true;
  try {
    await fetch("/runfile", {method: "POST"});
  } catch (e) {
    alert(e);
  } finally {
    event.target.disabled = false;
  }
}
</script>

in flask

@app.post("/runfile")
def run_file():
  subprocess.run(...)
#

the only part of the function that's really needed is fetch

#

the rest is boilerplate and can be excluded if you don't want to handle errors or double clicking

mortal ledge
#

I'm going to disagree with this approach. The js/ajax approach is fine, but I server side I would handle it much differently. First, you should have the server respond back with a some kind of a message "success" "fail" message so that the user get's feed back as to whether the function call was successful.

frank shoal
#

I was doing a very simple example.

mortal ledge
#

Second I wouldn't use subprocess. I would import the function into the flask file and call it from flask directly.

frank shoal
#

And yes, using a function is always better.

mortal ledge
# frank shoal I was doing a very simple example.

I get that, but in my opinion there are place to cut corners and providing a success feedback is not one of them, as it is simple enough to do. All you need is for your end point to return a jsonify'ed response with {"success": True} after the process returns (or False).

frank shoal
#

I'm also lazy, so there's that.

mortal ledge
frank shoal
#

Which is what I did. But it only alerts if there was a network error

mortal ledge
#
<script>
async function runFile(event) {
  event.target.disabled = true;
  fetch("/runfile", {method: "POST"})
  .then( resp => {
    if(resp.success){
      alert("Success that worked")
    } else {
      alert("Something went wrong with the python script")
    }
  })
  .catch (e => console.err("error:", e);
}
</script>
frank shoal
#

Why use the promise api in an async function?

#

just await it.

manic crane
#

can anyone help me with this error ? => django.db.utils.ProgrammingError: table "Occupy_clique_occupiers" does not exist

mortal ledge
stable bear
#

when is it better to use a web builder like wordpress, compared to full coding?

native tide
#

I'm working on a flask api but I want to use the api for other people not on my network how can I make it so the python script uses my IP address to fullfill the task?

real edge
#

Then it uses available inner IP dhcp adress so you could find it localaly, like in wifi

#

To through it available OUTER ( you need to got to your router and forward this ip in and port ) so anyone could see it by you're router IP and forwarded port

fickle basin
#

anyway to change the from in django when user select something without using jquery ?

#

or the more suitable way to do it drys

drifting flare
inland oak
sacred crane
#
api_names = ["/predict",'/predict_solubility','/predict_two','/predict_solubility_json']

@app.get(api_names[0])
async def predict(background_tasks: BackgroundTasks,solute,solvent):
    background_tasks.add_task(predict_dum.get(0),solute,solvent)
    return {'success'}

@app.get(api_names[1])
async def post():
    return {'result': response}
  
@app.get(api_names[2])
async def predict_two(background_tasks: BackgroundTasks,solute):
    background_tasks.add_task(predict_dum.get(1),solute)
    return {'success'}

@app.get(api_names[3])
async def post():
    return {'result': attach_drug_name()}

I am having a fastapi which does predictions on two end points and returns response. The background tasks were implemented using fastapi workers. Now how can i shift it to celery workers.

visual gull
#

It is very neat, simple and fast

dawn shard
#

anyone has some tutorial to split backend and frontend for beginners?

#

I have no idea how to do that, but looks like something funto try.

native tide
#

instead of 127.0.0.1

marsh canyon
#

you need find you local IP address and then use that instead of 127.0.0.1

#

@native tide

#

if you are on windows, try the command ipconfig

formal bronze
#

            'title' : forms.TextInput(widgets=attrs={'class':'form-control', 'placeholder' : 'Title'}),
            'description' : forms.Textarea(attrs={'class':'form-control','placeholder' : 'Description'}), 
            'category' : forms.CharField(attrs={'class':'form-control','placeholder' : 'Choose Category'}),
            'bid' : forms.FloatField(attrs={'class':'form-control','placeholder' : 'Place your bid here...'}),
            'url' : forms.URLField(attrs={'class':'form-control','placeholder' : 'Paste your url here...'}),
        }

I want to add placeholder but this error is coming
init() got an unexpected keyword argument 'attrs'

visual gull
hard whale
#

What is easier implemented with FastAPI (optionally SQLModel):

  1. Let cliend request data from db via API
  2. Just scrape this data from web page displaying the very same table
    ?
#

Webscraping tables must be tricky

inland oak
#
  1. let client request data from Backend app endpoint, that returns data in json format. The Backend app makes request to db.
jovial pine
#

hey guys

royal mountain
#

anyone can help me with django ?

inland oak
#

clarified more precisely

hard whale
royal mountain
#

form.py

class pForm(ModelForm):
    class Meta:
        model = personalInfo
        fields = (
            "religion",)
    widget={
        "relagion": forms.TextInput(
        attrs={"class": "form-control"}
  }
#

models.py

    reChoice = (
        ("select_one", "Select one"),
        ("islam", "Islam"),
        ("cristian", "Cristian"),
        ("hindu", "Hindu"),
    )
    religion = models.CharField(
        "Religion", choices=reChoice, default="select_one", max_length=50
    )
hard whale
#

But yes :)

inland oak
#

I am having fun. Migrate a django app from 3.0.8 to 3.2 version, which has 4000+ tests. and 420 out of them are breaking during migration.

hard whale
royal mountain
hard whale
royal mountain
#

anyway can anyone help me please.. dying here with problems and limitation 😦

hard whale
#

I wish I could bro but i myself a big noob :)

stark mesa
#

Im having troubles with django urls. for some reason my main urls cant detect my other 2nd apps urls. it worked fine for the first one

hard whale
#

Django is so complicated 😫

stark mesa
#

i love it tho. gets my brain going

hard whale
#

God bless fastapi

#

Doesn't get brain going but doesn't even require you to have one to do your stuff

royal mountain
stark mesa
#

alright

stark mesa
# royal mountain <@210904091721859074> can you help me with this one please and give us the code...

from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
path('admin/', admin.site.urls),
path('', include('store.urls', namespace='store')),
path('basket/', include("basket.urls", namespace='basket')),
]

if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

hard whale
#

Together we can

#

Lets make shitcoding great again

stark mesa
#

lets make coding great again

#

been tryna solvee this for almost an hour

#

i even tried this as a test if it would fix it

path('basket/', include('django.contrib.auth.urls')),
path('basket/', include("basket.urls", namespace='basket')),

#

if i cant fix this imma just put it on hold and just move onto another

inland oak
#
type_queryset = qs.annotate(
                    type=Value(type, output_field=CharField()),
                    date=Case(
                           When(previous_date=None,
                              then=F('next_date')),
                           default=(F('previous_date') + (F('next_date') - F('previous_date'))/2)
                         )
                )
#

Expression contains mixed types: DateTimeField, DurationField. You must set output_field.

#

how to fix errors like that?

inland oak
#
'date': Case(
                When(
                    previous_date=None,
                    then=ExpressionWrapper(F('next_date'), output_field=DateTimeField())
                ),
                default=ExpressionWrapper(F('previous_date') + 
                    ExpressionWrapper(
                        ExpressionWrapper(
                            F('next_date') - F('previous_date'), 
                            output_field=DurationField()
                        ) / 2, output_field=DurationField()
                    ), output_field=DateTimeField()
                )
            ),

Obviously somehow like this. But I have somewhere error 🤔

#

Lets think step by step.
next_date is a DateTime
previous_date is Datetime
their substraction is TimeDelta
/2 = still TimeDelta

previous_date + TimeDelta = DateTimeField. Looks like everything is correct, but it is wrong 🤔

#

how to debug it

#

step by step 😉

#

I don't get it

#
Case(
                When(
                    previous_date=None,
                    then=F('next_date')
                ),
                default=F('next_date')
            )

this works

Case(
                When(
                    previous_date=None,
                    then=F('next_date')
                ),
                default=ExpressionWrapper(F('next_date'), output_field=DateTimeField())
            )

this does not work

#

it is supposed to be working. It is the same F expression but with specified DateTimeField type...

inland oak
#

nvm. I solved it + multiple other cases, xD stuck in another one

royal mountain
#

is there a way to save multiple form data in one table ?

nimble berry
worn crystal
#

i have a db with a bunch of entries that i want to use in an autofill function
so like if a user types into the search bar- "pok"
under the search bar i want like the top 3 alike things pop up under the search bar. If anyone has a suggestion on how or what to look at to do this i'd greatly appreciate it

fast sun
#

Guuuys, strange question
What's safer: Django web framework or just FastApi?

stable bear
#

When using Flask, is it easier to use a MySQL database or a SQLite database?

fast sun
stable bear
#

If you use sqlalchemy, how would you deploy to heroku?
i have heard that you need something called postgres

fast sun
river remnant
#

or better, I use django

serene prawn
#

What do you mean by "safer" ?

fast sun
serene prawn
#

It depends on you really

fast sun
#

Also, vulns made by beginner

serene prawn
#

Most vulnerabilities come with authentication, authorization and input validation

#

I personally would not recommend Django for building APIs

nimble berry
fast sun
#

Thanks for answering :>

serene prawn
#

Django is just old at this moment, if you're building api I would use fastapi

nimble berry
serene prawn
#

Only advantage of using Django for me is built in authentication

#

And Django orm is just not very good

nimble berry
spiral kestrel
#

Hi guys , i got a customer that wants e-commerce website for one usage (concert ticket selling website) , i couldnt gave him a price , what do you think about it ? How much that costs generally

nimble berry
serene prawn
#

Fastapi just also has smaller footprint: no built-in orm, authentication, etc

nimble berry
#

exactly, much smaller code base and thous a smaller vulnerability cross-section, even though that is not a guaranty for more secure code on it's own

serene prawn
#

There's just much less potential risks

nimble berry
#

but on the other hand you have to bring in all those missing pieces from somewhere else and then you have to trust that code too

serene prawn
nimble berry
#

and that those projects are as vigilant about fixing security bugs in a timely manner and that the project has enough eyes on it to find those vulnerabilities

serene prawn
#

Also i can't stress enough about how bad django orm is 😦

nimble berry
royal mountain
#

I need a form like this.. I made a model and form .. but I can't split cuz all I know is {{ form.ap_s }} {{ form.as_table }} so can't split like that form.. so I made 1 model but 4 form with that.. it allowed me to split the form but it save differently 😦 I need it on one table

#

forms.py

from email.policy import default
from logging import PlaceHolder
from django.forms import ModelForm
from django import forms
from .models import personalInfo


class fForm(ModelForm):
    class Meta:
        model = personalInfo
        fields = (
            "fName",
            "fcNum",
            "fOccu",
            "fEmail",
            "mName",
            "mcNum",
            "mOccu",
            "mEmail",
        )

class pForm(ModelForm):
    class Meta:
        model = personalInfo
        fields = (
            "inProgram",
            "shift",
            "session",
            "section",
            "sName",
            "cNum",
            "email",
            "gender",
            "bCert",
            "image",
            "religion",
            "doBirth",
            "pAds",
            "bGroup",
            "nationality",
            "quota",
        )
class e1Form(ModelForm):
    class Meta:
        model = personalInfo
        fields = (
            "eTitle1",
            "board1",
            "eGroup1",
            "bRoll1",
            "eResult1",
            "pYear1",
            "insName1",
        )```
#

view.py

import calendar
from calendar import HTMLCalendar, month_name
from datetime import datetime
from django.shortcuts import render
from django.urls import is_valid_path
from .forms import pForm, fForm, e1Form, e2Form, d1Form, d2Form
from .models import personalInfo
from django.http import HttpResponseRedirect

def addmission(request):
    submitted = False
    if request.method == "POST":
        form = pForm(request.POST, request.FILES)
        form2 = fForm(request.POST)
        form3 = e1Form(request.POST)
        form4 = e2Form(request.POST)
        form5 = d1Form(request.POST)
        form6 = d2Form(request.POST)
        if (
            form.is_valid()
            & form2.is_valid()
            & form3.is_valid()
            & form4.is_valid()
            & form5.is_valid()
            & form6.is_valid()
        ):
            form.save()
            form2.save()
            form3.save()
            form4.save()
            form5.save()
            form6.save()

            return HttpResponseRedirect("/addmission?submitted=True")
    else:
        form = pForm
        form2 = fForm
        form3 = e1Form
        form4 = e2Form
        form5 = d1Form
        form6 = d2Form
        if "submitted" in request.GET:
            submitted = True

    return render(
        request,
        "addmission.html",
        {
            "form": form,
            "form2": form2,
            "form3": form3,
            "form4": form4,
            "form5": form5,
            "form6": form6,
            "submitted": submitted,
        },
    )
serene prawn
royal mountain
frank shoal
#

With flask, is it possible to specify some default options when using flask run?

royal mountain
frank shoal
#

e.g. ```py

app.run(
debug=True,
extra_files=[
Path("pages").glob(".md"),
"settings.toml",
],
)

nimble berry
royal mountain
outer geode
#

https://paste.pythondiscord.com/luhoyasewu can you help me with some different code i want to work out average pixel whiteness of image. my code i wrote i think the library doesnt support transparency, i have transparency in my image

stable bear
#

Is it possible to convert a flask web app into a desktop app?

stable bear
#

like an equivalent of electron js

#

a desktop app with the same ui and working in the same way as a flask web app

nimble berry
stable bear
#

standalone would be ideal but i dont think thats possible

#

but the same ui, with api requests would be fine

paper moon
#

Well, I had a problem before, thought it was a ports issue but seems like its one with quart. I have a help channel opened, anyone mind looking at it? #help-pancakes

nimble berry
coral hatch
#

Hi I'm having some issues using fastapi with prisma client python. I'm trying to use prisma model like this:

@app.post("/add_temp")
async def add_temp(temp: Temp):
    await db.add_temp(temp)
    return {"msg": "ok"}

the problem is that fast api expects the model Temp to have a field called id even though it's supposed to be generated.

outer geode
#

someone help me sum all pixel colours?

austere acorn
jaunty depot
#

hey guys
I deployed my flask app to heroku, but when I tried to access it for the first time, I got the application message that my page could not be served. In the terminal I got at=error code=H10 desc="App crashed" method=GET path="/" with status=503 and such status means that the server runs properly but can't be served at this time

does that really mean that I should just wait or what? is there a problem in my code? because my application runs with no problems locally. I've already waited 15 minutes and heroku still can't serve my page. Does anyone know what is going on?

#

restarting heroku did not help

#

my Procfile also looks correctly (no unnsecessary spacing) etc

coral hatch
#

I think it's supposed to work but maybe I'm making some mistake

serene prawn
coral hatch
#

what am I supposed to use theb

serene prawn
#

Create a schema model

coral hatch
#

because this is how I do it with expressjs in typescript

serene prawn
#
class PostSchema(BaseModel):
    id: str
    title: str
    content: str

class PostCreateSchema(BaseModel):
    title: str
    content: str
coral hatch
#

oh so I guess I will just have to do it this way

#

huh pretty annoying I'd say

serene prawn
#

It's not, your api schema shouldn't depends on your database models

coral hatch
#

the point of Prisma is to have a prisma.schema file that has models which are converted into classes that I can use normally

serene prawn
#

Well, but these are still your database models

#

You might need to change your database structure, your schema on the other hand shouldn't change

coral hatch
#

I see

serene prawn
#

Or you risk taking down prod 🙂

#

Because your clients (frontend, other services) used different schema

coral hatch
#

anyways thanks for your help I will look into it tomorrow

pseudo zenith
#

hello is there a server for django framework?

worn crystal
#

Is there any library or something that I can use for my flask app that I can use for autofill suggestions?

mint folio
tacit depot
#

Hi

#

For django developers how d u test abstract models without inheriting it

orchid fox
#

Hello may I ask what license would you guys use for your website ?

#

I'm trying to pick a license but I don't know which one to choose because there are so many/

frank shoal
patent glade
#

Okay, so like

#

Am I crazy?

#

Or is the DOM as implemented in Javascript fucking bonkers?

#

Example: The Document object is a node, except can't be/have a parent and can't be/have any children. All it gets, really, is inheriting from EventTarget by proxy

#

Window is NOT a node, even though its relationship to the rest of the program is pretty much the same as for Document, but window DOES inherit EventTarget directly

#

Attribute inherits from Node also, even though its basically just a tuple consisting of a name and a value (and of course, all the extra bagage it inherits from Node)

#

And yet a dozen other component classes of Element DONT inherit from Node

sacred crane
#

I am having a fast API that does ml predictions and uses celery for task queue.

prediction code

response = {}
async def predictions(solute, solvent):
      m = Chem.MolFromSmiles(solute,sanitize=False)
      n = Chem.MolFromSmiles(solvent,sanitize=False)
      mol = Chem.MolFromSmiles(solute)
      solute = Chem.MolToSmiles(mol)
      mol = Chem.MolFromSmiles(solvent)
      solvent = Chem.MolToSmiles(mol)
      interaction_map_one = torch.trunc(interaction_map)
      response["interaction_map"] = (interaction_map_one.detach().numpy()).tolist()
      response["predictions"] = delta_g.item()

and my function in worker.py

from model.model import predictions, response
@celery.task(name='predictions')
def predictions(solute, solvent):
    return {'result': response}

and main.py where i create the celery task

@app.get(api_names[0])
async def predict(solute,solvent):
    task = predictions.delay(solute,solvent)
    return JSONResponse({'task_id': task.id})

Actually, I am migrating from fast API background tasks to celery and facing problems with returning responses. When I am running it is giving an empty dictionary celery which means it's not running the prediction. But I don't know where I am doing wrong. If you can check the below picture you will understand what I am saying.

I am guessing I have done some wrong in the worker.py but not sure what it is.

nimble berry
# sacred crane I am having a fast API that does ml predictions and uses celery for task queue. ...

what are you expecting to get back as a result from the call after you have migrated to celery?
remember that the celery job will probably not have run yet when you send the client the response, so you can't really reply with any result, only something like a job id that they can then poll for at another endpoint later in a loop with a pause in between each try and then break out of the loop when that endpoint with that job id returns something meaningful

solid meadow
# coral hatch anyways thanks for your help I will look into it tomorrow

I agree with @serene prawn, separation of concerns between your database and your API is important. Currently you can automatically generate additional pydantic models with only certain fields, make certain fields optional or required and point relational fields to another model. The only feature that is missing is renaming fields.

coral hatch
#

and how can I do that

solid meadow
coral hatch
#

oh I see

#

either way I created another pydantic model for it so it works fine

solid meadow
#

Yeah that works too, the benefit of using Prisma's built in support for partial models is that you don't have to redefine the types

#

And if you don't care what fields are in the model, you just want non-relational fields only you can easily do that too without having to update all your models

coral hatch
#

yeah I'm trying to rewrite my prisma typescript express server in python so I was a little disappointed when I had to redefine the types again

solid meadow
#

yeah I was in a similar situation and was annoyed that I had to redefine the types, that's why I added partial model generation :)

coral hatch
#

also do you know if there is a OR keyword in prisma python? Because I couldn't find it

#

like I can do this in normal prisma:

    return await prisma.temp.findMany({
      where: {
        OR: [
          {
            "d": { "in": nowDays },
            "m": new Date().getMonth() + 1
          },
          {
            "d": { "in": beforeDays },
            "m": weekAgo.getMonth() + 1
          }
        ]
      }
    });
solid meadow
#

What editor are you using?

coral hatch
#

lunarvim (neovim) at the moment

#

I'm running the pyright language server

#

I should be using pylsp as well I know

#

my bad

solid meadow
#

Ah I was just about to recommend that

coral hatch
#

although I'm not sure if they work well together

#

because pylance in vs code has to be a little different than pyright I think

solid meadow
#

Are you getting autocomplete for Prisma Python queries?

coral hatch
#

yeah I am

solid meadow
#

Great :)

#

I know some people struggled to get that setup so I just wanted to make sure you had it setup

#

It's arguably the best feature imo

coral hatch
#

yeah it's really good

solid meadow
#

Let me know if you have any more questions :)

coral hatch
#

I don't think I do so thanks for your help 🙂

#

actually I may have one question @solid meadow, is there a way to ommit the #type: ignore so pyright doesn't complain about id being None as seen here:

    async def add_last_temp(self, temp: TempClass):
        last_temp = await LastTemp.prisma().find_first()
        if last_temp is None:
            await LastTemp.prisma().create(data=jsonable_encoder(temp))
            return
        await LastTemp.prisma().update(where={'id': last_temp.id}, data=jsonable_encoder(temp)) #type: ignore
solid meadow
#

If it's like ```prisma
model LastTemp {
id String? @id
}

#

Then you've marked the id field as optional which means you could run into a situation where last_temp.id is actually None

#

You could either handle that case by raising an error or update your model so that the id field isn't optional

vivid canopy
#

guy's what u think about rpa developer

coral hatch
solid meadow
#

Yeah that's right

zealous oar
#

Hey, I have a Django Rest API endpoint that takes some data + image as an input, I'm trying to test this endpoint but I face a problem with sending an image
serializer.py

class CreatePackageSerializer(serializers.Serializer):
    workshop_id = serializers.IntegerField()
    title = serializers.CharField(max_length=550)
    price = serializers.FloatField()
    image = serializers.ImageField()

and sending data like this by Pytest

from PIL import Image
img = Image.new(mode="RGB", size=(200, 200))    
data = {
    'workshop_id': 1,
    'title': 'Package Title',
     'price': 33,
     'image': img
   }

so drf gives my this error

AssertionError: assert [ErrorDetail(string='The submitted data was not a file. Check the encoding type on the form.', code='invalid')]

so, my question is how I can send the image as a file?

autumn veldt
#

this is more js then python but idk whare to ask cause no one answers me

#

i want to build extension when someone clicks on it runs a js code on the website the user is in, can someone help me please?

coral hatch
rigid laurel
covert yew
#

does someone know how can I get and save a photo that user as uploaded in flask?
without flaskForms if possible

rigid laurel
#

request.files?

#

If they're submitting a form it should just be a post request with the find file found there

covert yew
rigid laurel
#

It's a dictionary like object where the key will be the filename

#

I tell a lie

covert yew
#

I get this

rigid laurel
#

The key isn't the filename

#

It's whatever the form key is I think

#

The docs are here

covert yew
#

alright

#

thanks <3

dense slate
#

If you want to run it from your page without refreshing it, you should look into setting up a request via ajax. This sends a request to your server and then you can use the returned data/response.

#

If you don't care about it refreshing, you shouldn't need javascript.

iron tusk
#

complete beginner here. What is the best way to implement that kind of animation

#

As my site-background till the user picks a choice on where to go?

snow crater
#

Hello. I'm very new to web development and programming in general. I was wondering what is the typical workflow when using django or other python frameworks for building projects. For instance, I heard that its a good practice to work with django or other python projects in a virtual environment, but im confused how that would play out when using github. Say If I made a web app using django under a virtual environment, so i also have to upload the files of the venv to github? What's the norm when it comes to this things? (I am new, so try to help me understand please)

serene prawn
#

I would try something like poetry which uses venv under the hood

warped lance
#

Can anyone guide me how to host JustPy website? I used Pythonanywhere for flask but it doesnt support justpy i cant seem to find anywhere. I want to share with others not just localhost

#

In simple words i want to share my justpy project with friends

#

So they can test some functions for me

swift wren
# iron tusk

you can either match the black color through a screenshot and then color picker it and use the hex value

ionic raft
# snow crater Hello. I'm very new to web development and programming in general. I was wonderi...

You've got a number of concepts jumbled up. And I get it...when I started I was very lost.
You can program with Python. Python has a lot of flexibility in the ways it can be used (use cases). When you program in Python you can create a virtual environment. This creates a safe space, or rather, an independent space where different tools you use (libraries) can be installed and offer you more potential and power. Python is such a well-used language that there are many, many tools (libraries) that many people have built that do many things.
Django is one such tool. It is a web development framework that, like Flask, allows you develop web applications. If you really want a web application that offers enterprise level administration and security, Django is a great place to start. If you want a simple website, Flask is recommended as a better starting point than Django in some ways, particularly because working out how web servers work is a whole layer of complexity when new.
GitHub is a tool that is a version control system. In other words, every time you update your program (in a github repository) git (the tool behind github) will track the changes, down to the individual characters. This is really helpful because software engineering is hard. When you build a web application in Django, for example, you'll be working with the presentation layer (how web pages appear), manipulating the application layer (with lots of logic, that will in effect allow you to build workflow) and building/using a database to work with data.

What is the norm? There are so many flavours of norm that there is no norm. I'd suggest thinking about a problem you'd like solve. Maybe it's a problem that can be broken down into a number of different problems. Then I'd learn how to program with Python.

nocturne mica
#

Yo guys hope y'all are doing good!

My Problem:
I am trying to store a SQL query in SQLite in a variable so I can use it to show it on a Flask Website

#

My Code:

import sqlite3
from flask import Flask, render_template

app = Flask(__name__)

@app.route("/results")
def results():
    conn = sqlite3.connect("Database\database.sqlite")
    database = conn.execute('''SELECT * FROM twitch_data''')
    
    return render_template("result.html", content= database)

app.run()

#

HTML:

<!DOCTYPE html>
<html>
    <body>
    <p1>
        {{content}}
    </p1>
    </body>
</html>
#

Can anyone tell me what is the appropriate way to store a SQLite query in a variable?

#

i wasnt sure if i had to use Available Help Channels or this channel

#

hope it's not an issue

forest walrus
#

Hi

#

Anyone have experience in using JWT tokens in Login

north apex
#

Css file not supported in pycharm. Please help how to solve this

cerulean badge
#

logo_django2 can you use modelserializer for nested serializer?

cerulean badge
#

I have 2 models A and B and B have fk to A, i have model serializer for both and want to just include a list of related B in A's model serializer. can i just use the B model serializer to nest it in A? like this?

class B(serializers.ModelSerializers):
  ...

class A(serializers.ModelSerializers):
  ...
  list_of_b = B(source="b_set.all", read_only=True, many=True)
toxic cave
#

hi guys, i kindly need your help, i can't seem to serve my static files whatsoever and i'm terruble at explaining

normal token
violet willow
#

i'm trying to center some text in a html table, the css looks like this

.tablee + td{
  text-align: center;
}```
But it doesn't do anything, if i just do something like this it works, can someone help me ?
```css
td{
  text-align: center;
}```
terse niche
#

hey guys i have a question, I am creating a website using django and i want to create a desktop version for it in future so how would i make it interact with the database in my web application?

inland oak
#

Hello. I have a problem with Django rest framework.

ViewSet has get_queryset which aggregates one big queryset with a lot of data.
one of the fields named organized_id is present in the returned objects
But it is not recognized as field which I could use to order_by/ordering.
what could be the problem? Perhaps I could make somehow the field recognized

gusty hedge
dense slate
dense slate
inland oak
#

so far I was able to make a trick of

dense slate
#

bla bla bla are the other fields?

inland oak
#

yeah

dense slate
#

Do you need to declare the field somewhere before using it?

#

like admin.py you declare the fields included

inland oak
#
annotate(
organizer_id=OuterRef('organizer_id'),
)

if I annotate by OuterRef
I can order_by this field then

but the query breaks later because OuterRef field has no declared is_summary thing

inland oak
#

the main magic happens in this ViewSet in function
def get_queryset(self):

where the queryset is formed. There is the problem, as this field is incorrectly queried. Not fully formed into the query columns

dense slate
#

Ok, so whenever I run into that error with REST or GQL, it's because I didn't include it in the fields that have to be declared.

#

but it looks like ordering_fields is where you do that

inland oak
#

The problem appears because queryset is formed using custom made multidb_objects.prefertch_related thing

#

it is a bit of complicated

#

I am trying to find just a hack around it in order for the field being recognized

dense slate
#

This was on SO: "Did you enable cursor pagination in your settings?"

#
REST_FRAMEWORK = {
    ...
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.CursorPagination',
    ...
}```
inland oak
#

too bad organizer_id=F('organizer_id'), is not working, the field is not recognized error again)

inland oak
#

another custom made thingy

dense slate
#

Well, if you're hacking it, then something must be setup incorrectly. If it's an ID field, I would think it should work without issue.

inland oak
#

I wish to do in some way at least

dense slate
#

What if you remove 'name' from ordering?

#

Does it work with just the organization_id?

inland oak
dense slate
#

Can you order by the id before you get the set?

#

Where the original queryset is formed

inland oak
dense slate
#

I think we can both agree I solved your problem 100%. 😄

inland oak
native tide
#

guys, do you know if type attribute is necessary for <source> tag?

#

or it is optional

warped lance
#

Does no one know how?

glad swallow
#

Hi everyone. I have inherited an Angular application that was generated by Angular CLI version 9.0.2. I have the following in my Dockerfile: https://bpa.st/UFIA. When I run docker compose up frontend --build, I see the following error: https://bpa.st/7BXQ Is there a way to upgrade the Angular dependencies to newer ones then manually update the code to use new Angular API (for lack of a better term)? Thanks.

rigid laurel
#

you'd probably be better off asking in a JS discord

#

!resources communities

lavish prismBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

rigid laurel
#

on that page is a link to a big list of Discords

#

there's definitely JS ones on there, and probably an Angular specific one

glad swallow
#

Hi. Yes I did take a look but the invite links of the JS one seem dead. Also there wasn't any that was Angular focused.

gaunt tangle
#

how I can enable ssl on django

timber jungle
#

YES!

I have managed to integrate Select2 ( search in dropdown ) with a list in python 😄
It is working beautifully.

                                        <div class="rs-select2 js-select-simple select2-search">
                                            <select class="" name="projectid" required>
                                                <option value="" selected disabled>Select a Project</option>
                                                    {% for element in gcpprojects %}
                                                       <option value="{{element}}"> {{element}}</option>
                                                    {% endfor %}
                                            </select>
stable bear
#

I would like to apply <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> to only a section of a webpage, with the rest being in bootstrap. How can I do this?

frank shoal
#

Looks like most of the classes are prefixed with w3-

#

I would just copy what you need and make your own css file

#

Most of what isn't prefixed with w3 is normalize, which bootstrap provides as well.

#

Other than that, it sets the default font and sizing for html, body, and h elements

timber jungle
#

If i have a container / wrapper. How can i make some elements go outside of it?

frank shoal
#

position: absolute; ?

timber jungle
#

i will try, thanks

vernal basin
#

hello everyone

how can i fix this error ??


django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

#

I created a script that must run with crontab in a django folder but when I import the models to insert data I have an error.

native tide
gusty hedge
#

still you might need to define where your settings are

midnight night
#

Hey Guys,

Looking for some guidance.

So I am creating a web app using django as the backend that tracks the stats of nft project prices.

I would like to know the best way to load this db , If I should be using the post from the api or loading directly with mysql.connector or another direct method. I'm worried about the slugs and the timestamp when loading from with python

Also I would like to show charts of the prices changes how can I accomplish that with django and the front end? Looking up data from 3 days and comparing it to now.

This will be a prob website so optimization will need to be in mind

vagrant dew
#

How could I connect a django app running on an aws server to a domain I bought?

native tide
#

Is there a way to import HTML into another HTML file? For example, I have a base.html file and I want to have the content in a separate HTML file named content.html.

hushed glacier
#

hi i am doing an assignment and im getting these errors
this is my code btw

#
import {courseType} from "/home/udit-waghulde/Assignment_3/services/Course/course-service";
import {instructorType} from "/home/udit-waghulde/Assignment_3/services/Instructor/instructor-service";
import {Instructor} from "/home/udit-waghulde/Assignment_3/services/Instructor/Interface/instructor-interface";

export class Course implements courseType {
  
  CourseDetailsByInstructor: any;
  course: any;
 
  CourseDetailsByCid(CID: string): courseType{
    let item: any = this.course.find((item) =>item.CID == CID);
    return item;
  }
    static find(_arg0: (item: any) => boolean): any {
        throw new Error("Method not implemented.");
    }
  
  private CourseDetailsByInstructors(Email: string, info: any){
    if (info[Email] !== item2[Email]){
      info[IID] = item2[IID];
    }
    this.course.push(info);
  }; 
let course = [
    {
        CID: "215e77ee-ba6d-486f-95ce-0e0c0fb4b919",
        Title: "Programming In Javascript",
        IID: "185e77ee-ba6d-486f-95ce-0e0c0fb4b919",

    },
    {
        CID: "225e77ee-ba6d-486f-95ce-0e0c0fb4b919",
        Title: "Structural Analysis",
        IID: "195e77ee-ba6d-486f-95ce-0e0c0fb4b919",
    },
    {
        CID: "235e77ee-ba6d-486f-95ce-0e0c0fb4b919",
        Title: "Power Electronics",
        IID: "205e77ee-ba6d-486f-95ce-0e0c0fb4b919",
    },
];
function Email(Email: any): any {
  throw new Error("Function not implemented.");
}
latent cedar
#

is there somewhere i can go to talk to other poor devs that got stuck creating microsoft canvas/power apps? im having some growing pains trying to trick microsoft dataverse and the app builder into functioning like real development tools.

agile pier
#

I have a technology field in my django model asset_inventory_active

#

These are some of the values of the field

#

I want to get the count of each technology, those separated by commas also
Example- count for Nginx- 2, because the last field contains Nginx tech and the first field also contains Nginx tech

#

How do I separate all tech if they separated by commas, and get their count also

#

top_techs = asset_inventory_active.objects.values('technology').annotate(tech_count=Count('technology')).order_by('-tech_count')[:5]

agile pier
worn crystal
#

i'm trying to implement jquery autocomplete in my flask app and was wondering if I could use a python variable that i passed into my html page as a var in some script

    <script>
        $(document).ready(function() {
          var some={{content}}  
          var tags = [
                 "Washington", "Cincinnati",
                 "Dubai", "Dublin", "Colombo",
                 "Culcutta"
            ];
                 
            $('#hello').autocomplete({
                source : {{content}},              
                select : showResult,
                focus : showResult,
                change :showResult
            })
                   
            function showResult(event, ui) {
                $('#cityName').text(ui.item.label)
            }
        });
/script>
#

var some is what i want to happen but it doesn't like it currently

mental summit
celest pivot
#

jquery....

#

Who using

#

that

#

these days?

worn crystal
#

is there a better way to do it?

lavish prismBOT
#

:incoming_envelope: :ok_hand: applied mute to @earnest dagger until <t:1650525486:f> (9 minutes and 59 seconds) (reason: duplicates rule: sent 4 duplicated messages in 10s).

sudden grotto
#

What are the pros and cons of using Nameko as a micro service web framework?

devout sparrow
#

Hi

#

Hi
Anyone familiar with flask form validation? I really need some help 😦

plucky wadi
#

What are the use cases of django channels ? (other than chat app)

devout sparrow
#

Hi

#

Anyone can help out with flask

simple river
#

Hi! I'm mainly a backend developer, but I want to build a web application. I have been using FastAPI earlier without a database connection, which was awesome. However, this web application is more complex and should include a database. Is Django probably a better choice since its opinionated (which I like)?
A big community is great but I would rather use new and improved technology, if it's well documented and on the rise.

Also, I've been thinking of using a modern frontend framework, like ReactJS or Svelte.

main yacht
#

I built a website where you can practice your programming skills by working on weekly projects to improve your skills. All skill levels welcome! https://www.devjam.org/. This may be useful to some of you who want to try putting your skills to the test against others.

wicked pier
#

Hey, whats up with livereload dying when I update Python?
It works fine if I change the template, but it dies if I try to update any Python files

#

Am I doing something stupid here

inner oasis
#

Guys I'm building a blockchain app using typescript and express i just started building it should I switch to python and flask or python and django (NOTE: My app only uses REST)

gusty hedge
scenic dove
#

Hello im making a Post model using django and want the post to have as many images as the user wants to post, how to implement this ?

#

tried typing the option (many=True) like in the django rest framework but it look like django doesnt have one

mental summit
#

You can have a model that contains an image and a ForeignKey that points to a specific post

scenic dove
#

but that means only one image for a post right?

mental summit
#

No

#

You can create many image models with the ForeignKey pointing to a specific Post

scenic dove
#

i dont understand

#

hows this different from just leaving the image field inside the Post model

scenic dove
#

oooh

#

i get it

#

lol

#

thanks

#

if anyone has other ways of doing this let me know about it

#

@mental summit this way right?

mental summit
#

Looks good

azure lily
#

Hey guys new to the server and django for that matter.. I used the built in auth & auth models provided. However, when I make my own model (Member) I can't call all results and display them. (works for user model). Do I have to specify something as I've imported the member class.

#

I've detailed it and put my code up there, any help or suggestions would be great

native tide
#

trying to darkmode a page which works for the main homepage however on this site for some reason the <body> is only registered as that tiny top section. any ideas why. site is running flask btw and the production site is apache2

queen horizon
#

Hello there, I have a very weird bug. Every time I save this file, and only this file. It gets completely emptied. Also my code doesn't recognise the € character, it shows as a �. Does anyone know how to fix this?

queen horizon
#

Problem fixed, not using the € symbol apparently

twin vector
#

Weird @queen horizon

#

Maybe using the html symbol for Euro might work? They are called html entities afaik

queen horizon
#

Well that works

#

But it's kinda stupid, because in the files my friend made the € works fine

worn crystal
#

so purely theoretically.. how bad is loading flask variable "content" in this instance with a lot of entries(maybe 80k max of just names) and using it in jquery autocomplete?..


@app.route("/test", methods=["POST", "GET"])
def test():
   if request.method == "GET":
      languages = ["C++", "Python", "PHP", "Java", "C", "Ruby",
                     "R", "C#", "Dart", "Fortran", "Pascal", "Javascript","joe","Joestar","Jotaro","john"]
          
      return render_template("testing.html",content=languages)
   elif request.method == "POST":
      user=request.form["em"]
      return render_template("testing.html",content=user)
    <script>
        $(document).ready(function() {
          var some=JSON.parse('{{content|tojson}}');
 
                 
            $('#hello').autocomplete({
                source : some,              
                select : showResult,
                focus : showResult,
                change :showResult
            })
                   
            function showResult(event, ui) {
                $('#cityName').text(ui.item.label)
            }
        });
    </script>```
#

i want to do autocomplete searches off of a database of names i have and that's why i ask

worn crystal
#

Like could I potentially do this

Names= db.execute(SELECT * FROM table_name)
return render_template("testing.html",content=names)```
#

Without much consequences?
(Also, sorry for the syntax/ formatting typing from mobile atm)

sturdy idol
#

For flask, Is there a way I could specify a version variable in my app.py and use it in my base.html without passing the version variable in every render_template statement? I understand that I could just hard code the value into the html, but I want my app.py to handle the versioning so it shows on GitHub

brisk drum
#

Guys i need to check when a button which is normally hidden is displayed in a website and if it is displayed then click it, there is a way?

native tide
#

Java script is best for web development

brisk drum
#

the website isn't mine so D_D

rigid laurel
#

Depending on specifics, selenium, a Chrome extension, or just a simple js script pasted into the console is probably the way forward

torn ledge
#

how to make flask_basicauth only get password
cuz flask_basicauth needs a user and a password, i want it to only need a password

brisk drum
rigid laurel
#

Well selenium has a pretty reasonable python interface. I've not used it but I don't think it's too difficult to get set up. That's definitely where I'd recommend looking

brisk drum
#

i'm starting documenting

manic crane
#

i keep getting this error in my django app => django.db.utils.IntegrityError: insert or update on table "authtoken_token" violates foreign key constraint "authtoken_token_user_id_35299eff_fk"
DETAIL: Key (user_id)=(1) is not present in table "Occupier_occupier".

dense cedar
nimble berry
# torn ledge how to make flask_basicauth only get password cuz flask_basicauth needs a user a...

just prompting for a password with out even displaying the username field can't be done with what is built-in to the browsers by default
using your own code you could just ignore what ever is filled in to the username field and a blank username should probably work as well in that case and just check the password
if you don't want to display the username field you have to roll your own and you could probably make something similar using javascript for the prompting of the password

that said, i would highly advice against any of those solutions for more reasons than i care to enumerate here
you can go and check what was written on the subject many years ago even if the question isn't 100% a match and it has been a while most of the reasons holds true still
https://security.stackexchange.com/questions/20072/using-only-password-to-authenticate-user-no-username-field
https://security.stackexchange.com/questions/2384/why-do-we-authenticate-by-prompting-a-user-to-enter-both-username-and-password

nimble berry
agile pier
#

how do I resolve ERROR for site owner: Invalid key type google recaptcha v3 error on django

#

my captcha settings seems good

#

pls help

native tide
#

hi, guys
need a help with django: i have a custom implemented django user inherited from AbstractBaseUser and i need to create roles like student, teacher and etc with extended fields
can you share links, articles or something else to implement this thing? checked veryacademy on youtube, but don't think that it is for me

devout sparrow
#

Hi

#

Anyone can help with bootstrap

stable bear
#

how do you make a bootstrap nav bar, which has this feature?: when you click on a page, there should be an indication that you are on the services page.

digital oracle
stable bear
#

is there a way to do this with a layout.html instead of having to include the nav bar in every page?

thorny skiff
outer apex
nimble berry
devout sparrow
#

@nimble berry I'm trying to apply a bootstrap template to my table

nimble berry
#

it selects all div elements which has a article class

devout sparrow
#

@nimble berry I m not sure how to do

stable bear
#

If a flask/django web app is hosted on a vps service like linode/digital ocean, would a sqlite3 database still work?

devout sparrow
nimble berry
# stable bear If a flask/django web app is hosted on a vps service like linode/digital ocean, ...

it depends on the service, but generally for vps the answer is yes, you need presistent storage that you can trust and if they offer backups of that storage it's even better

then you have providers like heroku that don't offer vps service, ther the answer is instead generally no as you don't have access to persistent storage, there you are recommending to use a external database like a PostgreSQL server or as a service that they can provide

native tide
#

she said that she just wants it as a project

#

she ain't planning to host it ig

native tide
#

idk why i'm telling but ... lol nvm

#

i was talking about jessicaM

#

sorry

#

well in your case rndpkt already answered

#

but still telling

#

that if u host on heroku u will get postgresl-add on @stable bear

#

you'll just have to look on the web about how to host your django app & configure its db with your app

#

that's all

#

where else r u planning to host?

#

:")

#

i would personally recommend heroku if u want to go for free

#

since i'm not aware of any free vps...

#

so yeah

#

:")

native tide
nimble berry
# native tide since i'm not aware of any free vps...

GCP has an always free tire, with their e2-micro you'll have free hours to last you a howl month if you only run one of them, or you can run a few hundred for much shorter time

there are limitations on amount of storage and network traffic and such as well that you need to manage to keep it free

worn crystal
#

Anyone know of a way I can pass a bunch of db results to my html page? I'm doing this in flask as well

nimble berry
worn crystal
#

Yeah?
I'm using sqlalchemy so I'm making an engine object and then doing like db.execute(SELECT * FROM table_name) to get results

#

Well that gets me a pointer i believe

#

@nimble berry

nimble berry
native tide
#

so i've finished with my personal project, i'm just looking for tips on decoration / presentation...

if someone has any spare time, could they go through and check my code out to point out a few things, or redecorate the file entirely?

#

if anyone is willing to, could they dm me

mortal ledge
#

It seems that Flask jsonify doesn't preserver the order of the input dict. Is there away to ensure that the dict in is in the same order as json string that it returns?

Otherwise I suppose I could simply use json.dumps to create a string and the set up a manual json response (ie: by setting response headers).

nimble berry
mortal ledge
mortal ledge
mortal ledge
# mortal ledge After some investigation, it appears that this is not exclusively an issue with ...

So I tried sending the response text/plain and that solves the problem. Here is the solution in code in case anyone is curious:

json_str = json.dumps(my_dict)
response = await make_response(   #await because I'm using Quart not Flask.
    json_str,
    { "Content-Type": "text/plain; charset=utf-8" }
)
return response

The response header on the client side is as above (as expected) and the browser displays the string as is without parsing the JSON into an object first.

nimble berry
mortal ledge
nimble berry
mortal ledge
nimble berry
mortal ledge
native tide
#

can someone run through my code and tidy everything up?

fiery rampart
native tide
fiery rampart
#

I don't really find any issues. It looks pretty good. The only change I would make is instead of

If not x:
  return False
return True
#

You can do return x

native tide
#

in those cases, for example 'emails'

#

the if not is testing to see whether there have been any emails fetched or not

#

if i was to return emails it'd be giving me the emails fetched, when all I want is to check if it exists

native tide
fiery rampart
#

By presentable do you mean easy to read?

native tide
#

i guess so yes

fiery rampart
#

I would say having your classes and routes in different files

#

Have each file's functionality clearly defined

native tide
#

the classes and subclasses, i've definitely not worked them right - are u able to run me through how i could better them?

fiery rampart
#

Why would you have User inherit from Database is there anything in the database that the user needs?

native tide
#

nope, i forgot to remove it

#

it's declared in __init__ of user now

#

self.database = Database()

fiery rampart
native tide
#

because the cursor returns something like [()] if it doesn't exist

#

which isn't None

fiery rampart
#

I'm guessing its because cursor.execute returns an object. You could add .first_or_none() to make sure it returns a workable values

native tide
#

to the cursor?

fiery rampart
#

What framework are you using?

dense cedar
ruby sorrel
#

hello everyone 🙂 noob here,
you guys know css?

im trying to copy this guy's flex but i cant get it to work the same way

his are centered

#

while mine are stuck to the side

#

any ideas?

* {
  box-sizing: border-box;
}

body {
  margin: 0;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  min-height: 100vh;
  display: flex;
  align-items: center;
  font-family: 'Inter', sans-serif;
  background-color: whitesmoke;
}

.contacts {
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
  gap: 40px;
}

.contact-card{
  flex-basis: 225px;
  box-shadow: 1px 1px 8px rgba(0, 0, 0, 0.25);
  border-radius: 10px;
  display: flex;
  flex-direction: column;
  padding: 13px;
  padding-bottom: 20px;
  background-color: white;
}

.contact-card > img {
  width: 100%;
  height: auto;
  align-self: center;
  border-radius: 5px;
  object-fit: cover;
}

.contact-card > h3 {
  font-weight: 700;
  font-size: 18px;
}

.info-group {
  display: flex;
  align-items: center;
}

.info-group > img {
  height: 11px;
  margin-right: 8px;
}

.info-group > p {
  margin-block: 3px;
  font-size: 12px;
  color: #2B283A;
}
ruby sorrel
#

figured it out it was just a typo on the classnames

native tide
floral herald
#

i got this error from instance = self.Meta.model(**validated_data) this line of code how can i solve it ?

manic crane
#

anyone know how to solve this => ImportError: cannot import name 'Clique' from partially initialized module 'Occupy.models' (most likely due to a circular import)

serene prawn
#

I believe it's app_name.ModelName

serene prawn
#

Yep

#

models.ForeignKey('application.Model')

#

For example ^

manic crane
#

ohh calm ill try that

serene prawn
#

And remove your import for this model too

manic crane
#

thanks

dreamy portal
#

hey

#

can you told me which programming language i can used to make a website

serene prawn
#

You can use python for backend, if you need something complex then only choice for your frontend is JavaScript

dreamy portal
#

ok

prisma ravine
#

hey guys is there any discord server based on only web-development?

tiny snow
#

Yeah

#

Its name is WebDev now

obtuse mantle
#

I have udemy full webdevlopment and DSA also course with life time access
At just Rs 250 only
Hurry up
If any one interested can dm me

rigid rover
#

@open forum(look at the message above)

lavish prismBOT
#

6. Do not post unapproved advertising.

ornate flame
grim helm
#

is there a way to edit html before render_templating it, using flask?

dusty haven
#

Jinja may be a way

grim helm
#

yee, googling led me to directly calling jinja, but i dont wanna open the template file on each request
i wanna use the caching part (i hope render_template caches things)

ornate flame
#

Hey there please help #help-cheese sorry for messaging in between a conversation.

inland oak
#

We host flask application as Gunicorn + Nginx.

#

Nginx as reverse proxy + it hosts your static files

#

Nginx at the same time can handle caching rules, for certain urls which you specify (or all of them)

#

+Cloudflare with its CDN is yet another more high leveled caching mechanism

grim helm
#

ohh, so i use html as static content 🤔

inland oak
#

+If you wish to have caching at the level of framework....

#

...you can cache inside of Flask with using Redis key-value in memory database

grim helm
#

rittt

inland oak
#

as you can see. There are many means to cache stuff 😉

grim helm
#

that helps tyy

#

yeah, was worried about too much I/O, never realized nginx

inland oak
#

...compilated result of Jinja framework

#

with insertion of different CSS/JS files into it

#

CSS/JS files will be cached by Nginx / Cloudflare rules, client side caching can be applied to it

#

the rendering of the page itself?

#

you can cache it with Nginx or with Redis (or with Cloudflare too)

#

your ability to cache it, depends on what type of content it has

grim helm
#

totally goin nginx file system thingy

inland oak
#

If the page is purely static in content? you can cache it agressively at CDN / Client side way
if the content is changing only with query params? You can cache at nginx level (probably with CDN too)
If the content is fully dynamic? You can cache with Nginx requests to JSON endpoints, or you can cache dynamic data in Redis

#

many means to cache stuff

inland oak
#

or Nginx can cache for you by adding Client side caching rules headers to the files. Which will make stuff cached in the client browser

grim helm
#

yeah, im already using nginx for serving stuff, will just add another rule to expose another port interally that can serve my html files

inland oak
#

good.

#

Read the free Nginx cookbook from O'reilly

#

to know what you can do with Nginx

#

get a hang of Cloudflare service, for the most powerful CDN caching, it is easy

#

and optionally learn using Python Redis library, in order to use key-value db

inland oak
# grim helm yeah, im already using nginx for serving stuff, will just add another rule to ex...
grim helm
#

tysm

slim maple
#
    list-style: none;
}

.menu-up a {
    text-decoration: none;
    color: white;
}

.menu-up ul {
    display: flex;
    justify-content: space-evenly;
    width: 60%;
    background-color: black;
    margin: 0 auto;
}

.menu-up {
    text-align: center;
    position: fixed;
    top: 0;
    left: 0;
    background-color: black;
    width: 100%;
    border-bottom: 0.5px solid white;
    z-index: 20;
}``` i don't want it to be display: flex but something else but when i for example chage it to display: inline-block it goes like this