#web-development

2 messages · Page 209 of 1

plucky cape
#

nope

#

it still says

#

incorrect

#

the admin log in?

#
@app.route('/admin_login',methods=['GET','POST'])
def admin_login():
    msg = ''
    if request.method == 'POST' and 'username' in request.form and 'password' in request.form:
        username1 = request.form['username']
        print(username1)
        password1 = request.form['password']
        print(password1)
        cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
        cursor.execute("SELECT * FROM accounts WHERE username = %s AND password = %s AND adm = 'yes'", (username1, password1,))
        account2 = cursor.fetchone()
        print(account2)
        if account2:
            session['loggedin2'] = True
            session['id'] = account2['id']
            session['username'] = account2['username']
            return redirect(url_for('adminhome'))
        else:
            msg = 'Incorrect username/password!'
    return render_template('admin_login.html', msg=msg)
#

nope

#

aaaaaaaaaa

#

whats wrong with the template file now

#

wdym between?

#

its showing the incorrect pass thing

#

yea

dusk portal
#

Hey i need help ;m facing issues in handling img file in django by request.files idk why

@login_required
def course_upload(request):
    if request.method == 'POST':
        course_title = request.POST.get('course_title')
        course_desc = request.POST.get('course_desc')
        course_subj = request.POST.get('course_subj')
        course_thumbnail = request.FILES.get('course_thumbnail')
        course_author = request.user
        print(course_desc,course_subj,course_thumbnail)
        entry=Course(course_title=course_title,course_desc=course_desc,course_subj=course_subj,course_thumbnail=course_thumbnail,course_author=course_author)
        entry.save()
        messages.success('Course Uploaded!')
        return HttpResponseRedirect(reverse('home:index'))
    return render(request,'index/course-upload.html')```
dusk portal
# dusk portal

so the thing is when im filling the form its showing this error
n it's not adding default value but when im adding a post through admin panel its adding the default

#

n when im trying to upload thumbnail then too it isnt storing to db
its showing same error

#
<div class="input-box file-box">
              <span class="details">Thumbnail</span>
              <div class="dragarea">
                <header class="header">Drag & Drop To Upload Thumbnail</header>
                <span>OR</span>
                <a class="browse" onclick="clike()" style="border: 1px solid #11101d;border-radius: 4px;padding:6px;cursor: pointer;">Browse</a>
                <input type="file" name="course_thumbnail" id="course_thumbnail"  hidden>
              </div>
             
              </div>```
#
class Course(models.Model):
    course_title=models.CharField(max_length=90,unique=True,null=False,blank=False)
    course_desc=models.TextField(null=False,blank=False)
    course_subj=models.CharField(max_length=20,choices=course_subject_choices,blank=False,null=False)
    course_thumbnail=models.ImageField(upload_to='Course_Thumbnail',default='default_course.jpeg',validators=[validate_image_file_extension])
    course_author=models.ForeignKey(User,on_delete=models.CASCADE)
    course_published_on=models.DateTimeField(auto_now_add=True)
#

thx in advance

#

any help would be appreciated.

upper goblet
#

anyone goold with django

warped aurora
#

trying to figure out how to do an sqlalchemy query in my flask view when I open a bootstrap modal

upper goblet
#

this isnt practical for the admin

#

they need to see which bookings

#

@thorn lily

native tide
#

why doesn't this work?

#

if reaction.emoji == ['8️⃣', "7️⃣", "6️⃣", "5️⃣", "4️⃣", "3️⃣", "2️⃣", "1️⃣", "0️⃣"]:

#

fuck

native tide
#

wrong channel

upper goblet
warped aurora
# thorn igloo what?

I want to click a button in my html which then executes a function in my flask view

thorn lily
#
>>> class User:
...     def __init__(self, name, age):
...         self.name = name
...         self.age = age
>>> print(User("ROY", 1))
<__main__.User object at 0x7fbf62289460>

>>> class User:
...     def __init__(self, name, age):
...         self.name = name
...         self.age = age
...     def __str__(self):
...         return f"User - {self.name} - {self.age}"
>>> print(User("ROY", 1))
User - ROY - 1
#

And similarly, the string representation will be used in the admin dashboard

golden bone
thorn igloo
upper goblet
#

so how do i print manytomany

#

relationship>

warped aurora
thorn igloo
thorn lily
upper goblet
#

i did

thorn lily
#

what was the makemigration output

upper goblet
#

also im getting this error when

#

it seems i cant add whats in the basket

#

to the service

warped aurora
golden bone
upper goblet
#

@thorn lily

thorn igloo
#

considering flask produces static content, i believe a post would be the best way to go on about this

warped aurora
#

Ok so I would wrap the link in a form like this
<form action="" method="post" id='myForm'>
<input type='hidden' value={{{row.value}} />
<a href="#" onclick="this.parentNode.submit();"> List item 1</a>
</form>

and then get the form value

@app.route("/", methods=['GET', 'POST'])
def page():
if request.method == 'POST':
data = get_data_for_modal(request.form['value']

#

but then how do i pass that data back to the template? @thorn igloo

upper goblet
#

hey guys anyone hre

#

i need help

thorn igloo
warped aurora
thorn igloo
#

i guess

south stump
#

Using Flask, SQLAlchemy & Marshmallow.

When i generate a DateTime it puts it in this format:

2000-12-28T20:50:11

However when I try to update an entry with this for example:

PUT http://127.0.0.1:5000/weathers/update-date
Content-Type: application/json

{
  "id" : "1",
  "date" : "2000-12-28T20:50:11"
}

It doesnt work. Printing exceptions shows:

    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type type is not JSON serializable
127.0.0.1 - - [28/Dec/2021 21:11:33] "PUT /weathers/update-date HTTP/1.1" 500 -****
#

any suggestions ?

golden bone
south stump
# golden bone What's the code that's generating the error? I suspect the problem is with the r...

just a simple print:

@app.put("/weathers/update-date")  # MODIFY DATE
def weather_update_date_json():
    json_data = request.get_json()
    weather = Weather.query.filter_by(id=json_data['id']).first()
    if weather is None:
        return {"Message": "Entity with id doesnt exist"}
    try:
        Weather.query.filter_by(id=json_data['id']).update(
                dict(
                    date=json_data['date']
                    )
                )
        db.session.commit()
    except Exception:
        print(Exception) ### <<<<<<<<
        return {"Message": "Error fulfilling update request"}
    return {"Message": "Record updated in DB"}
upper goblet
#

ypp

#

TypeError at /customer/book
Field 'id' expected a number but got ['70wPdi0O', '3BgjwlbE'].
Request Method: POST
Request URL: http://127.0.0.1:8000/customer/book
Django Version: 4.0
Exception Type: TypeError
Exception Value:
Field 'id' expected a number but got ['70wPdi0O', '3BgjwlbE'].
Exception Location: /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/db/models/fields/init.py, line 1824, in get_prep_value
Python Executable: /usr/local/bin/python3
Python Version: 3.9.6
Python Path:
['/Users/arnantaroy/Documents/GitHub/afterglow_website',
'/Library/Frameworks/Python.framework/Versions/3.9/lib/python39.zip',
'/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9',
'/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/lib-dynload',
'/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages']
Server time:

#

any suggestion?

wind abyss
#

I'm a little bit confused on what Serializers and Viewsets do?

wind abyss
#

Oh I mean just in general

south stump
#

serializes allow you to put variables/json into http packages as far as im aware

#

no idea when it comes to viewsets

wind abyss
#

Icic

#

Thank you

upper goblet
#

help me out

south stump
#

plus you aint included the package youre trying to send

#

if you read the log its expecting an ID and its not getting it. So i would start there

upper goblet
#

ik

#

but i dont haave id in my model

south stump
#

and youre trying to store it in a db?

#

seems kinda stupid to me, just assign an ID as primary key so it works

upper goblet
#

bruh

#

it doesnt work

#

anyone

#

???

south stump
#

show the package you are trying to post

upper goblet
#

that error is from booking.service.add(request.session['basket']

#

@south stump

#

@whole crow

autumn lagoon
#

@upper goblet Im guessing this is a better place for django support

upper goblet
#

Ik

autumn lagoon
#

Ah there you are

#

I hate django, sorry man

upper goblet
#

It’s not working out for me

autumn lagoon
#

I can see that lol

south stump
#

okay but why would you want a randomly generated primary key

upper goblet
#

Like why Tf does it automatically generate Id field

#

When I didn’t say so

south stump
#

that means that it could select something that already exists, which breaks 3NF

upper goblet
autumn lagoon
#

I tried reaching out for help in the #python channel before it went to hell on freenode and nothing but trolls there. I switched to flask and things worked so much better

upper goblet
south stump
#

but its not a uuid its random, like i said. So it could pick the same combination

#

no but its a problem you could encounter in future

upper goblet
south stump
#

which leads back to my initial point, if you just use a standard integer it will get rid of both issues

upper goblet
#

Which is very annoying

#

Idk how to fix this shot

south stump
#

show the method for handling the post request @upper goblet

upper goblet
#

I did ?

south stump
#

where

upper goblet
#

Wdym show the method

upper goblet
south stump
#

oh okay my bad yea, have you tried breakpoints?

upper goblet
#

Breakpoints? What does that mean

south stump
#

its where you can pause code line by line, view variable states and continue/skip code

upper goblet
#

Yh I have tried that the issue is 100% in request.session[‘basket’] I jus don’t understand django

#

When I clearly stated that the field is going to be manytomany

south stump
#

should the service not automatically be added?

upper goblet
#

It should be

native tide
#

Hey, I'm new to creating login sessions. And I wanted to try to add it to my site which uses FastAPI

#

and I got to the point where I have a refresh and an access token, but idk how to go from there

olive tiger
#

is it OIDC?

native tide
#

no clue what that means

olive tiger
#

then it isn't 😉

native tide
olive tiger
#

take a look at oauth2 concept

#

it is simialr to what you are trying to achieve

native tide
#

well I got the part where I get the token

#

what I'm stuck on is getting the userinfo from it and creating a session so I dont need to add url params with the token in it

olive tiger
#

are you using jwt?

native tide
#

also no idea what that is

olive tiger
#

how are you trying to get the info from the token?

upper goblet
#

sex guys

#

sex]

olive tiger
#

how is the token generated?

native tide
#

thats what I'm asking, how do I get the info Hehe

native tide
# olive tiger how is the token generated?

fastapi-discord has a token, refresh_token = await discord.get_access_token(code) where it takes the code that is returned by the discord oauth url to create an access and refresh token

olive tiger
#

there are several ways - 1) use token to access some endpoint and get the info from there, 2) use jwt to store info inside and then get it from there, when you receive it

olive tiger
native tide
#

but

#

I know I can like keep a dict

#

but how do I know when to grab which token

olive tiger
#

you need to check the expiration time of the token and refresh it, when it expires

native tide
#

yeah but that doesnt answer my question yet teehee

olive tiger
#

which one?

native tide
olive tiger
#

every user should have its own stored in the db or in cache

#

and you update them accordingly

#

generally, there are modules made for such things, as far as I remember, such that you do not need to do it manually

haughty gazelle
#

may i know the solution

native tide
#

But for better security, you should also hash it

native tide
#

hey im new in this Community im enrolling into Diploma in computer science i wanna know what should i major in and can u all show a path to teach me to like free website to do pythan

weary spear
#

What's better for Flask/Blog app?
Having each class like Post, Pages etc and its functions in separate .py files or in one like (dashboard.py)?

viscid walrus
#

i have started learning react as a beginner...when i saw the documentation of react there its written learn by practical tutorial and other learn by main concepts..so which one should i prefer ?

restive furnace
#

You all know while Downloading Anime and watching online You see a lots of advertisement and hundreds of redirects adult pop up messages by website send to you Sad for user privacy . 😭

But i created a web scraping model that' help anime lovers to watch download anime without seeing ads and all shity things and no privacy issues ...

Website Link - https://asteroidfire.pythonanywhere.com/

Repository : https://gitlab.com/Aakash-Yadav/flask-anime-downloading-web-app

native tide
#

pog

dusk portal
red ice
#

Does anyone have a solution to fix my problem, git push -u origin main takes too long

inland oak
restive furnace
#

Code please

river shadow
#

I could not share that that’s the problem 😞

#

Found that

#

Wrong path

random oar
#

My website is receiving get requests for css file but why is it not responding?

random oar
# thorn igloo what do you mean?

It got fixed by itself, maybe its the server's problem, but the moment I visit my website its not loading because the server is not sending me the css

rotund perch
#

Hello, is it possible to do Authentication Token on another Backend API other than Django and send it to Django to count it as authorized?

weary spear
#

Hey, is it better to have functions of one category (for example related to posts) in separate files like: posts.py, pages.py etc or put everything in one file like functions.py?

golden bone
strong stirrup
#

hello

#

when i run the html file normally i get this

#

and when i run it in flask i get this

#

i need help

#

with this

#

like images wont load

#

and then the layout like the button is in wrong place

#

and text is unreadable

#

i have looked on google and found nothing

frosty abyss
#

looks like it doesn't find the css file or the newest version of it

#

guys I have a problem that I don't know what to put into google to find the answer

#

I want the customers on my website to sign up for a service, and when they sign up (submit a form) that means they signed the contract

#

which would be of course explained in detail in terms of service

#

but since I can do with the form data anything I want, which means I can fabricate any form easily

#

how do I prove that the user actually submitted it? That he consented to data processing and to terms of service?

#

using django if that makes any difference

swift wren
#

guys could i get some consultation? im planning to chose my db for my project. i have a flask backend and a js frontend. should i chose a js based db engine or use the flask backend for db. there are alot of databases for js and seeing how i have a js frontend, should i use js databases like graphql or other popular dbs. im also way more profecient in sql based dbs but i've heard no sql is faster. also would offsetting the db operations to the backend be more beneficial?

thorn igloo
thorn igloo
#

and you cannot really interact with a database directly through a frontend

swift wren
#

yeah nah i've learnt what graph"ql" is

thorn igloo
#

it's an alternative to the REST API structure

#

it's not a JavaScript specific thing

#

an api is really just a way to interact with a backend

#

the backend handles the interactions to the database

#

you still cannot directly interact with a database through frontend only

native tide
#

sorry, if this is the wrong channel to ask this. does anyone know of a discord server that's about p2p networking, ipfs, etc.?

strong stirrup
#

i know r/Cisco and r/networking, they may have a discord server

south urchin
#
        url(r'^swagger/$', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),

quick question. I'm working on Django project and trying to figure out this particular line

#

How would I actually access the swagger UI o.O?

tranquil isle
#

Hello i have a question

#

If there is somene free go prv plz

#

How I can inclue the h1 in the photo

#

Sometting like that

mossy rock
tranquil isle
#

It's normal that alt didn't work ?

#

@mossy rock

tranquil isle
#

It didn't work

compact shadow
#

Any drag and drop HTML generators out there? Kind of like PAGE for tkinter would be what I'm looking for.

inland oak
upper goblet
#

yoo

#

any actives

restive furnace
#

Ya

weary spear
#

Good Morning/Afternoon/Evening/Night!
I have an issue with GIT.
I've added one file __init__.py to .gitignore it after I've pushed the dummy config to GIT but if I'll do git add . __init__.py is still being added there.
How can I exclude it once for good?

daring isle
#

trying to make a react api call. i have a link pointing to the desired url...

#

but my console looks like its going elswhere and obv giving an error

#

i have a feeling its something to do with my axios baseUrl , but im unsure on how to properly manage it.
i cant change the baseurl in axios, whats the proper way of defining a new end point

#

its the base url so /api/ "another endpoint"/ "id"
what seems to be happening is the "another endpoint" is just being ignored

#

this is my axios.js file

native tide
#

Hello everyone, is it a way to create a rpg in a browser with python? I heard about pyjs

timber spindle
manic crane
#

Sam8 — Today at 1:54 PM
who has here implented jwt authentaction in their djano project ?

inland oak
autumn veldt
#

why my flask app dos not have files that i put the with (imgs js scripts....) in the dev tools sources ?

#

someone ?

valid void
#

Hello guys, I have a problem (that's why I'm here). I'm working on a django website hosted by DigitalOcean, and I bought a domain name through 1&1, and both are connected (I also have an email address with my domain name). But when I send email using python using the host smtp ionos, gmail is telling me that the email is unsecured and it could be spam. The support at ionos told me on DigitalOcean to add a SFP to my domain, but it didn't changed anything

#

Do you guys have an idea ?

proven hawk
valid void
#

Ok but I don't know why when I hover the profile picture with the red "?" I am notified about the email address "do-not-reply@domain.com" and the name is set to Undefined

proven hawk
valid void
#

This is my config on django settings

#

And I use EmailMessage from django.core.mail to send mail in views.py

proven hawk
# valid void This is my config on django settings
autumn veldt
#

what 304 code means ?

inland oak
#

or not

#

or it it is response to caching

#

that file was not modified and not needed being reloaded

#

oh right. 301 is redirect from http to https 😉

#

304 is probably caching then

manic frost
#

Basically, it says: "here's a link to a resource. but it didn't change since you last looked at it"

warped aurora
#

hiya

native tide
#

Hi

warped aurora
#

trying to understand this

@app.route("/ajaxfile",methods=["POST","GET"])
def ajaxfile():
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    if request.method == 'POST':
        userid = request.form['userid']
        print(userid)
        cur.execute("SELECT * FROM employee WHERE id = %s", [userid])
        employeelist = cur.fetchall() 
    return jsonify({'htmlresponse': render_template('response.html',employeelist=employeelist)})

$.ajax({
                        url: '/ajaxfile',
                        type: 'post',
                        data: {userid: userid},
                        success: function(data){ 
                            $('.modal-body').html(data); 
                            $('.modal-body').append(data.htmlresponse);
                            $('#empModal').modal('show'); 
                        }

data.htmlresponse...data here is the response from the flask view right? and it's appending the 'htmlresponse' attribute. What was the point of the line above > $('.modal-body').html(data);

native tide
#

That is if the ajax call was a success

#

From your python code you can return a success or error

warped aurora
#

oh sorry I meant the line $('.modal-body').html(data); not above it

#

also data: {userid: userid} this is passed to the flask view on post correct and is accessed through request.form right?

native tide
#

It just replaces some html on the page with another.
So you python will return some html, and when your JS request gets a successful response the piece of code $('.modal-body').html(data); will set that elements content to what HTML python returned you.

#

$('.modal-body') is a jquery class selector so it will get the element with that class.

warped aurora
#

Ahh, I get that it's just the word data is throwing me off. because data is set to {userid: userid} but then after the success it's accessing data.htmlresponse?

native tide
#

Also i think success was deprecated in one of the versions. Was replaced with done() or something like that.

#

But should still work, as all my code uses success

warped aurora
#

@native tide tried to do the thing and got this error "POST /process_status HTTP/1.1" 400 -

from clicking this button

<td><span class="edit_btn"><a data-bs-toggle="modal" data-bs-target="#optionModal" id="option_link" data-id="{{ vehicle.T_Number }}">Buttton</td>
 

$(document).ready(function(){
            });
                $('#option_link').click(function(){
                    var t_num = $(this).attr("data-id");
                    $.ajax({
                        url: '/process_status',
                        type: 'POST',
                        data: {T_Number: t_num},
                        success: function(data){ 
                            $('.modal-body-update').html(data);
                            $('.modal-body-update').append(data.htmlresponse);
                        }
                    });
                });

@app.route("/process_status", methods=("GET", "POST"), strict_slashes=False)
def process_status():
    if request.method == 'POST':
        T_Number = request.form['T_Number']
        print(T_Number)
        status = Status.query.filter_by(T_Number=T_Number).first()
        garage_form = status_form(obj=status)
    return jsonify({'htmlresponse': render_template('garage_response.html', garage_form=garage_form)}) ```
#

might be some crsf token thing actually

native tide
#

400 is when you send data invalid

#

csrf would generally be 419, but yes you should also send the csrf with the ajax.

#

This is how i do it normally:

        $("#example-form").submit(function(e){
            e.preventDefault();
            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });

            $.ajax({
                type : 'POST',
                url : '/some-url',
                data:{
                    foo: 'foo',
                    bar: 'bar',
                },
            }).done(function (data) {
                // on success
            }).fail(function () {
                // on error
            });
        });
warped aurora
strange charm
#

Hi everyone, When i'm send post request with raw data. I'm getting this error "detail": "JSON parse error - Expecting value: line 4 column 24 (char 95)"

#

But when i use HTML form its working

#

drf

#

raw data request { "Company_name": "Facebook", "Position": "Software", "Employment_type": Full-time, "Primary_Skills": VA/PT, "Skills_tag": "Nmap", "Location": "Worldwide", "available": true, "Min_salary": 20000, "max_salary": 100000, "Description": "This is a description.", "company_logo": null, "url": "https://www.facebook.com", "email": "test@facebook.com", "show_logo": true, "Highlight": false, "sticky_day": false, "sticky_week": false, "sticky_month": true }

lavish prismBOT
#

Hey @strange charm!

Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:

• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)

• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:

https://paste.pythondiscord.com

strange charm
#

this is html form data

#

please help

#

how to send data in raw format?

upper goblet
#

yo anyone know

#

how to add foreign key in html

#

??

#

so it gets the data from model

lavish prismBOT
#

@hasty stirrup Please don't try to ping @everyone or @here. Your message has been removed. If you believe this was a mistake, please let staff know!

glacial portal
#

Can code on the subdomain have access to the main domain's Session?

crude delta
#

Hey Memebers 👋

Anyone tried connecting LAMPP in Django in Ubuntu? ❤️

livid thunder
#

Can someone here help me to find and give me the API of an site in a dump file? Would that be possible? I can also hand out my user credentials if needed.

thorn igloo
upper goblet
#

Nvm

#

I got it

golden bone
dim plume
#

i get this error when i deploy my api in heroku

#

at=info code=H82 desc="Free app running time quota exhausted" method=GET path="/favicon.ico" host=covid19data-apii.herokuapp.com request_id=71862c4b-cf84-465e-ac39-bc7afb8b6d8e fwd="59.94.193.113" dyno= connect= service= status=503 bytes= protocol=https

#

how can i fix?

livid thunder
#

if needed

gritty cloak
#

can someone help

#

i wanna do this in python

tight trout
#

Hi, any idea how to redirect using headers in flask using flask_jwt_extended?

#

I am trying to redirect from login page to dashboard using jwt but I am unable to redirect where as I can return json but not as a web page .

dim plume
#

hello, Where can i deploy/host my fastapi server for free other then heroku cause i finished my free dyno.

dim plume
#

to host the api

olive tiger
olive tiger
#

I only use it for testing

#

they give you some domain, but not the one you want

dim plume
olive tiger
#

it is something like yourusername.pythonanywhere.com

dim plume
#

is it a sub domain?

#

oh

olive tiger
#

i think so

#

for real web project you need to pay

#

but it is not much - 15 euros per year for domain, 5 euros per month for the VPS

gritty cloak
dim plume
#

cause i have a vps

olive tiger
dim plume
#

not the subdomain

#

a full domain

olive tiger
#

you can try to find some discounts - sometimes they sell it for 1 euro for the first year

dim plume
#

i need for free

mystic wyvern
scenic dove
#

Hello

#

in HTML is there a difference between

<input type="submit" value="Save>

and

<button type="submit">Save</button>

when dealing with forms?
because i was moving along with this django book and it used <input> in forms but started using <button> when it came to the authentication forms (sign up login..)

#

that's weird cuz i didnt use any java in that project

#

wut

mystic wyvern
#

sorry i thought you want to know the difference between <input type="submit" > and <input type="button" >

scenic dove
#

ah

#

ok

#

how did u rap your code in a box like this

quick cargo
#

!codeblock

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.

scenic dove
#

thanks

mystic wyvern
white delta
#

In Django, how do i get grab the latest object by date and not date created?

untold star
white delta
white delta
untold star
rotund perch
#
    allBlogs = models.Blogs.objects.all()
    allAuthor = models.Author.objects.all()

    
    oneBlog = models.Blogs.objects.get(id=id)
    AuthorsAllBlogs = models.Author.objects.get(id=id).blogs.all()

    allBlogsserializers = serializers.Blogserializer(allBlogs,many=True)

    oneBlogserializers = serializers.Blogserializer(oneBlog,many=False)
    
    allAuthorserializer = serializers.Authorserializer(allAuthor,many=True)

  
    Blogsserializers = serializers.Blogserializer(AuthorsAllBlogs,many=True)

    
    data = {
      "allBlogsserializers":allBlogsserializers.data,
      
      "oneBlogserializers":oneBlogserializers.data,

      "oneBlog'sAuthor": oneBlogserializers.data["author_id"],

      "allAuthorserializer":allAuthorserializer.data,

      "Blogsserializers":Blogsserializers.data
    }
    return Response(data)

Any better apprpach?
its just for learning not for production....

torn heron
#

Hello

#

I got a domain in Freenom

#

and i was wandering how i can host my website to the domain

#

on my local machine

thorn igloo
#

possible but not recommended

torn heron
#

what do you mean

#

?

thorn igloo
torn heron
#

i have vps

white delta
torn heron
#

but i am not sure how to change local host to the domain name

#

so i am testing it out on my local machine

#

how can i do it?

warped aurora
#

for some reason when I append it appends twice? or rather it takes whatever was previously appended and appends it again

//this script gets the data-id from a button sends to the flask view and then appends the response to the modal body

$(document).ready(function() {
    $('#option_link').click(function(){
        var id = $(this).attr("data-id");
        $.ajax({
            data : {
                ID : id,
            },
            type : 'POST',
            url : '/process'
        })
        .done(function(data) {
                                $('.modal-body-update').append(data.htmlresponse);
            }
        });
        event.preventDefault();
    });
});

@app.route('/process', methods=['POST'])
def process():
    x = request.form['ID']
    return jsonify({'htmlresponse': render_template('replace.html', x=x)})

//this is the replace.html
<div class="modal-body-update">
    {{ x }}
</div>
thorn igloo
torn heron
#

How can i do it on my vps then?

white delta
thorn igloo
#

I'm not familiar with VPSs, you're probably gonna have to look up how to point your domain to your vps

torn heron
#

hrm

#

okay

#

thanks

mystic wyvern
untold star
untold star
olive tiger
torn heron
olive tiger
torn heron
#

what do you mean

#

i can host it on a vps

rotund perch
olive tiger
torn heron
olive tiger
torn heron
#

somehost.xyz

#

it's a service

olive tiger
#

if you want to automate the deployment, there are tools like jenkins, travisci etc., which can do this from your git repo

white delta
white delta
native tide
#

can someone give me yts whole site design

#

well if its not hard

mystic wyvern
torn heron
#

so i can't do it from vps?

olive tiger
#

which can help you deploy new versions, etc.

rotund perch
#

is it possible to do a custom login view using the built in obtain token just to edit the Response in django rest framework token authentication?

warped aurora
#

can't seem to figure out why im getting this error
"POST /process HTTP/1.1" 400 -

{% extends 'base.html' %}
{% block content %}
<a href ="" id="test_link" data-id="2">test</a>
<script type='text/javascript'>
  $(document).ready(function(){
      $('#test_link').click(function(){
          var id = $(this).attr("data-id");
          $.ajax({
              data : {
                  id : id
              },
              type : 'POST',
              url : '/process'
          })
          .done(function(data) {

              if (data.error) {
                  alert('I hate tomatoes.');
              }
              else {
                  alert('I love tomatoes.');
              }
          });
          event.preventDefault();
      });
  });
</script>
{% endblock %}
@app.route("/process", methods=("GET", "POST"), strict_slashes=False)
def process():
    if request.method == 'POST':
        print("pls work")
    return jsonify({'htmlresponse': 'lol'})
normal nova
#

any one intrested in partnership?? i am looking for app idea or opensource project to work on

olive tiger
warped aurora
olive tiger
warped aurora
olive tiger
warped aurora
olive tiger
#

you use it on this line if request.method == 'POST': , but where is it coming from?

warped aurora
#

@olive tiger $.ajax({ data : { id : id }, type : 'POST', url : '/process' })
that creates the post request and then sends it to the url for the route

olive tiger
#

I am talking about your python code

warped aurora
olive tiger
# warped aurora from flask import request

this is the module, which you import from flask - has nothing to do with that request. I already gave you the answer: request must be an argument of you process function

warped aurora
olive tiger
#

I think, it should be like this: def process(request):

quick juniper
#

So Flask uses an import for the request an not a param

quick juniper
#

Maybe you should return a response?

#

*another

warped aurora
olive tiger
warped aurora
quick juniper
upper goblet
#

Hey guys

rotund perch
#

Ive did a register view in this way:

def Register(request):
    serializer = serializers.UserSerializer(data=request.data)
    if serializer.is_valid():
      serializer.save()
      username = User.objects.get(username=serializer.data['username'])
      token = Token.objects.create(user=username)
    else:
      print(serializer.errors)
    data = {
      # 'user_id':serializer.data['id'],
      'username':serializer.data['username'],
      'Token':Token.objects.get(user=username).key,
    }
    return Response(data)

Is it a good approach ?

zealous oar
#

Hi there, If any Django developer could help me with this question, I would appreciate that!

It is important if you are using DRF to build your API

Link: https://stackoverflow.com/questions/70544938/cant-measure-the-performance-of-serializer-using-cprofile

zealous oar
manic crane
#

i keep getting
{
"detail": "Token not valid"
} when trying to do
jwt api authentication

frank shoal
#

And you're providing the header Authorization: Bearer <jwt token>?

#

and not just Authorization: <jwt token>

rotund perch
#

Does django pagination load only the set of the data tht is 10 object per page for example or it loads all data and just response with the first 10?

If it loads all data ,does that mean that Queryset slicing or limiting is better to load only a specific count of objects for performance purposes

warped aurora
#

@quick juniper @olive tiger changing type : 'POST' to 'GET' allowed the ajax call to go through, which is still a problem cause I can't send data to the route lol..progress tho

native tide
#

do someone have experience with hosting tensorflow dockerized project on heroku?

tawdry fog
#

flask help: python in create_app from .auth import auth ImportError: cannot import name 'auth' from 'templates.auth'

golden bone
tawdry fog
#
from flask import Blueprint

views = Blueprint('auth', __name__)
tawdry fog
#

omg

#

wrong name

#

thanks for help

radiant aurora
#

Hey guys, I'm working on a text editor website which will basically write with voice. (Speech to Text Functionality)
I'm not able to figure how can I update just the text editor(Text Area)part without loading the whole website again and again after a speech.

rotund perch
radiant aurora
#

any idea how can I do it in django?

rotund perch
#

I mean you can do a new front end project and send api

rotund perch
radiant aurora
rotund perch
strange charm
#

Hi, Can someone guide me with dj-rest-auth. I want to create api of login, logout, reset password and etc.

#

I tried but its asking for template

#
from django.urls import path, include
from rest_framework.authtoken import views
from dj_rest_auth.registration.views import VerifyEmailView, ConfirmEmailView

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api-auth/', include('rest_framework.urls')),
    path('api-token-auth/', views.obtain_auth_token),
    path('dj-rest-auth/', include('dj_rest_auth.urls')),
    path('dj-rest-auth/registration/account-confirm-email/<str:key>/',ConfirmEmailView.as_view()),
    path('dj-rest-auth/account-confirm-email/', VerifyEmailView.as_view(), name='account_email_verification_sent'),
    path('dj-rest-auth/registration/', include('dj_rest_auth.registration.urls')),
    path('api/', include('api.urls')),  
]```
native tide
#

What Is web development

#

?

inland oak
# native tide What Is web development

in general it means creating web sites.

Web development can be considered existing in two versions:

  1. Dumb version: Just use wordpress to create simple stuff in minimal amount of time but heavily limited in what you can do
  2. More complicated version: Any custom desires can be fulfilled with Frontend/Backend/Devops stuff, as exapmle online tools https://www.photopea.com/ or online games
    In general 2nd choice is assumed here as a web development

Frontend: stands for making visual part of the web site
Backend: stands for making server side part of applications and usually means to work with databases
DevOps: means working with infrastructure of the servers as a code and automatization of development processes

Technically also, web development architecture is heavily reusable to be reattached in not just web sites but in any web connected applications, like mobile apps or desktop apps.
So we can say that web development is not really limited to web sites.
It means just about any development that as a end result hosted in servers with at least some parts having public access.

Usually web development assumes to target Linux servers(Because they are efficient in resource consumption and having free licenses), but Windows Servers exist too.
Any Software as a Service platform that exists to simplify it, in the end is just intermediate link to the same thing.

So let's conclude:
in 98% of the cases web development means to develop applications to be running in Linux Servers, with public exposure
for access to them in the form of web sites, mobile apps or any other web connected device.

obtuse compass
#

I need a CTO for my startup who knows full stack web dev if anyone is interested ping me

rotund perch
#

DJANGO:
is it possible to do custom functions and call it from views and pass parameters to make the logic but outside the views file?
PURPOSE:
(To make views file more readable and reduce code duplication)

untold star
native tide
#

hi

#

help me

old stratus
#

yes?

native tide
#

i want my html code to run

#

and its running fine

#

but

#

i want to add some script too in it using python but idk how

dim rover
#

that's a pretty unusual thing to do actually

native tide
dim rover
#

but in theory you could add the brython javascript to your file

#

then you should be able to declaere a script block with text/python as the type

dim rover
native tide
#

can u help

#

?

#

@dim rover

inland oak
#

as it was said using python for client side in unusual, but nobody says strict no 😉

limpid mason
#

Hi! So, I have built my website using Jekyll. And I want to add clarity.ms analytics service to my website. I copied the code from clarity.ms site and after I paste the code in my project, save the file and run jekyll locally, the clarity code won't be there and the project is back to the previous state. Please help me to fix this and understand why this is happening ... thanks!

oak pecan
#

hello do somebody knows what is Post back page can u please explain?

inland oak
oak pecan
inland oak
#

we can only speculate its meaning

#

it can be

  1. body of POST request for example
  2. Or it can be page rendered in response to POST request
  3. or something else?
#

I just proposed the closest guess I have

oak pecan
inland oak
inland oak
# oak pecan thx i appreciate your help

In web development, a postback is an HTTP POST to the same page that the form is on. In other words, the contents of the form are POSTed back to the same URL as the form.Postbacks are commonly seen in edit forms, where the user introduces information in a form and hits "save" or "submit", causing a postback. The server then refreshes the same pa...

#

oh we have some similarily named definition

#

so according to this definition..

#

highly like your Post Back Page is
POST request (during HTML form for example) to exactly the same URL of the original page to receive rerendered changed page

#

main content is rendered to you during GET request

#

but when you click button, you perform POST request against the same url

oak pecan
#

everything is making a sense now thx for the info's @inland oak

native tide
#

eyo

#

need help with flask

#

😔

native tide
#

ok

#
from flask_socketio import emit, join_room
from random import randrange

from models.database_config import mongodb
from .. import socketio
from ..models.mogodb_utils import get_all_documents, create_new_room, get_roomdetails, delete_game_details

@socketio.on('createroom', namespace = 'boxit')
def createroom():
    previds = [document["_id"] for document in get_all_documents(mongodb["gamedata"])]
    newid = randrange(10**6, 10**7)
    while newid in previds:
        newid = randrange(10**6, 10**7)
    gamedetails = {
        "_id": newid,
        "playercount": 1,
    }
    try:
        create_new_room(mongodb["gamedata"], gamedetails)
        emit('roomcreated', {'roomid': newid}) 
    except:
        emit('roomecreationerror')
        
@socketio.on('findroom', namespace = 'boxit')
def findroom(payload):
    roomid = payload['roomid']
    room_details = get_roomdetails(roomid)
    if room_details['playercount'] == 1:
        room_details["playercount"] += 1
        delete_game_details(mongodb["gamedata"], room_details)
        emit('roomfound', {'roomid': roomid})
        emit('opponentjoined', {'roomid': roomid})
    else:
        emit('roomnotfounderror')
    
@socketio.on('joinroom', namespace = 'boxit')
def joinroom(payload):
    roomid = payload['roomid']
    join_room(roomid)
    
@socketio.on('killroom', namespace = 'boxit')
def killroom(payload):
    roomid = payload['roomid']
    room_details = get_roomdetails(roomid)
    if room_details["playercount"] == 1:
        delete_game_details(mongodb["gamedata"])
#

flask socket is not responding

#

no error in the terminal

#
const socket = io.connect(window.location.href + ':' + location.port + '/boxit');

socket.on("roomcreationerror", () => alert("Internal server error.\nTry later."))

socket.on("roomcreated", (roomid) => window.location.href = waitinglobbyurl + "?id:" + roomid)

socket.on("roomnotfounderror", () => alert("Room not found!\nEnter valid code."))

socket.on("roomfound", (roomid) => window.location.href = online + "?id:" + roomid)

const performOnLoad = () => {
    document.querySelector("#join-room").addEventListener("click", onJoinRoomClick);
    document.querySelector("#create-room").addEventListener("click", onCreateRoomClick);
}

const onJoinRoomClick = () => {
    var roomid = prompt("Enter room id");
    socket.emit('findroom', {"roomid": roomid});
}

const onCreateRoomClick = () => {
    socket.emit('createroom');
}```
#

js code

inland oak
native tide
#

no errors

inland oak
native tide
#

no errors in dev tools*

inland oak
native tide
#

oki wait

inland oak
#

Connection that was not made, could not be without errors

native tide
tiny scaffold
#

Hi, is there an interface for django testing, which you can include to urls.py to start tests from development server and not from comandline, so you can manage everything in browser?

inland oak
tiny scaffold
#

O.K. whats its name?

inland oak
#

It gives visual interface in left side bar + right at where the tests are in the code

#

the most comfortable feature of it to run them in debug mode

#

which enables breakpoints stuff for debugging

tiny scaffold
#

Oh cool THX and is there a module to do it from admin panel?

inland oak
#

There is interface that shows test results in Github/Gitlab and e.t.c. repositories

#

it is called CI/CD pipeline

#

automatically launches tests on every commit for example

#

and shows results in browser / if something goes wrong notifies by email

#

I am having it in Gitlab CI for example

tiny scaffold
#

Cool, I am thinking how to implement this in docker. I want to make a drf with js frontend, but I have to learn much about devops tools.

inland oak
#

docker is the way. docker is beginning of the devops ecosystem 😉

tiny scaffold
#

Xd. Thank you very much for your advice.

inland oak
inland oak
tiny scaffold
#

Xd, I use nuxt.

native tide
#

😔

#

plis help

manic frost
#

@native tide what do you need help with?

native tide
#

mentioned it above

#

please check it

steel tendon
inland oak
#

it is auto suggesting some choices interactively during its creation also

serene prawn
# inland oak

You could probably run your tests in parallel 😉

inland oak
inland oak
# serene prawn You could probably run your tests in parallel 😉
stages:
  - dev_build
  - dev_test
  - dev_push
  - staging
  - staging_test
  - prod_build_push

build-test:
  image: ${docker_image}
  stage: dev_build
  script:
    - docker login $CI_REGISTRY -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD
    - echo $CI_COMMIT_SHA > core/commit_version.txt
    - docker build -t $CONTAINER_TEST core -f core/docktest

build-bundle:
  image: ${docker_image}
  stage: dev_build
  script:
    - docker login $CI_REGISTRY -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD
    - docker build -t $CONTAINER_DEV --build-arg VUE_APP_BACKEND_URL=**redacted** --build-arg NODE_ENV=development core

lint:
  image: ${docker_image}
  stage: dev_test
  script:
    - docker login $CI_REGISTRY -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD
    - docker run $CONTAINER_TEST lint

unit-test:
  image: ${docker_image}
  stage: dev_push
  script:
    - docker login $CI_REGISTRY -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD
    - docker push $CONTAINER_DEV

trigger-downstream:
  stage: staging
  inherit:
    variables: false
  variables:
    EXTERNAL_TRIGGER: "true"
  trigger:
    project: **redacted**
    strategy: depend

integration-testing:
  image: ${docker_image}
  stage: staging_test
  script:
    - docker login $CI_REGISTRY -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD
    - docker run $CONTAINER_TEST test:unit

save-as-latest:
  image: ${docker_image}
  stage: prod_build_push
  script:
    - echo $CI_COMMIT_SHA > core/commit_version.txt
    - docker build -t $CONTAINER_FOR_PROD --build-arg VUE_APP_BACKEND_URL=**redacted** --build-arg NODE_ENV=production core
    - docker login $CI_REGISTRY -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD
    - docker push $CONTAINER_FOR_PROD
#

Those are tests with deployment to staging environment, running integration tests and then saving to docker registry

serene prawn
#

Publishing /Deploying a library/app I guess?

#

You can add global before_script to login into registry though

serene prawn
#

Also would make more sense to not run lint in a container I guess

inland oak
#

it gives me less code to write in CI

#

one container is reusable to run different stuff. it is already reused twice

serene prawn
#

I have multiple lint jobs (formatting, unit testing), it would be faster to run them in parallel in ci

inland oak
#

to run Lint and to Run integration testing

#

going to be reused even thrice, when I would run locale testing stuff

inland oak
#

I just don't have enough tests types to run in parallel yet

serene prawn
#

Yeah, I guess I have too many linters 🙂

#

I run isort, black, flake8, mypy, pytest and coverage iirc

serene prawn
#

Yep 🙂

inland oak
#

why to run pytest/coverage separately

#

I thought they run at the same time

serene prawn
#

I don't

inland oak
#

black / flake8 are same thing, aren't they

#

no idea what isort is

serene prawn
#

Not really, flake8 catches more things, like unused imports, black is just a formatter

inland oak
#

that's it.

serene prawn
#

Also don't use latest tag for deployment 🤔 if you're triggering your deployment using gitlab ci you won't be able to rollback it.

serene prawn
inland oak
#

I use same tag for staging env to simplify staging deployment in every commit

#

and I have different tags for prod env for rollback and additional purposes

#

I attach different tags in infrastructure repository, when it is time to make new prod deployment

spiral blaze
#

Please help, my flask app is super slow for some reason, it's loading a page in like 5-10 seconds

#

And theres literally nothing on it, just one html page

inland oak
#

run LightHouse if u wish

serene prawn
#

That we can run/read and see what can be the cause

spiral blaze
#

app = Flask(__name__)

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

if __name__ == "__main__":
    app.run()```
and a html page that has `<h1>hello world</h1>`
#

really has nothing on it, it happened randomly like 3 days ago

serene prawn
#

This shouldn't take 5 seconds

spiral blaze
#

i have 3 flask apps and they seem to all run slow

#

yea, no idea what is happening

#

its loading slower than youtube

quick cargo
#

2 things

  1. How is this being ran
  2. how are you loading the page? via localhost or 127.0.0.1 are both slow?
spiral blaze
#

yep, via http://127.0.0.1:5000/

#

im loading this through cmd, it this is what youre asking

#

my cpu usage is 16%, so i don't think its a problem there

quick cargo
#

what does you browser say in terms of loading time distribution

native tide
#

hello

quick cargo
#

on the network tab if you select the main endpoint it should break down what took what time

quick cargo
spiral blaze
#

wait im sorry, where is this? chrome?

quick cargo
#

Im on firefox

#

chrome will probably have it as well

spiral blaze
#

doesn't look that bad.. in fact it looks normal, i think

#

16 seconds... jesus

quick cargo
#

apparently its not flask then

serene prawn
#

You said you only have an h1 tag in your HTML 😅

quick cargo
#

also this

#

well put simply, we can awnser your question

#

bootstrap and Jquery loading is why its slow

spiral blaze
#

oh yea i installed bootstrap too, just the lines that install it

quick cargo
#

flask is responding in 7ms

serene prawn
#

Try loading bootstrap from their cdn

spiral blaze
#

this is the html page

#

ah alright

quick cargo
#

yeah so, you're loading a load of JS that's forcing the browser to wait on it before it can fully render

#

are you defering those scripts?

serene prawn
#

It shouldn't take that long to load some js

spiral blaze
#

my other extend page just has ```{% extends "layout.html" %}
{% block content %}
<h1>Hello World</h1>
{% endblock content %}

quick cargo
#

try add defer to each script tag

#

although the loading times from the CDNs are still horrible

#

and are an issue in themselves

native tide
serene prawn
#

You could actually try to just load a file from that cdn, is that link in official bootstrap docs?

spiral blaze
#

wait im quite confused right now, i copied the bootstrap code from another project that i was following with a youtube video, now i used the one from the bootstrap website,

#

now its like running normally, but that really doesn't make sense, why is the other one running so slow all of a sudden?

quick cargo
#

what did you change?

spiral blaze
#

i just took the code from the website

quick cargo
spiral blaze
#

wait what

#

???

serene prawn
#

Some questions don't have answers 🙂

spiral blaze
#

nevermind, now its running slow again

#

ok what is going on exactly

#

i guess it is an improvement of 2 seconds

quick cargo
#

CDN moment

#

ig their CDNs are dying

#

does it actually stop the page from loading content then?

spiral blaze
#

I havent added any bootstrap yet, just a <h1> tag, yes its loading the <h1> tag

#

let me add a button

#

its not loading bootstrap

#

its just... well a button, not a bootstrap button, a button

native tide
#

did u add

#

{%load static%}

quick cargo
# spiral blaze

yeah it wont untill it actually gets the JS for it and css

#

which appears, bootstrap cdn is dying

native tide
#

try using 4.5 maybe

spiral blaze
#

should i just download it?

#

seems easier

native tide
#
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
spiral blaze
#

it actually just fails

serene prawn
#

Yep, that would help 🙂

native tide
#

🙏

inland oak
warped aurora
#

Still triying to figure out why my Ajax calls only work when type : 'GET' lol

<head>
<!-- AJAX -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<a href ="" id="test_link" data-id="2">test</a>
<script type='text/javascript'>
  $(document).ready(function(){
      $('#test_link').click(function(){
          var id = $(this).attr("data-id");
          $.ajax({
              data : {
                  id : id
              },
              type : 'POST',
              url : '/process'
          })
          .done(function(data) {
              if (data.error) {
                  alert('I hate tomatoes.');
              }
              else {
                  alert('I love tomatoes.');
              }
          });
          event.preventDefault();
      });
  });
</script>
</body>
dim rover
inland oak
hollow fiber
#

Man, fastapi is amazing

scarlet rapids
languid beacon
#

I installed tailwind css but the style did not come up any ideas?

inland oak
#

or just actually accessing it with url

#

your web site url / path to tailwind css

#

to find if it is accessable at all

limber root
#

Do i need to know JavaScript for flask

warped aurora
#

no

limber root
#

Flask or django

rare lagoon
#

Hey guys, I wanted to start with web dev in this year, I know like the basics in html, however I don't understand at all how or when to use divs, I need to learn css and some Js and I've heard of something called boostrap for html and react for js? Any path for getting started and what projects I can do to start practicing?

terse vapor
#

how can i use flask to filter sqlalchemy object by month?

golden bone
# limber root Flask or django

If you have to ask, you should probably start with Flask. Django is more powerful but more complex. It will take you less time to finish your first project if you start with Flask

golden bone
golden bone
# rare lagoon Hey guys, I wanted to start with web dev in this year, I know like the basics in...

If your primary interest is in frontend, bootstrap does sound like a good next step. There's not shortage of free materials https://medium.com/javarevisited/7-free-courses-to-learn-bootstrap-for-web-designers-and-developers-5135215648f1

Medium

Hello guys, you may know that Bootstrap is one of the most popular front-end libraries which provides a customizable template of HTML, CSS…

warped aurora
#

No matter what I do I can't seem to get the csrf token to work with my AJAX request...help 🥲

steady cargo
#

should I know grid/flex before learning bootstrap?

#

I'm just curious as to what knowledge I will need to have beforehand

fading gale
#

Any tips for learning flask and sql alchemy? I got a new job that uses flask for their backend so I gotta learn it

native tide
#

Want help from you people

native tide
#

I want to start my web development course so plzz suggest me how can I start , plzz help me with the resources for web development 🙏🏻

native tide
#

Eivl plz help me

native tide
#

Hi dark wind I also want to learn web development plz help me

daring gust
#

@reef cave We do not permit job postings in this server. Please review our rules.

valid void
#

Hello everyone ! First, I wish you all a happy new year. However, I need your help for javascript in django(v4.0) forms. I'd like, in a separate file, use an onchange event on a specific field of a form. Can you help me ?

#

I found this :
reciept=forms.ChoiceField(reciept_types, widget = forms.Select(attrs = {'onchange' : "myFunction();"}))
but it looks like the js need to be in the same html file as the form

#

But I need the javascript to be in a separate file

thorn igloo
#

js file that is

valid void
#

Oh so I import js separate file into html file and define the function in attrs field form

#

So it'll search into the js file imported in the html

thorn igloo
native tide
native tide
native tide
#

how to write output

native tide
golden bone
native tide
#

hello everyone

#

i am new in this field

#

and i alsoo want to learn web development so plzz help me

thorn igloo
native tide
#

help me like fronmm where should i start or what are the things that should i need for web development

terse vapor
#

I got a OperationError for the code

len(db.session.query(Detail).filter(func.date(Detail.Date_of_diagnosis) == date.today()).all())

with the error FROM detail WHERE date(detail."Date_of_diagnosis") = ?] [parameters: ('2022-01-02',)]
how can i fix it?

terse vapor
#
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such column: detail.describtion
[SQL: SELECT detail.id AS detail_id, detail.subid AS detail_subid, detail."Symptom" AS "detail_Symptom", detail."Check_result" AS "detail_Check_result", detail."Preliminary_treatment_plan" AS "detail_Preliminary_treatment_plan", detail.describtion AS detail_describtion, detail.cost1 AS detail_cost1, detail.cost2 AS detail_cost2, detail.cost3 AS detail_cost3, detail.tag AS detail_tag, detail."Date_of_diagnosis" AS "detail_Date_of_diagnosis", detail.user_id AS detail_user_id, detail.patient_id AS detail_patient_id
FROM detail
WHERE date(detail."Date_of_diagnosis") = ?]
[parameters: ('2022-01-02',)]
(Background on this error at: http://sqlalche.me/e/13/e3q8)
#

please dont mind the bad variable name

manic frost
#

You have a typo (describtion)

terse vapor
#

oh fr

#

lemme check

manic frost
#

(sqlite3.OperationalError) no such column: detail.describtion

terse vapor
#

ohh

#

i forgot to update the new column into the db

upper goblet
#

@whole crow

#

@whole crow

limber root
#

what a goo ide for html css and js

upper goblet
#

vs code

whole crow
upper goblet
#

@whole crow

#

242

whole crow
#

it looks like you never saved the date in the session

upper goblet
#

how do i do that

whole crow
#

did you ever post a valid form?

upper goblet
#

yh i did

#

basically so what happens i choose the date and time

#

then continue next

pine maple
#

Hey! I am trying to create a flask request that is quite intensive in the sense that it makes some DB calls some other API calls and does some compute. So I want to do parllel processing here. How can I go about it?

upper goblet
#

which leads to the payment pae

#

page

#

and this is wat shows on the payment page

#

is kinda frustrating now the request works in the class

#

but outside of class it shows error

#

actually ur right for some reason it is not getting saved

#

@whole crow something wrong my fucking code why is not redirecting to payment

#

but customer/booking

thorn igloo
bold finch
#

Why I cant render login.html even tho it is in the same folder?

#

Dont ask why I use Kali with root account. Linux deploy has several problems with setuid so cant use regular user.

#

What I tried:
Write ./login.html and full path of HTML.
Result:
Same thing. Same error.

inland oak
bold finch
#

render_templete()?

native tide
#

@thorn igloo ok

pine maple
#

I want to do parallel processing in a flask request. How can I go about it?

frank shoal
#

do you want to wait for the processing to finish before returning a response?

manic frost
#

I am a bit confused about Vuex, Redux and similar things. Aren't they just big global variables that we're trying to avoid in properly structured applications?

#

It seems to me that they have the same issues: anyone can change anything at any time. And this become increasingly painful with concurrency

inland oak
#

Which makes control logic in one place

#

DRY and much less tangled

inland oak
manic frost
inland oak
#

Setters/getters make a difference though. A single functions to change them and to get, it is enforced usually

manic frost
#

still, you can call these getters and setters from anywhere

inland oak
#

Makes life easier

manic frost
#

I feel like there isn't a way to not write spaghetti code on the frontend... I don't know what to do

inland oak
#

I heard react scales better

#

Perhaps it is solved there

manic frost
#

React has Redux, which seems to be the same idea?

inland oak
#

Yes

#

I don't know why react scales better, that is just collected rumour

#

I tried only vue

manic frost
#

I think I'll try to avoid using vuex as long as I can

inland oak
#

Going to learn some stuff to improve my Frontend anyway probably

#

Because there is no alternative

manic frost
#

I tried PureScript, but that seems overkill

inland oak
#

I will use only production ready stuff

#

That allows me using
Only React, Vue, Angular
And as a stretch... Some Frameworks based on those three Frameworks

JavaScript and Typescript only

manic frost
#

Is Svelte not production-ready? Why?

#

And what about Elm/PureScript?

upper goblet
#

Hey guys

#

You okay?

native tide
#

ask away

#

your question

#

roy

vital crest
#

hey ppl i've a trouble...

can i make an API using flask that when i do a get request then i get a json and download a file at the same time?

civic talon
vital crest
#

i got it... it's what im doing.

languid beacon
#

I struggle with uploading my react projects on git hub?

#

Any good tutorials recommended?

upper goblet
hollow scaffold
#

How can I configure django to allow /media/ within the staic dir? I know full well this isn't standard practice, however I'm rebuilding a large application with a JS frontend and am bundling it in django's static dir so upon collectstatic, it deploys to ./public_html/. Outside of dev/debug, django only renders /admin/ and /api/, everything else is static.

#

The only other thing I can think of is to configure setup.py to deploy the frontend but I'm not sure how to accomplish that outside of venv/lib

gleaming tiger
#

I have this python snippet. and the log output is not what i expected at all... interface is a peewee.Model and g is just flask.g. g.user is a model and g.user.interfaces returns a peewee.ModelSelect object. it iterates over interfaces acting like list[Interface] models.

# Save a has a priority bug that needs to be fixed
def save(interface: db.Interface) -> int:
    state = InterfaceState(interface)
    if state.is_empty:
        return 0
    if state.is_single:
        return state.set_interface()
    for index, item in enumerate(g.user.interfaces):
        if item == interface:
            item.active = True
        else:
            item.active = False
    with db.database.atomic():
        saved = db.Interface.bulk_update(
            g.user.interfaces, fields=['active'], batch_size=50)
    return saved

The result from the log is

[save] [interface] [arg] <Model: Interface> main False
[save] [interface] [iter] [0] <Model: Interface> main False
[save] [before] [equal] True [active] False
[save] [after] [equal] True [active] True
[save] [interface] [iter] [1] <Model: Interface> sandbox False
[save] [before] [equal] False [active] False
[save] [after] [equal] False [active] False
[save] [saved] 2

What's weird about this is that the results show that item is selected and updated and saved with the bulk update, but when i query the database, its not updated

>>> for i in user.interfaces:
...     print(i.name, i.active)
... 
main False
sandbox False
>>> 

I thought at first it was my logic, but i can only trace this issue to the Model.bulk_update method provided by peewee.

drowsy rune
#

Hey everyone, I'm playing with JWT and FastAPI - went smooth enough for the swagger Interface, got a token and can "execute" protected routes. Now I'm trying to implement HTML templates and create users with a protected route. Create, login no problem but I stored the JWT in a cookie and can't seem to pass it back to the fast API page to authorize correctly. Question, how should I be storing it in order for fastAPI to recognize it and decode it properly?

inland oak
# manic frost And what about Elm/PureScript?

No. Svelte can be used only for pet/home projects as maximum
Svelte has a hype to try
But it is taking super low market share (small fraction, which is less than 0.1% for sure)

The biggest drawback.. the size of community and passed years.
Svelte has really small ecosystem of libraries (or their lack of)
If u take svelte, then u can consider only on standard package, everything else u a going to reinvent.
Hell even router is not stable.

Things like Vue have. Everything. Router, state management, I18n tools, and many others. Ready solution for any common problem.
And just stability. Ensures that components will work without surprises.

When I tried svelte, I was able to break it in five minutes and due to compiler not really catching errors efficiently, I did not have even errors/logtrace to find what was wrong

As for elm, pure script....
In production ready stuff only typescript suggested as augmentation.
And according to statistics it is the most used static typing tool
And official docs to Frameworks usually mention only it

crude stirrup
#

what is bootstrap for?

compact forge
#

I have made a complete static website using tailwind(v3.0) and now i have to make this website dynamic using django. How can i do that with no mistakes , since there are many files like config and others and I don't know where to put these and all .
I have made a dynamic website with simple static website that uses pure css but not with any css framework. Can anyone help

bold finch
#

I want to make a web login system using flask. Let's guess that I made 2 input boxes for username and password. How can I "connect" them to my code?
I had experience with PyQt and it was something like get_text() or similar (long time no use so forgot....) but what about Flask?

cobalt condor
#

I don't know if this should be here, but I'm trying to open a websocket connect to a url and then print something. Here is my code:

def on_message(ws, message):
    print('Hello, World!')

ws = websocket.WebSocketApp('wss://some-url, on_message=on_message)
ws.run_forever()

print('Hello, World')

But it doesn't execute the print statement. Can someone please help?

rigid laurel
inland oak
rigid laurel
rigid laurel
inland oak
lilac solar
#

It's more a case of pick the right tool/framework for the right case. Svelte's origins is from data journalism, so it's perspective is going to be different when it comes to the likes of React coming from Facebook.

While it is small, it has an active community and is maintained so can be used in production

manic frost
rotund perch
#
@api_view(['POST'])
def Logout(request):
    request.user.auth_token.delete()
    data = {
      'status':'Success!'
    }
    return Response(data)

Whats better, to make @api_view(['METHOD']) a post or a delete or a get? or it doesnt matter

manic frost
#

I tried PureScript a while ago. And while the language is great, the ecosystem is very young. I'm hoping it gets better over the years

inland oak
manic frost
#

Do people actually use vue-cli and create-react-app in production? 🤔

#

my company doesn't

inland oak
#

Vue Cli was recently updated to 5th version to be up to date with stuff

manic frost
#

there is no doubt to it

inland oak
#

Considering its popularity and quite often demand in jobs, higher chance to have people both knowing TypeScript than other js flavors

#

it should make easier to have several people working in same project / or project transferability

native tide
#

hi i m getting this error with webhook request : TypeError: 'NoneType' object is not subscriptable

deft apex
#

Hey. I'm learning HTML, css and Java for freelance web development. But there's this question that always come to my mind. Should I learn these or learn a bit of wordpress? I feel like a web developer and a wordpress designers are treated the same way. Most of the free lancers are wordpress designers on sites such as fiverr. Wordpress doesn't require any coding knowledge whatsoever. Ofc I know learning web development is worth way more but I wanted to know if it's any good in freelancing,

thick sinew
#

Does someone know how to set lookup_field in DRF? I tried specifying my custom pk in a viewset and serializer's Meta class but it still generates swagger docs with the wrong field for get/put/delete by id endpoints

golden bone
deft apex
native tide
#

what

languid gulch
#

DJANGO vs FLASK??👀

languid gulch
golden bone
# languid gulch DJANGO vs FLASK??👀

For what? Generally if you need to ask, you should probably start with Flask as it's less complicated to pick up and you can always learn Django later if you need something more powerful

restive furnace
#

Django is quite complex when it comes to file handling

echo cobalt
#

i am trying to blur only the background of div with some child element(h1,p). But couldnt do it with pure css . help me plz

restive furnace
#

Flask give you great experience working with back-end part and after that you can learn Django easily

terse vapor
#

how can flask admin filter by date?

echo cobalt
restive furnace
echo cobalt
restive furnace
echo cobalt
#

anyone who can help me with pure css?

terse vapor
valid dawn
#

Does anyone know how to actually solve this issue? Whenever I run the system, it will pops out 404 error

golden bone
dusk portal
#

i;m trying to make course system like udemy or some another platform
so in vid 1st field is foriegn key to get/select the course to get the video is of which course

#

then i tried to do stuff like django admin by radio buttons at the form

#
    vid_of=models.ForeignKey(Course,on_delete=models.CASCADE)
upper goblet
#

Anyone know how I can print datefield in django it always prints None

dusk portal
# dusk portal i;m trying to make course system like udemy or some another platform so in vid ...
@login_required
def video_upload(request):
    if request.method == 'POST':
        vid_of=request.POST.get('vid_of')
        vid_title=request.POST.get('vid_title')
        vid_desc=request.POST.get('vid_desc')
        vid_video=request.FILES['vid_video']
        vid_author=request.user
        if Video.objects.filter(vid_title=vid_title).exists():
            messages.error(request,'Title taken!')
            return render(request,'index/video-upload.html')
        elif len(vid_title)>55:
            messages.error(request,'Title too long!')
            return render(request,'index/video-upload.html')
        print(vid_of,vid_title,vid_desc,vid_author,vid_video)
        entryy=Video(vid_of=vid_of,vid_title=vid_title,vid_desc=vid_desc,vid_video=vid_video,vid_author=vid_author)
        entryy.save()
        messages.success(request,'VID ADDED SUCCESSFULLY')
        return HttpResponseRedirect(reverse('home:index'))
    return render(request,'index/video-upload.html')```
#

in print statement it's printing

upper goblet
#

Anyone know how I can print datefield in django it always prints None

dusk portal
#

i used same way as django admin panel

#

but it's giving error

golden bone
# valid dawn

So no, you do not have a route for '/' if that's everything.

valid dawn
#

do you mean by this?

golden bone
spiral blaze
#

Does anyone know how to move the world Flask to the right a little? I'm using bootstrap and i tried ml-2 and it isn't working.

frank shoal
#

tried wrapping the whole page in <div class="container">?

spiral blaze
#

tried it, it kind of cuts the blue part a little

gaunt heath
#

so i have a question, is it possible to make a very simple social forum with only html , no css/javascript?

scarlet rapids
#

Hi, is there any good and simple codebase to add Photo gallery (in which each photo can have some description when opened) compatible with Jekyll for GitHub pages?

valid dawn
#

because when "/" gets called, it checks the session cookie

#

but that doesn't exist until you login

#

so need to add an exception for that

golden bone
gaunt heath
#

i was thinking to do something like a study forum

#

would i be able to do that with only html? with just some simple interface and mainly using text and maybe images

golden bone
gaunt heath
#

grumpchib i have to do it in lamp, with apache, mariadb, php and html

stone kite
#

Is there a good tutorial how to host a django app on local linux server and update it etc. ? I am learning django but got depressed because I can not find a way to Host an App on my rpi.

keen inlet
#

hi guys
someone knows why can't I catch the exception and print it to my front end ?

#

I use Django server

frank shoal
#

print() prints to the backend. You need to include it in the response object to send it to the frontend.

#

if django has the concept of flash like flask does, you can use that and use it in your template later.

languid beacon
#

I have a question regarding to react js frameworks, should I learn Remix or Next js

drowsy rune
# stone kite Is there a good tutorial how to host a django app on local linux server and upda...

Are you running a webserver on that linux server? I think any tutorial on deploying to a linux server would work. This is a little older but generally has the same principals. https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-apache-and-mod_wsgi-on-debian-8

DigitalOcean

Django is a powerful web framework that can help you get your Python application or website off the ground quickly. Django includes a simplified development server for testing your code locally, but for anything even slightly production related, a mor

golden bone
upper goblet
#

Hey guys we are all so worked up with django, I just wanna let you know. Whatever it is you are trying to do never give up and always take break in between

drowsy rune
drowsy rune
valid void
#

Hello everyone, I need help for something I don't understand. I'm creating a website for shopping, so every product as a quantity stored in the database. I would like, when I create the form, to populate my select list with the number of product left in the database. For example, I get in the views the quantity for the product (for example : 20 products left), and when I create the form I need to populate my select with numbers between 1 and 20. Do you have a solution ? Thanks 😄

drowsy rune
#

@valid void What framework are you using and what have you tried? Maybe share your codebase.

valid void
#

woops, sorry it's for django

#

I've tried absolutely nothing as I can't find any answer

#

I know how to populate with specific values using forms.ChoiceField(choices=variable)

#

But now I need this variable to be populate by integers between 1 and a number I have from my views

drowsy rune
#

hmmm, i'd have to see the code to be able to help but I'm sure it's been handled as this is a very old problem. Probably just need to do a count

valid void
#

views.py

def productinfo(request, idp):
    p = Product.objects.gets.get(pk=idp)
    form = AddForm() #I need to populate the field quantity in this form
    #p.quantity -> is the variable I need to populate
    template = loader.get_template('project/productinfo.html')
    context = {
        'product': p,
        'form': form,
    }
    HttpResponse(template.render(context, request))
native tide
#

ok what is your issue

valid void
#

forms.py

class AddForm(forms.Form):
    quantity=forms.ChoiceField(choices=#range between 1 and a variable, required=True)
#

I need to populate quantity with integers between 1 and the variable p.quantity that I got into my views

native tide
#

can you share your model just so I have more of an idea what you're talking about

valid void
#

(quantite = quantity)

#

(Produit = Product)

#

In my views.py, I got p.quantity which is an integer that shows the number of products left, and I need to store all the integers between 1 and p.quantity in my field "quantity"

native tide
#

this link should help

valid void
#

I found a solution 🙂

#

In my form :

#

And in my view I'm calling my form with qt as an argument

upper goblet
#

anyone

native tide
#

or wrong in your template

upper goblet
#

and plus the paypal buttons disappears wtf

radiant aurora
#

Hey Guys, I'm facing a issue with my Register Page in Django. While creating a new user it is giving me an error:

permission denied for table auth_user

But the thing is registration is working fine on my localhost but not working on heroku server.

Also, the permission is denied for creating a new user.

User.objects.create_user(username=username, email=email, password=password) 
upper goblet
#

@native tide

native tide
# upper goblet

if you're referring to it by name in template, you need complete_order not completeOrder

radiant aurora
upper goblet
#

wat

upper goblet
#

@native tide

native tide
# upper goblet I did

sorry, missed the second attachment, not sure how that works with the JS, I never touch it, but you aren't in a template there, maybe that's the issue. Can you use python templating directly in JS?

upper goblet
#

most of the tutorials

#

says this

sacred crane
#

I was trying to use celery in my flask app which does prediction on two strings. but when I run the celery -A tasks worker --loglevel=INFO command I am getting Error: Invalid value for '-A' / '--app': Unable to load celery application. The module tasks were not found. I am following this documentation. I am attaching the pic for your reference below.

open cape
#

When I push data to HTML, I get table syntax like paragraph instead of table

rich tusk
#

Hey so if I am trying to do sprite sheets for my icons, would it still be valid to use a SVG file at that point or would I be better off using a PNG if its a sprite sheet?

jovial cloud
hollow verge
#

Hey guys I have flask app with postgres and I want to deploy it to google cloud ?

#

what should I use google app engine or virtual machine?

cobalt valve
#

hello guys

#

anybody that can maybe help with some django pattern not working correctly..

valid dawn
#

anyone know how i can solve this problem? It happened suddenly and before this, there was no these errors

jovial cloud
jovial cloud
# valid dawn anyone know how i can solve this problem? It happened suddenly and before this, ...

If you're talking about yhe warnings, those are fine. Also, if you're referring to the 304 codes, those are also fine. The 304 http code means that there's no need for the css & js to be transmitted again because they have already been cached by the browser
https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/304

The HTTP 304 Not Modified client redirection response
code indicates that there is no need to retransmit the requested resources. It is an
implicit redirection to a cached resource. This happens when the request method is
safe, like a GET or a HEAD request,
or when the request is conditional and uses a If-None-Match or a
If-Modified-Si...

outer radish
#

Hey guys i got a question, recently i discovered Tailwind for real and tried using it and it really good, so my question is as someone who can produce something with Vanilla CSS 100% or with Tailwind which one should i go with, in terms of client satisfaction

strange walrus
#

Hey everyone, I have a question and I would love if I could get some support on this:

I am developing my first ML API which I want to host in AWS Lambda. I have figured everything out but I am missing something important: How will logging work?

Currently I am using a filehandler and locally, logs are written in a log file. How will that work with aws lambda?

rigid laurel
#

you should just log to stdout rather than a file, then you can see the logs in CloudWatch

civic dragon
#

Hi, how is it possible to print a response in a flask app to the terminal (i.e. to see payload for a route to help with debugging)?

native tide
#

@civic dragon have you tried google

#

the very first answer on there

#

clearly has the same situation as you are in

#

if you are unsure about the actual information given there, we would be happy to help you understand it

#

its also useful to be able to find information on your own, helping you learn to do it is actually the most helpful thing we could do for you arguably

onyx pivot
#

I am having a problem with django

#

It says module <app>. Urls not found

strange walrus
civic dragon
# native tide clearly has the same situation as you are in

@native tide I agree with you. I actually went through a few search results and wasn't successful. It's primarily b/c I'm new to python/flask (I usually deal with JS/Node) and the app I'm working with isn't a simple hello world app (possible I might be trying to do things in the wrong place/file), so I'm getting confused and decided to ask here. You're right though...I need to get better at finding helpful google results and figuring out how to apply the info.

hasty folio
#

Is django-tailwind the best way to get up and running with Tailwind v3.0 in Django? The JIT features and extended flexibility look really amazing

uneven plume
native tide
#

hello web community, how to add security in simple way to my flask app? Thanks a lot

junior wraith
uneven plume
#

What does that mean?

junior wraith
#

@uneven plume you are having {"request": request} and request is <starlette.requests.Request...> which you can't use in json

uneven plume
#

Hmm

#

Then there is smh I have to verify

#

Thx!

junior wraith
#

and what fastapi does - it returns json

#

so it tries to covert your dict to json and it just can't

uneven plume
junior wraith
uneven plume
#

The token

junior wraith
#

for exmaple like this:

from pydantic import parse_obj_as, BaseModel
from starlette.requests import Request
from starlette.responses import JSONResponse


class ResponseModel(BaseModel):
    token: str


@app.get("/show_token")
async def show_token(
        request: Request,
        token: str = None
):  # noqa: B008
    """Show the refresh token from the URL path to the user."""
    response = dict()

    if token:
        response["token"] = token
        return parse_obj_as(ResponseModel, response)
    else:
        return JSONResponse(
            status_code=404,
            content={"message": "No token found"}
            )
uneven plume
#

Hm

#

I'll try it in a while

junior wraith
#

👍

uneven plume
#

pydantic is 3rd party lib?

#
web_1       | INFO:     172.18.0.1:32816 - "GET /callback?code=RdkSato3tIWbr6QyYtNYaiE2op9p2O HTTP/1.1" 303 See Other
web_1       | INFO:     172.18.0.1:32816 - "GET /show_token HTTP/1.1" 404 Not Found