#web-development

2 messages · Page 193 of 1

graceful flax
#

I want the other APIs to return 400 or 404 something I choose to if it is deleted=True

#

I don't want to manually write code in every API for this, was wanting to know a centralized way

candid meteor
#

i hosted it!

#

been so long been here

graceful flax
#

I meant in every API view function

#

I'm doing

post = getpost..
if post.deleted == False
         then updatedPost()```
#

I don't want to write this in every view function is what I meant.

glacial yoke
#

that's posgres, I was asking about MYSQL

inland oak
glacial yoke
jade moon
#

Hi Pady. Check out https://www.dj4e.com/. You might find it helpful. There's also an 18 hour long video of it on FreeCodeCamp's Youtube channel https://youtu.be/o0XbHvKxw7Y.
Also if books are your thing, Django for Beginners by William S. Vincent is a good bet.

This Django tutorial aims to teach everyone the Python Django web development framework.

🔗 Course Website: https://www.dj4e.com/
💻 Sample Code: https://github.com/csev/dj4e-samples/

✏️ This course was created by Dr. Charles Severance (a.k.a. Dr. Chuck). He is a Professor at the University of Michigan School of Information, where he teaches var...

▶ Play video
tepid lark
#

can you configure django to not use a default database?

#

i'd like it to fail rather than fall back if you don't specify what database your model belongs

cinder sluice
#

@tepid lark yes, you can leave out the database. most of what I've been developing this year has been APIs fronting services and I don't need the database. All you would do in settings.py is

DATABASES = {}

cinder sluice
tepid lark
#

@cinder sluice Thank you!

next vessel
#

i have no clue why it isn't creating a .db file
it doesn't even give me any error

#

any solutions?

#
app = Flask(__name__)

app.config['SECRET_KEY'] = 'kdljfkldjfdlkfjklf'
app.config['SQLAlCHEMY_DATABASE_URI'] = 'sqlite:///site.db'

db = SQLAlchemy(app)```
outer apex
next vessel
#

how tf i didn't see that

#

🤦

#

thanks

vernal lotus
#

Hello anyone help me to figure this out.
django.urls.exceptions.NoReverseMatch: Reverse for 'delete-user' with arguments '('',)' not found. 1 pattern(s) tried: ['manage\-users/delete\-user/(?P<pk>[0-9]+)/$']

#

views.py

def DeleteUser(request, pk):
    data = dict()
    userprofilelist = get_object_or_404(User,pk=pk)
    
    if request.method == 'POST':
        userprofilelist.delete()
        data['form_is_valid'] = True
        userprofilelist = User_Profile.objects.all()
        data ['tb_list'] = render_to_string('table_list/tbl_user-profile.html', {
            'userprofilelist' : userprofilelist
            })
    else:
        data['form_is_valid'] = False

    context = {'userprofilelist': userprofilelist}
    data['html_form'] = render_to_string('partial_modal/delete-user.html',context, request=request)
    return JsonResponse(data)
#
 <a class="dropdown-item show-form-delete text-danger" data-url="{%  url 'delete-user' userprofilelist.id %}">Remove</a>
#
<form method="post" data-url="{% url 'delete-user' userprofilelist.id %}" class="delete-form mt-4">{% csrf_token %}
<p class="lead">Are you sure you want to delete this user <strong>{{ userprofilelist.username }}</strong></p>
</form>
#
 path('manage-users/delete-user/<int:pk>/', views.DeleteUser, name="delete-user"),
warm igloo
# vernal lotus Hello anyone help me to figure this out. django.urls.exceptions.NoReverseMatch: ...

Did you inspect the Remove button in browser to see if the url that's generated is actually good? Because it appears that its barfing on the url being something like manage-users/delete-user/('',) instead of your expectation that userprofilelist.id is something like an int. So then it can't find a url pattern accepting that weird string. So I'd start there to confirm that the template is really making the URL what you expect

stable coral
#

I implemented blueprints in my website using a tutorial

#

And now I'm not sure how to access my database from the terminal

#

When I try to run the website I get this

#

So I tried going into the terminal to just drop_all() then create_all()

near bison
#

I am trying to run android on the cloud ? Have anyone here tried that ? I tried using anbox. It's kinda working but i am having stability issues. CPU usage and RAM usages spikes randomly etc

dusk portal
#

@login_required
@cache_page(60*2)
def notes_upload(request):
    if request.method=='POST':
        title=request.POST.get('title')
        subject=request.POST.get('subject')
        desc=request.POST.get('desc')
        thumbnail=request.FILES['thumbnail']
        file=request.FILES['file']
        author=request.user
        entry=Notes(title=title,subject=subject,desc=desc,thumbnail=thumbnail,file=file,author=author,published_on=datetime.now())
        entry.save()
        messages.info(request,'Notes updated successfully!')
        return HttpResponseRedirect('/')``` this is my code for notes upload it's working fine but when i'm not uploading thumbnail it's flashing error
#

not from admin panel but only from the html file

#
MultiValueDictKeyError at /notes_upload/
#
class Notes(models.Model):
    title=models.CharField(max_length=60,blank=False,null=False)
    subject=models.CharField(max_length=50,null=False,blank=False)
    desc=models.TextField(blank=True,null=True)
    thumbnail=models.ImageField(blank=True,null=True,default='default_notes.jpeg',upload_to='thumbnail_notes',validators=[validate_image_file_extension])
    file=models.FileField(blank=False,null=False,upload_to='Notes',validators=[FileExtensionValidator(allowed_extensions=['pdf','doc','docx'])])
    author=models.ForeignKey(User,on_delete=models.CASCADE)
    published_on=models.DateTimeField(auto_now_add=True)```
dusk portal
#
        <form method="POST" enctype="multipart/form-data" >
mild wing
#

Hey I’ve been learning python for a couple months, doing dev work is something I might wanna do in the future.
Now I never done any web stuff but I would like to build an online store for my business. Would going and learning django be a good choice for that? Are the other routes I should consider, python or non python related?

vestal hound
sour wedge
#

heyya buddies

#

i have a doubt/problem in django
any one free to help me ??

raw compass
# mild wing Hey I’ve been learning python for a couple months, doing dev work is something I...

Wagtail is another layer on top of django that may prove to be useful. Start with a relevant tutorial like https://snipcart.com/blog/django-ecommerce-tutorial-wagtail-cms and see how you go.

Snipcart

Learn how to take advantage of the mix of Django & e-commerce. Follow this tutorial with Wagtail CMS to start quickly. Live demo & GitHub repo included.

lament birch
#

Is there a way to obtain real time audio data from a user in a django web application?

coral storm
#

do I need to use sqlalchemy with flask or can I use raw sql?

bright mason
#

you could

inland oak
#

I would say, SQLaclhemy provides simpler output in terms of database management

#

all your database... tables are stored as a code

#

and changes from one database version to another one, is just a database migration code stored inside your project

#

it simplifies stuff a lot for simple projects development

verbal forge
#

Hi everyone I'm working on the UI for my webapp and I cant figure out how to get it so that lobbies box fills out the remaining space in the container and scroll for the overflow

native tide
#

hey, my dream and what i want to do in the future is to be a fullstack freelancer or work at a big tech company im only 14 and i watched this entire video https://www.youtube.com/watch?v=rfscVS0vtbw and i also know html and css quite well and i want to be a web developer i don't know where to go now and help?

This course will give you a full introduction into all of the core concepts in python. Follow along with the videos and you'll be a python programmer in no time!
Want more from Mike? He's starting a coding RPG/Bootcamp - https://simulator.dev/

⭐️ Contents ⭐
⌨️ (0:00) Introduction
⌨️ (1:45) Installing Python & PyCharm
⌨️ (6:40) Setup & Hello Wor...

▶ Play video
mortal pike
#

I am getting an error on my django site hosted on heroku when I try to connect via sockets to a ngrok forwarded port from my raspi. I am getting it timing out but I am not sure why.
Logs:
Code for django view:

PORT = 8080
SERVER = 'redacted'
ADDR = (SERVER, PORT)
FORMAT = 'utf-8'
DISCONNECT_MESSAGE = "!DISCONNECT!"
class RobotDetail(UpdateView):
    model = Robot
    form_class = RobotUpdateForm
    template_name = 'dashboard/robotdetail.html'

    def form_valid(self, form):
        self.object = form.save()
        client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        client.connect(ADDR)

        def send(msg):
            message = msg.encode(FORMAT)
            msg_length = len(message)
            send_length = str(msg_length).encode(FORMAT)
            send_length += b' ' * (HEADER - len(send_length))
            client.send(send_length)
            client.send(message)

        send(form.cleaned_data['path_options'])
        send(DISCONNECT_MESSAGE)
        return render(self.request, "theblog/bloghome.html")
wraith prawn
#

Hello! Looking for some advice please. I am getting data from an api that has rate limits, these limits are 30 hits every 5 minutes. Is there a smart way to ensure my users cannot go over this limit, like limiting their ability to hit the button that sends teh request? struggling to solution this issue

last lily
#

Hey guys! <3 I want to make a very simple web API, I am not sure which platform to use, Flask? Django? Gunicorn? Uvicorn? D:

#

It's a very very simple API, just take some data from my DB, process it just a tad, and serve it

sonic island
#

I have already added chromedriver to path but then also it is showing error
raise WebDriverException(
selenium.common.exceptions.WebDriverException: Message: 'chromedriver' executable needs to be in PATH.
what to do?

olive patrol
#

I’m trying to add a form, but for some reason, above the form, it’s showing this field is required. This stack overflow shows what I’m talking about: https://stackoverflow.com/questions/68374208/remove-this-field-is-required-text-above-django-form. Is there a way to remove the bullet point?

stark tartan
#

hey i am going to build the video chat website using django WEB-RTC with django channels please give some docs or any suggestion is it possible to do this ??

stark tartan
sonic island
tepid trellis
#

Help needed, in django i have to upload a text file, that is done, then i have to copy the content of that text file to a new file (python normal code ready, dont know how to access that text file from django) then make it available for download

gray galleon
#

Hey there, I'm hoping to build a dynamic website with user profiles and such.
I've been wondering what is the best python web framework to use in this case?
Flask? Django? Or FastAPI.
I've also been wondering if I should directly send all the content to the browser or use "static" pages with REST/WS APIs to load the dynamic content?

native tide
#

heyy, is there anyone that can help me with Quart?

native tide
#

How can i get button onclick event to work?

#

i have this simple thing on web

#

and this in my code, how can i get the input from the input by the button click?

warm igloo
#

you need a form around it and the form determines where it goes

#

or you can use js and a listener

native tide
#

whats more simple?

#

and how to that, cuz im new to web developing and i cant find any info about it :/

warm igloo
#

I suggest pausing your python work and learning html forms first

wispy jacinth
#

I am trying to deploy my ASGI chat app on Heroku.. but I keep getting this error: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

warm igloo
#

you've tested locally and it runs fine?

#

it's likely a settings issue from what I can tell reading online

#

a missing ENV, a misconfigured asgi.py

#

bad procfile

fervent path
#

I am working on a web app using python and having trouble setting up virtual environment.
I have the latest Python3.9 installed. I am using VSCode. Windows
I have used the following command that is listed in the python documentation and I am trying to activate virtual environment py -m venv env
.\env\Scripts\activate

The result is a message saying 'Command not found'
-are there any commands I should do prior to this?
-I have tried activating inside and outside env folder.

fervent path
#

is there a way to undo 'django install' on vscode termial?

versed python
#

So I am working on a banking platform, and when a new user registers, we need to send the submitted data to that user's country's trusted verification API (for eg: SendWyre for US). Now as you can imagine each API has different requirements.

Is there any way I can use a common function to somehow contact all the API's or is it necessary to write a separate function for each?

versed python
# fervent path

looks like you are trying to run windows commands on a bash terminal?

olive patrol
fervent path
#

I was able to resolve both issues. Thank you for the replies!!

dusk portal
#
@login_required
def profile_update(request):
    if request.method=='POST':
        user=request.user
        image=request.FILES['image']
        about=request.POST.get('about')
        data=Profile(user=user,image=image,about=about)
        data.save()
        messages.success(request,'Profile created')
        return HttpResponseRedirect(reverse('users:profile'))
    return render(request,'users/profile_update.html')```
#

so i have a form for profile which takes 2 things by user
image and about
if about is left empty it works , but if i leave image empty if breaks and give error

#
class Profile(models.Model):
    user=models.OneToOneField(User,on_delete=models.CASCADE)
    about=models.CharField(max_length=200)
    image=models.ImageField(default='default.jpeg',upload_to='Profile_Pics',blank=True,null=True,validators=[validate_image_file_extension])
    follower=models.IntegerField(default=0)
    following=models.IntegerField(default=0)```
#
MultiValueDictKeyError at /account/profile-update
'image'```
#

according to me error is coming cuz in my form im taking

#
        <form method="POST" enctype="multipart/form-data" >
#

and when i dont take img this enctype remains empty

#

so it shows error

#

not sure

limber laurel
#

Ao turns out, my web application had a sys.exit() error because of gunicorn, I am not sure what caused this, how should I go about diagnosing the problem?

#

It seems like the request took 30 seconds for some reasons? But how would I know what caused such a timeout? I had a suspicion of the omage upload in said view as it sends it to Cloudinary, but that took 1-1.5s to complete not 30

tepid wren
# wraith prawn Hello! Looking for some advice please. I am getting data from an api that has ra...

ratelimit decorator package might help https://github.com/tomasbasham/ratelimit

from ratelimit import limits

import requests

FIFTEEN_MINUTES = 900

@limits(calls=15, period=FIFTEEN_MINUTES)
def call_api(url):
    response = requests.get(url)

    if response.status_code != 200:
        raise Exception('API response: {}'.format(response.status_code))
    return response

GitHub

API Rate Limit Decorator. Contribute to tomasbasham/ratelimit development by creating an account on GitHub.

ancient hollow
#

Looking to construct a looped select menu using flask and I am unsure about the jinja syntax

#
{% extends "layout.html" %}

{% block title %}
    Sell Stock
{% endblock %}



{% block main %}
<h2> Enter the stock name and the number of shares that you want to sell </h2>
    <form action="/sell" method="post" id="sell_form">

        <div class="form-group">
            <label for="symbol">Choose a stock:</label>
            <select name="symbol" id="sell_form">

                {% for stock in owned_stocks %}

                <option value="{{stock['name']}}" >{{stock['name']}} </option>

                {% endfor %}    

              </select>
        </div>

        <div class="form-group">
            <input autocomplete="off" autofocus class="form-control" name="shares" placeholder="Shares" type="number" >
        </div>

        <button class="btn btn-primary" type="submit">Sell Stock</button>
    </form>
{% endblock %}s
hasty glacier
#

Hi all - has anyone here deployed Django / React with Azure App services that I can pick their brain? I'm having a problem with my main.js not being found after I've collected statics and declared the static location.

terse vapor
#
current_time = datetime.now() 
time = timedelta(weeks=4) 
month = current_time - time
filter_by_month = db.session.query(Patient.subid).filter(Patient.create > month).all() 

This is my script for filtering patient per month, but is there a method that allows me to get all the list for each month?

fickle garnet
#

cant just increment?

inland oak
terse vapor
#

i have a list of patient in my database, and i have already filter them by current month and day, but im trying to filter the amount of patient for each month(Jan - Dec) (i hope this can make a bit clear)

inland oak
#

how your database customer table looks like?

terse vapor
#

the first part was right, and for second part, sorry for my bad explanation, i was meant to say from jan to dec, amount of patient for each month

inland oak
terse vapor
#

yup

inland oak
#

sounds like SQL grouping

#

I am a bit rusty on SQL, but I know for sure that it is possible

#

in raw SQL it involves syntax words like Group By, Having

terse vapor
#

that sounds like a great idea

fickle garnet
#

For an sql query its just as simple as a GROUP BY var_name clause isnt it ?

inland oak
fickle garnet
#

HAVING would specify a particular month. SELECT COUNT(*) GROUP BY(month)

#

i should use code so it doesnt look like im yelling at you

inland oak
#

nah, that will work too. having big SQL syntax is... normal.

fickle garnet
#

syntax handed down from old wise peoples

#

does nginx -> wsgi -> flask make sense for a small project ?

inland oak
#

because we use gunicorn as default for flask wsgi

#

and it can't serve static files

#

nginx is the best default option to serve static files

#

other things... like white noise just literally suck at serving static files (taking up to 4 seconds to serve one file)

#

old alternative solution could be using Apache, but I think Nginx is better, easier and faster at the moment

wooden ruin
#

wow i didn't know whitenoise sucked that bad with static files

inland oak
#

I learned it the hard way

#

😆

fickle garnet
#

haha hopefully not production env

#

4seconds.. ahhh!

inland oak
#

thankfully in dev env

#

plus with nginx you can easily setup additional things to speedup your website by about 100 times with minimum effort

#

you just enable http2
client side caching (static files css/js will be cached at the client side and will not be requested again until time expries)
and server side caching for urls you can (nginx will serve cached version of the particular url, before the request reaches your python framework

#

the book is free how to do that

fickle garnet
#

what do you think about uwsgi ?
does nginx still detect and cache static content generated by flask ?

inland oak
#

you mean by those jinja2 templates?

fickle garnet
#

yes

inland oak
#

yes

#

it can cache even JSON requests of your REST API end points (making one request to database and caching it 🙂 )

wooden ruin
#

wow

fickle garnet
#

i knew this to be true from experience, had to tell it not to cache to troubleshoot some stuff... just checking im still understanding 🙂 thanks mate!

inland oak
#

it can cache separetely requests like url?one_var=123&other_var=32434

#

it will serve/cache the right answers for different query_params

#

not sure how it works with POST requests since they have JSON data paylod 🤔

fickle garnet
#

it was working perfectly. it was my implementation that was awkward

#

making me curious but i must resist the rabbit hole

#

there are passthrough options... thats all i know haha

fickle garnet
#

always changing so never ending. which is good..

upbeat quarry
#

does anyone know which python tools I can use to start learning web development

native tide
#

String literal is unterminated``` please help String literal is unterminated``` please help

upbeat quarry
#

sorry, I meant app development. Does that come under web development?

inland oak
#

I am still torn apart, if I should apply Vue or Svelte at the startup 🤔

#

Vue looks like safer choice, but Svelte is so attractive and easier

inland oak
#

eh. the size of usage Vue and its community leaves me no choice but to choose Vue

#

Svelte is so super attractive, clean, small coding, but I just can't choose it for startup/commercial because of small community and small percentage of usage in commericial (50 times difference at least)

olive patrol
#

I have these two elements: text hello world. Text being a paragraph element, and hello world being a button. How can I make it so that if the button is clicked, it deletes the paragraph element and the button element itself?

tepid wren
inland oak
# tepid wren svelte is easier than vue ? vue was the only js framework I could work with

yeah, svelte is even easier than vue.
https://www.youtube.com/watch?v=cuHDQhDhvPE check comparison of the same program in Vue and Svelte

I built a simple app with 10 different JavaScript frameworks... Learn the pros and cons of each JS framework before building your next app https://github.com/fireship-io/10-javascript-frameworks

#javascript #webdev #top10

🔗 Resources

Full Courses https://fireship.io/courses/
Performance Benchmarks https://github.com/krausest/js-framework-benc...

▶ Play video
#

less code, plus I heard inbuilt nice testing framework.

tropic raptor
#

Hello,
I am struggling with getting Set-Cookie header's session value created by Flask-Login.

from flask import Flask
from flask_login import LoginManager, login_user, UserMixin

app = Flask(__name__)
app.config["SECRET_KEY"] = "abcdef"
login_manager = LoginManager(app)


class User(UserMixin):
    def __init__(self, identificator):
        self.identificator = identificator

    def get_id(self):
        return self.identificator

    @staticmethod
    def load_user(user_id):
        user = User(user_id)
        return user


@login_manager.user_loader
def load_user(user_id):
    return User.load_user(user_id)


@app.after_request
def ar(response):
    print(response.headers["Set-Cookie"])
    return response


@app.route("/")
def main():
    user = User(1234)
    if user is not None:
        login_user(user)
        return "Should be logged in"
    return "At first log in"

Minimal piece of code ^

Unfortunately, there is not Set-Cookie header in my response.

However, each time I call / endpoint, I see HTTP response in my curl - containing Set-Cookie and session=.eJ... headers!

#

How to obtain that session cookie value in my Python code?

inland oak
#

the size of its build... 10 times smaller than any other framework

tropic raptor
#

Yea, I do recommend Svelte!

tepid wren
#

so many javascript frameworks makes me feel lost

inland oak
#

anything that is not React/Angular/Vue/Svelte, throw away because of too small communities / low interest

#

Throw away React, because it is dirty mix of html / javascript / jsx in one code line

#

Throw away Angular, because long learning curve, suspiciously small developer satisfaction.

#

This makes remaning only Vue and Svelte to choose

#

Vue looks good and solid choice. High job market percentage, community, looks good from afar. 😉
Svelte, looks so super clean, lightweight, easy to learn, battery included (even for state management!) quite attractive and promising to be great in a future. But low job market occupation 😦

tepid wren
olive patrol
indigo kettle
#

I mean you could do it by navigating to an entirely new page that doesn't have those elements on it, but you should really just do it with js

#

what was the issue with js?

#

@olive patrol

olive patrol
# indigo kettle what was the issue with js?

Whenever all the items would get deleted, they would just come back to display. I’m assuming it’s because the elements are stored in a database, and I’m getting those elements fork the database and displaying it onto the screen

indigo kettle
#

do you have some interval on the frontend which is polling the backend and displaying that data every x seconds or something?

olive patrol
indigo kettle
#

That's just what happens on page load, right? So once you click the button and the elements are removed, they shouldn't come back

olive patrol
indigo kettle
#

ah

#

Well then you will have to send a request to your backend so it will handle it

#

So maybe you do want it to be handled by django and not js after all

#

you should maybe create a form which sends a delete request to your backend for the exact model ID you want to delete

#

then your frontend will refresh that page, probably and the item should be gone

indigo kettle
#

if you have created a database row then the django model will have an id attribute

#

that is the database id of the row

olive patrol
indigo kettle
#

if you have an instance of the model, then yes

#

like if you have a Todo app and you want to get a todo id

#
todo = Todo.objects.first()
todo.id # is the id

olive patrol
indigo kettle
#

?

olive patrol
# indigo kettle ?

My structure looks something like this: class Category(models.Model): … class SubCategory(models.Model): subcategory = models.ForeignKey(Category, on_delete = models.CASCADE)

indigo kettle
#

and you are trying to delete the subcategory?

#

or category

olive patrol
indigo kettle
#

even with foreignkeys, the model still has an id

olive patrol
#

Now what if there are more than two subcategories? I won’t be able to get the id with first() or second(). What would I use then?

indigo kettle
#

when you render your html I assume you're iterating a list of subcategories right?

indigo kettle
#

like for subcat in category.subcategory_set

#

then within there you can send the id to the frontend

#

and your frontend needs to send the id of the subcategory you want to delete to your backend

#

your backend shouldn't have to decide what to delete

olive patrol
native tide
#

Hey folks, how can I use track argument inside iframe?

        <script>
            function PlayTrack(track) {
                document.getElementById("iframeMusicPlayer").innerHTML = "<iframe src=\"track\" height=\"150\" width=\"400\" ></iframe>";
            }
        </script>
glacial yoke
#

when using DRF if I wanted to make a post function, to post info from the frontend to the backend, would I be able to return a response, which then I would be able to grab from the frontend? or would I have to create a get function as well, inside that APIView so that I can return a response to the frontend

#

ok, nvm, just tested it out

#

you can just return it through the post function

#

if you are using a js framework, then you can use axios like this to not just post your data to the backend, but also receive whatever you need back, from the same function:

axios
      .post(
        "function url",
        {
          whatever_you_are_posting: "whatever you are posting",
        },
        config //the headers with csrf token, can't make a post request without them
      )
      .then((response) => {
        console.log(response.data) //Do whatever you need with the data that you receive
      })
      .catch((err) => {
        console.log(err)
      });
native tide
dim rover
native tide
#

Yes.

#

Its just to include a audio player from the same domain

dim rover
#

then you can use iframe.contentWindow

#

to access the window/document inside it

#

like if you have a function in the iframe, you could call it from the parent page and pass your argument, right?

native tide
#

Please have a look at my stackoverflow question, I actuslly just need to know how to format the string, any idea?

dim rover
#
document.getElementById("iframeMusicPlayer").contentWindow.PlayTrack(track);
``` something like that?
#

oh, ok

#

you could use onclick=document.getEl....

#

same way

shadow vine
#

Any django fans in here?

brisk ledge
#

does anyone here knows anything about selenium, how could i find elements by saying that their id contains a certain phrase such as the letter q

//*[@id="assignmentsection_301649"]/td[3].

This is the type of xpath I am working with, everything i am trying to catch shared the id of assignmentsection_number. how do i capture all of those in one statement.

basicly I am looking or a statement like find_element_by_xpath(//*[@id contains "assignmentsection_301649"]/td[3]

Thank you

lethal drum
#

hihiya

mystic vortex
#

someone help

#

i need some help

mystic vortex
#

!guilds

lavish prismBOT
#

Communities

The communities page on our website contains a number of communities we have partnered with as well as a curated list of other communities relating to programming and technology.

slim beacon
#

Hello! I am attempting to use uvicorn[standard] for handling websockets requests. I am using Nginx as my web server and doing a reverse proxy to uvicorn for all websocket requests. I can get uvicorn running, but once the websocket request is made, I get an error from unvicorn saying WARNING: Unsupported upgrade request.

Here is the command line I used for running uvicorn uvicorn --log-level debug --workers 3 --uds /home/ubuntu/personal_site/app.sock mysite.asgi:application

I also want to mention that just in case I accidently downloaded the regular uvicorn, I uninstalled it, and then reinstalled it using pip install --no-cache-dir uvicorn[standard] , but I am still getting this error.

I can't seem to figure out why I keep getting an unsupported upgrade request. Could someone point me in the right direction

#

Also, just in case, here is my NGINX config file

`
server {
listen 443 http2 ssl;
listen [::]:443 http2 ssl;

    server_name _;

    ssl_certificate /etc/letsencrypt/live/ADDRESS/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/ADDRESS/privkey.pem;
    add_header Strict-Transport-Security "max-age=31536000";

    location / {
            root /home/ubuntu/personal_site/static/vue/personal_site_vue_prod/;
            try_files $uri $uri/ /index.html;
    }

    location /ws/ {
            proxy_pass http://unix:/home/ubuntu/personal_site/app.sock;
            proxy_http_version 1.1;
            proxy_set_header Upgrade &http_upgrade;
            proxy_set_header Connection "Upgrade";
            proxy_set_header Host $host;
            proxy_set_header X-Forwarded-For $remote_addr;
            proxy_set_header X-Real-IP $remote_addr;
    }

    location /static/ {
            root /home/ubuntu/personal_site/static/vue/personal_site_vue_prod/;
    }

    location /test/ {
            try_files $uri $uri/ /test.html;

    }

}
`

mystic vortex
lapis stratus
#

Hello, I tried to do python manage.py migrate but I got a ValueError from it. I tried to delete the migrations folder but when I try to do makemigrations and migrate again it still throw me the same error.

stable hawk
#

Hello How can we send update signal in django when model gets updated

stable sentinel
#

Hi, I've been bashing my head on something the past days tat I can not seem to find the answer to.

I'm building a password manager in Django and I'd like my password field to be hidden like a pw field usually is.

Now I have tried using forms.PasswordInput however, this is not persistent and it removes the content once refresh the page.

Is there a way to fix this using only django?

native tide
#

AttributeError: type object 'Oauth' has no attribute 'discord_login_url'

I am getting this error i am trying to make a discord bot dashboard these are the codes

from flask import Flask, render_template
from oauth import Oauth


app = Flask(__name__)


@app.route("/")
def home():
    
    return render_template("index.html",discord_url= Oauth.discord_login_url)


@app.route("/login")
def login():
    return "Success"

if __name__ == "__main__":
   app.run(debug=True)
pallid gale
#

hi, can I disable admin pagination in a django rest framework api?

vestal hound
#

I believe

#

you can include it in your template

#

but you’ll still need to code it

dusk portal
#

why from last month everyone's so inactive

#

;-;

graceful flax
#

Hi

#

What's the difference between

#
group.reportedBy.add(request.user)
group.save()```
**AND**

group.reportedBy.add(request.user)

#

It gets saved to the DB even without me doing .save()

vale wyvern
#

click it please

#

and support me...

#

😉

buoyant geode
#

Hi Im trying to write code for nav bar using flex box Im using two containers and I want use only one container which has a row with items and colum with items

#

these are html and css files

#

please some one help me with this

vernal lotus
#

hello guys how to delete with this userprofile along with auth user.? I'm not sure how to use post_delete signals. How do I code it?

class User_Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)

    ROLE_CHOICES = [
        ("Computer Operator","Computer Operator"),
        ("Level 2 Support","Level 2 Support"),
        ("Level 3 Support","Level 3 Support"),
        ("Application Support","Application Support"),
        ("System Administrator","System Administrator"),
        ("Database Administrator","Database Administrator"),
    ]

    role = models.CharField(max_length=50, choices=ROLE_CHOICES)
    access_group = models.CharField(max_length=50)
    
    def __str__(self):
        return self.user.username
native tide
#

hey can someone help me im very confused on how to use github, i need to basically update files

#

they said that i need to make a new branch and i did

#

now how do i upload all the files from my folder that i made into the branch

errant junco
#

Is there a rich text editor that works with both react for frontend and django backend? I also want extra stuff like [spoiler][/spoiler] and such tags to work.

cerulean badge
#

i am getting the below error while trying to signup from form
populate_profile() missing 1 required positional argument: 'sociallogin'
while using this
https://stackoverflow.com/questions/14523224/how-to-populate-user-profile-with-django-allauth-provider-information#answer-48182605

errant junco
whole ether
#

Hi everyone . I came across a very nonsensical error to start my Django project. Does anyone know where the problem comes from?

errant junco
#

paste the last line of error

#

last part

whole ether
#

Exception ignored in thread started by: <function check_errors.<locals>.wrapper at 0x0000028FFA731670>
Traceback (most recent call last):
File "D:\python3\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper
fn(args, **kwargs)
File "D:\python3\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run
autoreload.raise_last_exception()
File "D:\python3\lib\site-packages\django\utils\autoreload.py", line 251, in raise_last_exception
six.reraise(
exception)
File "D:\python3\lib\site-packages\django\utils\six.py", line 685, in reraise
raise value.with_traceback(tb)
File "D:\python3\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper
fn(*args, **kwargs)
File "D:\python3\lib\site-packages\django_init
.py", line 27, in setup
apps.populate(settings.INSTALLED_APPS)
File "D:\python3\lib\site-packages\django\apps\registry.py", line 85, in populate
app_config = AppConfig.create(entry)
File "D:\python3\lib\site-packages\django\apps\config.py", line 94, in create
module = import_module(entry)
File "D:\python3\lib\importlib_init_.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 850, in exec_module

errant junco
#

I don't think that's still the last part, have you tried scrolling down

Though I'm pretty sure you have missed adding some package to INSTALLED_APPS or not installed it...

whole ether
#

File "<frozen importlib._bootstrap>", line 228, in call_with_frames_removed
File "D:\python3\lib\site-packages\django\contrib\admin_init
.py", line 4, in <module>
from django.contrib.admin.filters import (
File "D:\python3\lib\site-packages\django\contrib\admin\filters.py", line 10, in <module>
from django.contrib.admin.options import IncorrectLookupParameters
File "D:\python3\lib\site-packages\django\contrib\admin\options.py", line 12, in <module>
from django.contrib.admin import helpers, widgets
SyntaxError: Generator expression must be parenthesized (widgets.py, line 151)

#

.

#

Problems with the package itself?

errant junco
#

I think there's a mismatch between versions of python and django

#

there were some changes made in syntax which is not supported in older versions of python or vice versa

whole ether
errant junco
#

if you are in the latest django, downgrade it, if it's not about that then your python is either too old or too new

karmic atlas
#

hello, Is it possible filter by '2021-10-4' <= end_date in sql because it doesn't equivalent in django end_date__lte=date(self.year, self.month, day)

muted scaffold
#

Any django users here?
I got a quick query, I am trying to develop a django template where, I have a base template and then that's inherited by a template and then another template tries to inherit the second template. Is it possible in django??

#

It looks something like this:
base.html

html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{% block title %}title{% endblock title %}</title>
</head>


<body>
    <nav class="navbar navbar-expand-lg navbar-light bg-light w-100" style="height: 65px; position: fixed;">
        <div class="container-fluid">
            <a href="#" style="font-size: 25px; text-decoration: none; color: #002b63;">Title</a>
            <div class="navbar-collapse">
                <ul class="navbar-nav ms-auto me-auto mb-2 mb-lg-0" style="width: 80%;">
                    <form class="d-flex w-100">
                        <input class="form-control ms-auto" type="search" placeholder="Search..." aria-label="Search">
                        <button class="btn btn-outline-success" type="submit">Search</button>
                    </form>
                </ul>
                <a href="" class="btn btn-success">Login</a>
            </div>
        </div>
    </nav>
    <div style="min-height: 100vh;">
        {% block body %}{% endblock body %}
    </div>
</body>
</html>

index.html

{% extends "main/base.html" %}
{% load static %}
{% block title %}Home{% endblock title %}
{% block body %}

{% block events %}{% endblock events %}

{% endblock body %}

second.html

{% extends "main/index.html" %}

{% block events %}
<div>
    <h1>Upcoming events</h1>
</div>  
{% endblock events %}
#

Please ping me

indigo kettle
#

sure

#

@muted scaffold

#

did you try it?

#

should work fine

muted scaffold
#

Yes I did but it seems that the second.html doesn't render

indigo kettle
#

well, when you do this

{% block body %}

{% block events %}{% endblock events %}

{% endblock body %}
#

I believe you are completely overwriting your previous body

#

actually that's fine

#

when you say it isn't rendering, what is it doing?

#

is there an error? is the page just blank

muted scaffold
#

The second.html file's content is not shown

indigo kettle
#

can you paste the view as well?

muted scaffold
#

views.py

from django.http.response import HttpResponse
from django.shortcuts import render

# Create your views here.
def home(request):
    return render(request, 'main/index.html', {})
    # return HttpResponse("<h1>This is a Home Page :D</h1>")
indigo kettle
#

you aren't rendering the second template

muted scaffold
#

@indigo kettle Thanks bro!!

#

It's working

indigo kettle
#

yeah if you want django to render something you have to tell it to render that thing haha

#

np

deep tinsel
#

ey guys

#

So

#

if I wanna start being a web developer

#

does any of you have any tips on how to start

native tide
#

is it hard to implement a search function on your website for searching ebay products ?

past silo
#

could anyone help with a flask issue in #help-pie

jovial cloud
stable sentinel
lethal trellis
#

Are we allowed to discuss Website automation in this discord?

pastel knot
#

if run 'npm run build' instead of 'npm run serve' in my Vue dir my bootstrap css files don't get built

tropic vault
#

Hi all, when would we return Response in django? Why use that instead of HttpResponse?

honest tartan
#

Hello friends, i'm getting a problem with my API.

So when i make the POST i,ve pass all the validated data in the request body, but when i'm will send the post, one of the fields are not caching the request body value, and i get an not-null error,cause the current field needs data. So i tried to make the request inside the DB and works, the problem its or in the serializer or in the views, but i can't find:

here the error:

#

the field pokemon its an related field to a pokemon table, but its work,
here a insertion maded insid DB:

#

someone can hel-me?

#

help-me

wary yarrow
#

Does anybody here has experience with web scraping?

#

I got a little newbie problem

terse vapor
safe seal
#

@soft heart I'm new to this server .

honest tartan
#

welcome

dusk portal
#

oo

split snow
#

Hello

ivory thunder
#

Hi, how can I see/highlight which elements a given css selector picks? I want all links that are in a list: <ul><li><a href=...> (and I want to follow them with scrapy

native tide
#

is it possible to use flask instead of js for like

<Body>
<button>hi</buttob>

{% if buttonvale == True:%}
   <style>
   .div {
    display: True
}
</style>
{%endif%}
</Body>
ivory thunder
native tide
#

hm

#

how does that work

ivory thunder
#

you call a function with the template name and a python dict (ca same as js object) with the key/values you need

lethal trellis
#

Anyone know why I get the weird errors in the bottom when using selenium?

#

"browser status ended" "getting default adapter failed"

graceful flax
#

Hi I'm using Django, if I want to query objects with filter "not equal" is ~Q faster or a .exclude

gray star
#

anyone knows any crypto exchanges built on django ?

cerulean badge
#

(context django) i am creating a chat app which has models Chat and Message.
i am thinking of creating groups for every chat object and add the user to the group when they connect.
my question is when a user adds a new contact (create a chat object with the other user in members m2m field) how do i add the other user to the group when he is already connected?

surreal portal
#

With DRF and Django simple JWT, can you get the user's info easily with a route where you can provide the JWT and it returns stuff like your username or mail?

#

I need help on this segment and I'm kinda lost

graceful flax
surreal portal
swift glen
#

good day again guys

#

i have a question

graceful flax
dry obsidian
#

Is it possible to have 2 apis, hosted on 2 different servers but that share the same domain name but on different endpoints?

swift glen
#

If anyone is familiar with cloudfare free ssl. Can I just remove the privacy + protection add on which is I know is SSL and use cloudfare free ssl and implement it. so I can jsut get it for 1.99$?

swift glen
inland oak
#

What is Domain protection they are offering, I have no idea. I know only about default domain protection that goes everywhere by default, they would be surely giving it for free anyway.

swift glen
#

oh I see

spiral blaze
#

{{ form.hidden_tag() }} can someone explain this to me? this is in flask

frank shoal
#

is it for the csrf?

native tide
#

Hello, i want to know how can i check if a column named "test" exists inside a table named "node" using php?

frank shoal
#

SELECT test FROM node LIMIT 1; and see if it errors.

native tide
#

I'm on LInux, have python 3.9.7, is 3.10 in beta or safe to use for making a site with Django?

forest kindle
#

hey i am making a survey with html and css and i want to use flask with python so that i can store the data and hopefully print them on like an admin page. Does anybody know any websites or tutorial on how i can recieve the info that is being put in my survey?

#

or just know how?

unreal monolith
# forest kindle hey i am making a survey with html and css and i want to use flask with python s...

This is part 4 on forms but i would advice watching from part 1. https://www.youtube.com/watch?v=9MHYHgh4jYc

In this flask tutorial I show you how to use the HTTP request methods Post and Get. The POST method will allow us to retrieve data from forms on our web page. In later videos we'll get into more advanced topics relating to login sessions and using POST methods to retrieve secure information like passwords.

Text-Based Tutorial: https://techwitht...

▶ Play video
forest kindle
#

Thanks you

#

I think this is exactly what I need.

lyric belfry
#

Can I use a model inside a model?

#

What I mean by this is can I make say a class for the following


class Comment(models.Model):
  text = blah blah blah django stuff

class User(models.Model):

  comments = []

``` could I then use that layout from the comment class inside like an array?
#

would that allow me to pull attributes? say I did User.comments[0].text

dire urchin
#

something like

class Comment(models.Model):
  text = blah blah blah django stuff

class User(models.Model):

  comments = models.ForeignKey(Comment, on_delete=CASCADE)

this way you can link the User's comments field with the Comment model, but ignore this if I misunderstood the question

lyric belfry
#

I've done things like pygame before so what I mean is could i use a different class and then use those objects inside another class? Like for example in pygame I could make like an class Enemy: and then make like an array called enemys = [] and then just append the enemy object into that array

#

Could I do the same thing with the comments?

#

Do you get what I mean? lol

#

Like use an ArrayField() and then append the comments into that?

#

It's for my project we bascially have to wrap our pygame project into like a web interface and im just using django because i already know python

dire urchin
#

full disclaimer i'm also pretty new to this stuff so my explanations are probably bad, hopefully someone more storied can chime in and correct me

lyric belfry
#

What's the format of the foreign key?

lyric belfry
#

Like when I call the attribute comments?

#

Can I use a foreign key inside an array field?

#
from django.contrib.postgres.fields import ArrayField

class User(models.Model):
  comments = ArrayField(models.ForeignKey('Comment',on_delete=models.CASCADE))

#

Like something like this?

#

I'm just asking before testing so i dont end up like destroying my db

#

and have to start the django project again

#

lol

dire urchin
#

i think there's no need for that
if you want to access a comment with the id 4 you can filter it from the database like this

comment = User.objects.filter(comment_id=4)
charred epoch
#

Hey im trying to use a variable from a js file to an html:

var api_key = "..."
<script type="text/javascript" src="restricted.js">
const youtubeKey = api_key;
</script>

but this doesnt seem to work

lyric belfry
#

Why would you set youtubekey to api_key if api_key is already it self?

#

Can't you just use that on it's own

lyric belfry
#

For like organisation sake

charred epoch
#

i want to hide the api_key in another file far from the main code

#

so that only "api_key" is visible

dire urchin
vestal hound
#

which should be on the Comment model instead

honest tartan
#

guys i got this problem,my api in django is not caching the data in the request body to send to db,here the error:

#

what could be?
bassically i'm passing de data in the field but even that i got a NOT-NULL ERROR, but inside db server is everything runnig fine,its only on the client-side

desert cradle
#

[Django]
I made the model with "inspectdb", but do I have to do "inspectdb" whenever DB is updated?

orchid olive
#

is python-flask a good option to setup a home-webserver? or do i need something like apache web server?

warm igloo
#

well, what are you wanting to do? and host?

orchid olive
#

local service using python-flask

warm igloo
#

a single app for yourself? flask could run like that internally .. but if you want to host lots of stuff, that's a different thing all together

orchid olive
#

you have the idea, yes

warm igloo
#

sure, you coudl write a single app and run it on a machine and have it listen to a port

orchid olive
#

large service application

warm igloo
#

for instance, I have a homelab and I host LOTS of things

orchid olive
#

multiple users

warm igloo
#

multiple users like how many and you plan to do this on a server in your home then do port forwarding to it from your router?

orchid olive
#

over 1k at the same time 24/7

warm igloo
#

yeah, no, you wouldn't want to host that via the simple server flask can throw up, you'll want nginx/apache or something in front

better yet if you know about containers and other things because then you can do real cool things

#

but ultimately, you're better off hosting what you want out on a real host and not over your home connection

#

your isp will likely have a clause forbidding that much incoming traffic

#

plus it'll bottleneck a bit because your download speeds may be high, but your upload is probably hella slow

#

and again, just so much better to host outside stuff for outside people in the outside

orchid olive
#

no uploads, only data service

warm igloo
#

you can try it, but that's a lot of incoming connections that I bet your ISP will pay attention to

#

depends on your contract with them

elder ledge
#

Hi, guys. I am looking for and need help from you for a django project.
If you have skills and experience, and interests on it, feel free dm to me

orchid olive
#

ok, got it, thanks for the adivice

warm igloo
warm igloo
warm igloo
lethal junco
#

hello can someone help me with my problem?

#

whenever I click a category, that's the error

mild hazel
#

Hello, so I'm trying to learn Flask and long story short I got a problem with some code and no idea why it even occurs or how to solve it, I'm new to programming and quite inexperienced, my .py code is this:

app = Flask(__name__)

posts = [
    {
        'author': 'John Doe',
        'title': 'Blog Post 1',
        'content': 'First post content',
        'date_posted': 'April 20, 2021'
    },
    {
        'author': 'Jane Doe',
        'title': 'Blog Post 2',
        'content': 'Second post content',
        'date_posted': 'April 21, 2021'
    }
]

@app.route("/")
@app.route("/home")
def home():
    return render_template('home.html', posts=posts)

@app.route("/about")
def about():
    return render_template('about.html')



if __name__ == '__main__':
    app.run(debug=True)```

and my .html code is this:

```<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    {% for post in posts %}
        <h1>{{ post.title }}</h1>
        <p>By {{ post.author }} on {{ post.date_posted }}</p>
        <p>{{ post.content }}</p>
    {% endfor %}
</body>
</html>

All I keep getting is a damn "jinja2.exceptions.TemplateSyntaxError: tag name expected" error message.

foggy plover
#

Hey! Anyone up? I had a query regarding Flask

coarse shadow
#

!code-block

lavish prismBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

foggy plover
#

I am working on a React-Flask project and I am getting this error,
TypeError: The view function for 'logout' did not return a valid response. The function either returned None or ended without a return statement.
Where I am returning a response. The Code is

@is_logged_in
def logout():
    if request.method == 'GET':
        session.clear()

        return 'OK'
    return 'NOT'```
inland oak
#

you will be able to query those endpoints from react with fetch operations

foggy plover
#

Sure, I'll try this.

#

Here's another error. I am using sessions from the flask library to work with sessions but I am unable to get the session variables.

#

Here I am setting the session, if dbm.check_login(username=username, password=password): session['logged_in'] = True session['auth'] = auth.get_auth_key(username=username)

#

And I am unable to access the same here, ```
def is_logged_in(f):
@wraps(f)
def wrap(*args, **kwargs):
print(session)
if 'logged_in' in session:
return f(*args, **kwargs)
else:
return {'error': 'Session Expired'}

return wrap```
inland oak
#

flask provides with auth library actually named login manager

#

it would be less reinventing the wheel solution

lavish prismBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

deep tinsel
#

Hey guys, just to confirm it, you can create a website with PyCharm only, right?

deep tinsel
#

Oh that's cool

native tide
#

how do I import in brython from django's static?

lethal junco
native tide
#

I'm redirecting <slug>.py but that doesn't work for directory modules

deep tinsel
lethal junco
lethal junco
native tide
#

I'm trying it with django with brython. Not having to deal with javascript is so nice.

native tide
deep tinsel
#

I started using python for 6 days ago

lethal junco
#

it's easy to understand

deep tinsel
#

Got it

#

Well

#

Can i create a website with PyCharm only or?

lethal junco
#

if so, yes PyCharm can develop a website

deep tinsel
#

Legit

#

Because I do understand a bit python yk

#

But I am hella interested in web development, game development and cyber security

lethal junco
lethal junco
#

I came from PHP but when I learned Python, I switch immediately to Python and start learning Django

deep tinsel
#

Is there much different between dj and python?

lethal junco
deep tinsel
#

So ehm

#

Lemme ask you dis question

#

Is it possible you can teach me how to build a website?

native tide
#

Pretty sure the subject is a bit too complex to be taught by one person over discord. You have to "do your own research"

deep tinsel
#

Yea but the thing is

#

Idk what the fuck I gotta search

#

Should i really just go on fucking YouTube and search "how to build a website using PyCharm"?

native tide
#

no, you search "how to build a website using python"

#

pycharm is just an ide?

lilac solar
native tide
#

fyi, you don't need fancy editors to code, you could even make a website with python using just notepad

spark dagger
#

hi can someone help me with django channels here

#

with auth specially

honest tartan
#

hey guys can anyone here help with a django jwt issue?

lethal junco
deep tinsel
lethal junco
# deep tinsel Thx

here you can watch Mosh, he's a very good teaching things and you can understand it very easily

deep tinsel
#

Thx

#

Fr, thank you

dusk portal
#

im learning from idk how many months

#

more then 3-4

#

whole day

#

and this guy taught in 1 hr

#

wtf lol

dusk portal
#

i need a help

#

anyone's up

#

very complex to explain here

foggy plover
#

Hey! If we are taking formData input type at the frond-end in react, then how can we handle the same at in flask?

#

At the frontend it is being stored like, formData: new FormData()

lethal junco
#

well for me anyway

dusk portal
#

dont crack jokes bro

#

i was good in web d foundations before jumping into django

#

i was a flask dev

#

if u wanna be a noob just do less time

#

but for practice different use cases

#

different places different methods

#

for a big

#

intermediate n a small app too

#

u need to give time

#

if u wanna be a good dev

lethal junco
#

indeed, more time, more effort

dusk portal
#

yes

pulsar lance
#

Having an idea of how things work and being able to put it all in different case scenarios is a different thing!

dusk portal
#

no more discussion

#

i wanna be sigma male

#

so just told my suggestion

#

u can surf yt n all for more info

#

if u just wanna make simple app it will take less then a day

#

but to master foundations 3 months

#

and for advaned stuff more 2-3 months

frank shoal
dusk portal
#

ig its request.FORM.get

foggy plover
frank shoal
#

!d flask.request

lavish prismBOT
#

To access incoming request data, you can use the global request object. Flask parses incoming request data for you and gives you access to it through that global object. Internally Flask makes sure that you always get the correct data for the active thread if you are in a multithreaded environment.

This is a proxy. See Notes On Proxies for more information.

The request object is an instance of a Request.

frank shoal
#

!d flask.Request.form

lavish prismBOT
#

property form: ImmutableMultiDict[str, str]```
The form parameters. By default an [`ImmutableMultiDict`](https://werkzeug.palletsprojects.com/en/2.0.x/datastructures/#werkzeug.datastructures.ImmutableMultiDict "(in Werkzeug v2.0.x)") is returned from this function. This can be changed by setting [`parameter_storage_class`](https://flask.palletsprojects.com/en/2.0.x/api/#flask.Request.parameter_storage_class "flask.Request.parameter_storage_class") to a different type. This might be necessary if the order of the form data is important.

Please keep in mind that file uploads will not end up here, but instead in the [`files`](https://flask.palletsprojects.com/en/2.0.x/api/#flask.Request.files "flask.Request.files") attribute.

Changelog Changed in version 0.9: Previous to Werkzeug 0.9 this would only contain form data for POST and PUT requests.
cerulean badge
#

(context django) i am making a chat app which have models Chat and Messages.
when a user adds a new contact
i create a chat object and send a message to a group containing all channels (i named the group global)
and then check if the connected user is member of the chat , if yes then add it to group of that chat

my question is
should i be sending a message with the socket to create the chat app or do it with just ajax and send the message to the group in the save method of the Chat?

tight agate
#

@cerulean badge I'm starting a build soon that requires chat. Would love to snap that module in when you're done if you don't mind me using it?

cerulean badge
#

(context django) how to check if presence of list of objects in m2m field?
all should be present

stark tartan
#

hey i am going to build the video chat website using django WEB-RTC with django channels please give some docs or any suggestion is it possible to do this ??

stark tartan
cerulean badge
#

(context django) i have a Chat model with m2m to User model, how do i filter all chats having members both user1 and user2?

turbid horizon
#

I know that this is a pretty general question but one of my cousins suggested that I build a webapp that runs on a python server for a school project. The problem is that I have no clue what that is and whenever I google what that is it just gives results on how to make one not what it is. Sorry if it is obvious but thank you if you can help me. Even if you can share a link or anything like that it can help.

mystic wyvern
#

why this happen ?

fickle garnet
# turbid horizon I know that this is a pretty general question but one of my cousins suggested th...

A web application (or web app) is application software that runs on a web server, unlike computer-based software programs that are run locally on the operating system (OS) of the device. Web applications are accessed by the user through a web browser with an active network connection. These applications are programmed using a client–server model...

inland oak
turbid horizon
#

thanks for the answer @fickle garnet and @inland oak they helped alot

foggy plover
#

Hey! How can I serve an image file saved in MongoDB? Any solution instead of saving the file locally?

frank shoal
#

you should save images and other blobs on a filesystem.

#

though with mongo, it uses bson, which supports raw bytes.

foggy plover
#

Okay, so I should save all the files in the file system only?

frank shoal
plucky heron
#

pydantic question.
Is there a good way to make all fields optional for a query but make them dependent. In case of one query arg is used few others must be used?

turbid horizon
#

I am going to start learning how to make webapps but I am unsure whether to use flask or fast api? Which one will be better/easier to learn?

warm igloo
native tide
#

is there a point to having jquery if u have react

calm plume
#

Nope.

native tide
# calm plume Nope.

html, css, django(python), JS, react, jQuery, SQL for this would u just take out jQuery

calm plume
#

Looks about right

native tide
#

why pop it off

calm plume
#

When you have JSX, there's no need for jQuery

sacred crane
#

hi

#

I want in my program that when a person select a word, with that word appear in a file txt and can upload it

#

someone to help at priv

scarlet crater
#

im not to sure what would be the best option for me to use, but im webscraping data off of a website which i want to then display on my own website. how should i do this

currently the only option i know of doing would be sending the data with socketIO to a node server but is there any python packages which allow me to edit a webpage like this?

candid meteor
#

how do i promote websites/social apps

native tide
#

um hello what editor can you use for javascript?

calm plume
native tide
#

thanks

native tide
#

is javascript better or html/css for a website?

vestal hound
#

they do different things

native tide
#

ok

hot granite
#

in flask routes can you make *args? i mean

@app.route('/route/*')
def route(*args):
    return str(args)

/route/a1/a2/a4/
['a1','a2','a4']

jovial cloud
hot granite
#

yeah, but im asking is there a way to do like this

#

i mean ofcource there should be a base route get method, maybe i can overide that instead if there is no *args, but i just cant find that function

jovial cloud
shut bloom
stable sentinel
#

hey peeps! Any django-crispy-form wizzards around?

#

I seem to have a question that has no answer in the docs

#

I am trying to set type attribute for an input field but not sure of the **kwarg name and can not seem to find it anywhere... it's not type, as type() is a reserved keyword. there's ref. to class for which is css_class but not for type

#

I am trying to render a form with crispy.helpers and this form is meant to have password field that can be toggled and I'd like to achieve this without setting a widget

uneven radish
#

I'm making a simple Django project (Todo Application)
So, let's say there are multiple users and they login and add a Task.
Now, while displaying a task, I have used slug in URL to display a particular Task (for that particular user)
Now I have added slug as unique for that Created date (when the task was created). This works fine but when I try to save a new task under another user with the same slug for lets say user X, it shows error. Which is expected.

#

How can I avoid this behavior? Is there a way where I can limit slug uniqueness only to particular user and particular Created date. But not globally.

#

That is, multiple users can create same slugged Task for any particular day, but one particular user when creating a new task for that day should get and error that this task is already added.

#

Hope this makes sense.

#

In short, unique table for every user.

hallow yacht
#

maybe not related here but. but i have a website i want to scan that displays a red square around a specific kind of part of the site. but it is not in the html its javascript based i think

chilly falcon
#

any guide on how to send mail from django rest framework

#

i want to send mail for reset password

#

any blog tutorial guide ?!!

brisk drum
#

Hi!
I need to make a python script which, given a php web page where news are posted, it takes the link of latest posted news and print it
How can i do this if there is a way?

inland oak
#

requests library + bs4 library to parse it, as the lightweightest easiest solution

#

if there would be some sort of difficulties... then firing heavy artilery in form of selenium

ancient ridge
#

Hey guys so I am following a tutorial and it tells me to do this step

#

This one

#

So can please some assist me on how to do this step?

#

Anyone????

uneven radish
#

You need a directory "templates" in your app directory, which will store your HTML files.

#

Project
-->App1
------>templates
---------->App1
-------------->index.html
-------------->something.html
---------->base.html
-->MyWebsite

thin crystal
#

Anyone else here build crawlers? seems like the best channel to ask in

fickle garnet
#

whats the difference between a crawler and a scrapper ?

thin crystal
#

a crawler's primary purpose is indexing

#

to be found, not to keep

fickle garnet
#

i remember spider

#

crawling though html is straight forward enough right ?

thin crystal
#

yeah very, it's doing it at scale that becomes complicated

#

you want to crawl a page or two, that's cake. You want to do 20 million pages a day, that's a bit more complex

dapper solar
#

Hi can anyone please help me? i am trying to pre populate the wtf form from given data but its not working for some reason !

@app.route('/write',methods=["POST","GET"])
def write():
    prevLetter =Letters.objects(author=session["user"]["username"], status = "draft").first()
    form = WriteForm()   

    if prevLetter :
        print("block 1")
        form.title.data=prevLetter.title
        form.content.data=prevLetter.content

    return render_template("write.html",form = form)
native tide
#

what does your template/html look like?

dapper solar
#

ah i figured it out. i had script tag clearing my text fields

native tide
#

awesome debugging

dapper solar
#

lol sorry to bother

native tide
#

no problem at all

native tide
#

i'm donig python exercises and i didn't know the list() method can turn a list into an array

#

i'm perplexed by that

#

is it different because of how an array is stored in memory as opposed to a list? In python at least

#

oh my god i'm an idiot sorry guys.

#

so what i had was zip(*2d_list) and that zip function returns a damn zip object which returns a tuple
doing list((1,2,3)) turns a tuple into a list lol

indigo kettle
#

it does indeed

#

do you need it to be a list?

dense trout
#

Hey, I have a problem with tests in django

class AboutPageTests(SimpleTestCase):

    def setUp(self):
        url = reverse('about')
        self.response = self.client.get(url)

        def test_aboutpage_template(self):        self.assertTemplateUsed(self.response,'about.html')

Running test return ```AssertionError: No templates used to render the response

#

in views ```py

class AboutPageView(TemplateView):
template_name = 'about.html'

native tide
#

Could someone help me with Django problem?

I have connected my Django server to PostgreSQL, created 2 tables for car and driver with help of python manage.py migrate, then removed those tables inside the PostgreSQL bash with help of DROP table, but now I still have them inside my permissions

#

but there are no car / driver tables in database

warm igloo
#

Advice: If you're going to do db migrations, do db migrations. Don't mix doing migrations and manual changes.

terse vapor
#

i got a question regards python web scraping, i saved all the data for each section(title, date, etc) in a indivisual list, and saved in a big list, something like list = [[title], [date]], and access by index element. However is there a method allows me to find any match string as my target item inside the date and remove all the text with that index element

native tide
#

Hew what does {%%} this trype of thing do and where to learn about it

#

in html

raw compass
candid meteor
#

flask 😭

#

darkwind 😐

#

why are you telling me what {% does

inland oak
raw compass
#

Not necessarily a loop. Though yes the engine allows loops. such as

    <ul id="navigation">
    {% for item in navigation %}
        <li><a href="{{ item.href }}">{{ item.caption }}</a></li>
    {% endfor %}
    </ul>
inland oak
native tide
inland oak
#

The main purpose is DRY, to have much more reusable code

#

Defining menu code once for all pages in the site for example

native tide
#

like a nav bar

broken harness
#

Hello everybody \o/

#

Decided to make myself a basic website using python \o/

native tide
#

ok

#

advil?

broken harness
#

yes

#

loads

native tide
#

oh

broken harness
#

sure

native tide
#

i maen

broken harness
#

idk what advil is but i'll take 3

native tide
#

the service

#

search it

broken harness
#

oh im using Django with python

native tide
#

for python

#

oh

#

sheesh

#

same

broken harness
#

is django not the best? 🤔

native tide
#

well

#

no

#

php is better

broken harness
#

😦

native tide
#

then node.js

broken harness
#

😮

native tide
#

😉

#

ur welcome

#

if u want to rebel

#

use c#

broken harness
#

if i wanted to be difficult I'd use straight up C or even binary to program my website

inland oak
native tide
#

100%

#

then node.js takes over

inland oak
native tide
#

faster html files

inland oak
native tide
inland oak
#

I am thinking to go for golang as next lang

#

it fits my dev path better

native tide
#

GO?

inland oak
#

yeah

native tide
#

just 'go' hahah, with rust

#

think of the long run

inland oak
#

about what am I supposed to think

native tide
jaunty depot
#

hello
I decided to help out my friend and make her a website for her business. So far it's been going smoothly, but I've never done any page at all and now I've bumped into a problem that I can't resolve
I wanted to make a navigation bar with some buttons and an icon. I wanted to make the three buttons evenly justified and to that I wanted to add an icon to the left. However I can't make it "jump" in line with those buttons. I have made some attempts, unfortunately non of them worked for me.

#

could anyone point me to my desired result? I would be very grateful
My code looks like this:

html

        <img src="static/icon.png" width="60" height="50" alt="icon" style="vertical-align:bottom" >
        <!-- <ul><li><img src="static/icon.png" width="60" height="50" alt="ikona" style="vertical-align:bottom" ></li></ul> -->
        <ul>
            <!-- <img src="static/icon.png" width="60" height="50" alt="ikona" style="vertical-align:bottom" > -->
            <li>Offer</li>
            <li>Contact</li>
            <li>About</li>
        </ul>
    </nav>```


css
```ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: rgb(30, 57, 88);
    display: flex;
    justify-content: space-around;
}


li {
    font-family: sans-serif;
    color: rgb(255, 255, 255);
    /* text-align: center; */
    padding: 16px 16px;
    text-decoration: none;
}

li:hover {
    background-color: rgb(86, 152, 190);
}```
#

I tried to make two unordered lists side by side, but that didn't work either, that's why I have those img sources in comments, I was trying out things

#

I also thought that it will help to put an image next to unordered list, but that put my icon on top of the navbar

dire urchin
#

is it a good idea to use webp over gifs? I have a a couple of gifs loading at once so I figured I'd convert them to webp but I heard there's some browser compatibility issues

swift glen
#

guys quick question. you can deploy 2 apps in one cloud server right? like for example django backend and angular frontend at the same time?

trim wolf
inland oak
#

it redirects from http to https

#

using just http is unsafe in production, we are supposed to use verified cerificates and only https mode

trim wolf
#

oo

frank shoal
#

I am doubting you're hosting on https.

orchid olive
#

question: lest say that i have 2 webpages for 2 different purposes: sales and inventory, both in the same server and different ports, but both web page use the same variables, lest say session["user"],

do that will create a conflict if the user A login sales and user B login inventory in the same pc?

normal tulip
#

Hi all, got a question and I haven't found a solution by googling yet. I am using requests and bs4 to do some scraping. Over the past week the page I have been successfully scraping via AWS Lambda for 2 years made a change and is now sending a 403 response if you don't have cookies enabled ( javascript: var cookiesEnabled=(navigator.cookieEnabled)? true : false; ). Does anyone know a way around this? I believe I need to specify a user agent and somehow enable this, but that's only a guess. Any help is greatly appreciated!

orchid olive
#

also i have no documentation, php had a way to split session by user, but i have not find how to do the same in python-flask

#

can i use session["inventory"]["user"] ?

limber flower
#

Help!! me, I want to take an existing url from the web and make a backend for it, can I do it with django?

warm igloo
warm igloo
normal tulip
#

so nothing too critical or anything 🙂

warm igloo
#

right but their changes could be because they are trying to mess with bots by having that js check on cookies

normal tulip
#

understood, not trying to argue w/ you

warm igloo
#

oh I know, sorry if it is coming off harsh

normal tulip
#

in my googling i found people having this issue w/ cloudflare, and it looks like they are now using cloudflare 🙂

#

selenium/chromedriver looks to be the workaround, just gotta figure out how to do that in aws lambda now

warm igloo
#

I did look at their TOS and spidering/crawling/etc is forbidden. So best of luck as it sounds like you have a totally non-shitty bot (like a sneakerbot or whatevs) but yeah ... sorry. :/

frosty lance
#

Django or flask?

olive patrol
native tide
#

hello

#

i need help please

#

thats my codfe

round plinth
#

First off, is there any reason why you are using var instead of let / const ?

#

Second ...
```js
/* code here */
```

#

you can edit your message for the second part

round plinth
# native tide

Third, I know that error.

// When you did this
progress.max = requiredclicks;
// The result of this (which wouild be outputted to the console) was actually false
console.log(Number.isFinite(requiredclicks));
// Put this last line before the `progress.max` assignment line
// or add that argument to the `console.log` that outputs `requiredclicks`
round plinth
#

NaN, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY, or a non-number ... all would be invalid for that.

#

Also, the progress bar has a minimum of 1 ... I think ... lemme check

native tide
#

wym

round plinth
#

oh ... after testing <progress> tags default to a missing value attribute (the "indefinite" state) and also default to max being 1 (but it can be any finite number that is positive )

#

Somehow your program tried to set progress.max to a value which is not valid ....

native tide
#

oh

#

progress.max = requiredclicks;

round plinth
#

yeah.

native tide
#

how is requiredclicks not valid

round plinth
#

somewhere, requiredclicks was not a finite number.

native tide
#

what does finite mean xD

round plinth
#

finite means it is a number, and NOT one of these special values:

NaN // Not a Number
Number.POSITIVE_INFINITY // can get it by a huge calculation
Number.NEGATIVE_INFINITY // same as above but it is a negative number
#

You can get one of those easily if you divide by zero

native tide
#

okay ty

#

any idea how to fix it?

round plinth
#

what is your requiredclicks getting set to?

native tide
#

level * 250 + multiplier * 50

round plinth
#

Ah, I think I see why.
When you call loaddata() your localStorage might not have level set (or it was cleared), or the value you got is set to a non-number.

By the way, localStorage IIRC always returns a string if the value is set (I forgot if it returns null if the value is unset or not)

native tide
#

oh ok

#

so i should set level to local storage?

#

level = parseInt(localStorage.getItem("level"))

#

i have

round plinth
#

.... you probably should make a class to help hold the data in memory and let that update your localStorage for you

native tide
#

im quite bad with classes

#

im new to js

round plinth
#

Ah.

#

Lemme find the link

native tide
#

do u know how to use classes

#

@round plinth

#

if u do do u think u can put that into a class for me

round plinth
#

I can do that, but it would be spoon feeding you the code.

native tide
#

alr

#

idk how to put it into a class

#

@round plinth

native tide
#

hi guys , how are you

wind dove
#

I have a mini project I'm working on and I setup a little flask site to interface it remotely and I left it on today (It's port forwarded) and I got these requests seemingly from nowhere:

#

I'm assuming this is some bot testing a security glitch on something like wordpress but anyone know any more info on it.

#

The end of the url I blocked out is Mozi.m+-O+/tmp/netgear;sh+netgear&curpath=/&currentsetting.htm=1

native tide
#

a cyber attack lol

#

where's your flask site deployed to?

wind dove
#

I was just home hosting it

turbid horizon
#

Is codeacedemy a good resource for learning flask?

urban sleet
#

For any web development related assignment kindly HMU .Quality and on time delivery assured.I can provide samples on request.Thanks

native tide
turbid horizon
#

I have basic experience in c++ and c# I know the basics of python but I just started python around a month and a half ago and I am starting to learn flask. So a beginner

native tide
turbid horizon
native tide
turbid horizon
native tide
#

good luck, i'm also learning. keep at it.

golden ibex
#

I've never worked with Web Auth before. I have a Flask site I'm putting together that allows OAuth "Sign in With X" only for logging in and I'm unsure what to do with their credentials when they sign in. Do I just take their Email Address and check for existing user and otherwise create it? Then for keeping logged in how does that work?

golden ibex
#

Actually I think I got it, I needed to utilize Flask-Login with Flask-Dance

native tide
#

hi is anyone here an app developer?

dire fractal
#

Loads of people

native tide
#

hello can anyone tell me how to publish a site using VS code?

#

have made i want to get a url and all and make it available for public use

native tide
#

deploy it on firebase

#

@native tide so you have like the html css and javascript files?

native tide
#

what is firebase?

#

oh you are just starting

#

yes

#

um

#

okay there are alot of things to learn

#

you gotta learn how the internet works

#

things like hosting domain names etc

#

just google it or watch a video on youtube

#

um can you explain this in detail to me after half an hour

#

i have a school class

#

thanks

#

bro just google it or watch a youtube video

#

um ok

gritty sage
#

Hi friends, I am after a bit of help, im trying to scrape a table off a website, but i need to fill out a search bar before the table is shown, I want to figure it out for myself but not sure what to search up on google, what are these websites called?

#

eg copy paste the url into another browser (or python) and the table is reset and search terms need to be reloaded

gritty sage
#

I can copy paste the table but then need to convert to csv?

limber flower
trim wolf
#

Hey Everyone!! Urgent help needed!!

Whenever I try to login in my Website it gives a 403 Forbidden Error
The Message: CSRF verification failed. Request aborted.

But I have {% csrf_token %} in my login form
Also I am using Django!

hoary yarrow
#

can you make a website with only python or would you also need html

hoary yarrow
#

crap

#

idk shit ab html

inland oak
#

I would say knowing some CSS is also preferable if u wish it looking good

hoary yarrow
#

i only know python sadly

#

still learning about it too

inland oak
#

As easiest and fastest solution

#

To have good looking site

elder echo
#

Hey everyone goodnight, so I've been specializing in the MERN stack but I don't really know any frameworks/libraries besides socket.io... What technologies would you guys recommend?

lilac solar
long monolith
# turbid horizon I have basic experience in c++ and c# I know the basics of python but I just sta...
GitHub

Student details, source code, and more for our HTMX + Flask: Modern Python Web Apps, Hold the JavaScript course. - GitHub - talkpython/htmx-python-course: Student details, source code, and more for...

GitHub

Awesome things about htmx. Contribute to rajasegar/awesome-htmx development by creating an account on GitHub.

elder echo
#

I’ve heard development on django and flask is quick but it could be slow at times

trim wolf
#

Hey Everyone!! Urgent help needed!!

Whenever I try to login in my Website it gives a 403 Forbidden Error
The Message: CSRF verification failed. Request aborted.

But I have {% csrf_token %} in my login form
Also I am using Django!

lilac solar
native tide
#
<!DOCTYPE html>
<html>
    <head>
        <title>Store</title>
       
    </head>
    <body>
        <h1>Jay Derep</h1>
        <strong></strong><p>web dev</p></stong>
        <img src ="https://cdn2.iconfinder.com/data/icons/avatars-99/62/avatar-370-456322-512.png" width="100" height="100">
        <hr />
        <i></i><h2>Summary</h2></i> 
        <p>i like doing web dev its fun</p>
        <hr />
        <b><h2>experiance</h2></b>
        <ul>
          <i><li>html</li></i>
            <p>i am learning</p>
            <br />
         <i><li>css</li></i>
            <p>still learning</p>
            <hr />
        </ul>
        
        <table border="1">
        <h2>skills</h2>
            <tr>
                <i><th>Languages</th><i/>
                <td>python</td>
                <td>c#</td>
                <td>kotlin</td>
            </tr>
        </table>
        <i><h2>Contacts</h2></i>
        
        <a href="link one" target="_blank"></a>
    </body>
</html>```
#

Has this error

sonic island
#

django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'stocks.Investor' that has not been installed
stocks is added to installed_apps and auth_user_model is also configured
How to solve this error?

glad egret
#

how to link html front end with python backend?

#

i found this code on net:

#
<form name="search" action="/cgi-bin/test.py" method="get">
Search: <input type="text" name="searchbox">
<input type="submit" value="Submit">
</form> ```
#

but I dont know what is cgi

native tide
#

Presumably a resource on the site where this form is hosted. If the form is on a domain like example.com, /cgi-bin/test.py is going to be found at example.com/cgi-bin/test.py

glad egret
#

my form is stored locally

#

on my device

native tide
#

Do you have a folder locally cailled /cgi-bin?

glad egret
#

my backend name is fetcher.py stored in same folder as my html form

native tide
#

You should be able to set that location to fetcher.py then, but like the action field just sends the data as an http request to that "endpoint", and if it's a python file, I'm not sure how that will consume it

#

Where was that tutorial?

glad egret
#

stackoverflow

#

my question is will this work?

#
<....... action=".......\fetcher.py">```
#

instead of cgi?

native tide
#

It will not, since that is not something that accepts an http request

glad egret
#

by the way what is cgi?

native tide
#

You could use an http server on your backend? Something like flask or django or starlette

#

CGI is just the name of the folder for that specific problem

glad egret
#

nothing special?

native tide
#

Could you link that SO post?

glad egret
#

yes

#

another query. Actually i wish to store the value written in my form.html to fetcher.py

native tide
#

Interesting, I think I was wrong then. CGI is another http framework

glad egret
native tide
#

Both ... and its alternate name are improperly configured
Domain does not resolve to the GitHub Pages server. For more information, see Learn more (NotServedByPagesError). We recommend you add an A record pointed to our IP addresses, or an ALIAS record pointing to suiniee.github.io.
how do i fix this? i dont understand the error

native tide
#

Like mentioned before, http and cgi are builtin, but 3rd party frameworks provide more utilities

#

Those include flask, django, starlette, fastapi, etc

glad egret
#

then how to create a cgi-bin python file?

native tide
#

The cgi section on the python docs covers how to do it, but it's a bit involved

mighty iris
#

@native tide, are you familiar with fastAPI?

native tide
#

Yeah I've used it before

mighty iris
#

Can I dm u?

#

for a short question

native tide
#

I prefer you ask here since others can correct me, and I'll be leaving soon

mighty iris
#

oh ok

#

how do i past python code here?

native tide
#

!code

lavish prismBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

native tide
#

or if it's long

#

!paste

lavish prismBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

mighty iris
#
  • a POST request with a boolean parameter that returns the current date in yyyy-mm-dd hh:ii:ss format if the parameter is set to true and returns the date in yyyy-dd-mm format if the parameter is set to false
  • a GET request that retrieves the value of a counter of the number of times either of the two endpoints was called
lavish prismBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

mighty iris
#
from typing import Optional
import threading
from fastapi import FastAPI
from datetime import datetime
app = FastAPI()

counter = 0
lock = threading.Lock()

@app.post("/fecha")
def mostrar_fecha(formato : bool): 

    global counter
    with lock:
        counter += 1

    if formato:
        fecha = datetime.today().strftime('%Y-%m-%d-%H:%M:%S')
    else:
        fecha = datetime.today().strftime('%Y-%m-%d')

    return {'Fecha':fecha}


@app.get("/counter/")
def count():
    global counter

    return {"Counter":counter}

#

Is that correct?

#

I mean, it works

#

but it's an important assignment, and wanna get full score

native tide
#

It looks fine yeah, but depending on how heavy the load to your server is, using that lock inside the function can slow things down

regal fossil
#

QUESTION
Django
When using django signals do we have to write each signal for each model?
for example if we have a models User, profile, Education, and has OneToOne Relation with Profile and Forignkey with Education so do we need to write signal for each of the model separately or only one signal for both?

native tide
#

I.E, if you get two requests at the same time, you have to process them synchronously because the lock is held by one request at a time

#

Now in this case, since the lock is only held for a fraction of a second, it's probably fine

mighty iris
#

I mean, this is a very simple project

#

Do you think the lock is necesary?

native tide
#

I don't know what your professor/teacher is looking for though

glad egret
#

python script uses import cgi is that sufficient

mighty iris
#

The server won't overload

native tide
#

Actually the lock may not be necessary since you aren't using an async function

mighty iris
#

yeah

#

I'll delete it

#

I haven't seen the lectures lol, I should

#

He just wanted us to learn basic backend stuff

#

Thanks for your help 🙂

glad egret
#

i need some help in cgi. has anyone used this before?

native tide
glad egret
#

is writing import cgi sufficient to create a cgi-bin file? or I need to install some things too?

#

in simple words does the code sent by you sufficient to change a nomal .py file tocgi file?

native tide
#

Yes, but, you also need to put it somewhere specific

glad egret
#

also does a cgi file work if not stored in a cgi-bin file?

native tide
#

For instance, the SO post uses cgi-bin which is the default for linux

#

What OS are you using

glad egret
#

the documentation says that it works on servers only

#

i use Windows 10

native tide
#

So you can use it on windows 10, but the process is a bit involved. You have to install the CGI element.

#

I've gotta run now, but I think that's the gist of it

glad egret
#

after installing the cgi element?

native tide
#

how can i connect my flask code to my domain?

mortal pike
#

If you guys have any experience working with sockets and ngrok, I have an interesting problem I have not been able to solve combining django with sockets for networking between server and raspberrypi. Full question: https://stackoverflow.com/questions/69503197/ngrok-with-python-and-raspberry-pi
Or Join
#code-help-voice-text

glad egret
#

@native tide I installed CGI now what is the next step?

stark tartan
meager anchor
#

the error tells you what you need to do, you can't call a synchronous method (get_object_or_404 from the ORM) from an asynchronous context

native tide
#

how would i make a button that would be at center for every screen size?

mortal condor
#

im making like a website through html and i have this python file for a game, i was wondering if i can somehow make it so u can run that python file through the website

#

without needing to download the python file and its code

vestal hound
#

and then update DNS records to make your domain point to where you're hosting the code

native tide
#

I got it, thanks.

mortal condor
vestal hound
mortal condor
vestal hound
#

your browser is (basically) incapable of running Python code

mortal condor
#

oof

sly echo
#

Hello

#

I've a query as I'm just a beginner

#

I have got command on basic Python like OOP, loops, functions, strings, variables, lists, data structures and algos.

#

I'm willing to learn Django now.

#

Do I need to learn HTML and CSS before I jump to Django?

vestal hound
#

BUT Django has a lot of magic in it

#

you might get kinda lost

sly echo
#

So how should I begin

#

I know about basic html though like what are simple tags and making a simple site with just head body and p tags lol

#

Is this much HTML enough?

vestal hound
#

uh

#

probably not

#

🥴

#

CSS is quite important

#

tbh

sly echo
#

So how should I begin?
with SQL or with HTML/CSS?

vestal hound
#

because it controls layout

sly echo
#

How much SQL do I need to learn?

#

People say you don't need much SQL to learn for Django unless you really need to dive into database engineering

#

My teacher said you need only 1 week of SQL practice and that's all.

digital edge
#

is this a channel where i ask about selenium? or diff one

limber flower
#

How to retrieve post data from a custom form in django?

native tide
#

Is there a way i can learn about what {%%} and how to use it for reusing code

#

dm me

wooden ruin
wooden ruin
limber flower
#

Hmm

wooden ruin
wooden ruin
#

like this

limber flower
#

it gave me a multivaluedictkeyerror

wooden ruin
#

the html input fields need a name attribute

#

that same name u use to access the value of it

limber flower
#

o ok

#

and 2 more things

#
if request.method == 'POST':
        form = UserRegisterForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            email = form.cleaned_data.get('mail')
            age = form.cleaned_data.get('age')
            password = form.cleaned_data.get('password')

            htmly = get_template('user/mainpage.html')
            d = { 'username': username }
            subject, from_email, to = 'Welcome!', 'abc@gmail.com', email
            html_content = htmly.render(d)
            msg = EmailMultiAlternatives(subject, html_content, from_email, [to])
            msg.attach_alternative(html_content, "text/html")
            msg.send()

            messages.success(request, f'Your account has been created !')
            return redirect('login')
    else:
        form = UserRegisterForm()
    return render(request, 'user/sign_up.html', {'form': form, 'title':'register here'})
limber flower
#

This is a code. (I took it from a website)

#

In this code, where is the stuff being stored?