#web-development

2 messages · Page 170 of 1

ionic raft
#
# Python code inside function...
    if form.validate_on_submit():

        # If user's email already exists
        if User.query.filter_by(email=email).first():
            # Send flash message
            flash("You've already signed up with that email, log in instead!")
            return redirect(url_for('sign_in'))```
#

here's the html jinja I used to receive

#
{% with messages = get_flashed_messages() %}
    {% if messages %}
        {% for message in messages %}
            {{ message }}
        {% endfor %}
    {% endif %}
{% endwith %}```
#

I hope that helps. I've only a couple of months with Flask so not an expert. But I did get those flashes working for me in Flask

noble wing
#

Okey, I understand the code here and in the documentation but I wonder how get_flashed_messages() can be read?

ionic raft
#

I didn't need any include statement at the top of the html file. So maybe it's a part of Jinja2?

#

The reading is happening in the for loop....give me a sec...

#

I'm also passing in an a form object within the return render_template()

noble wing
ionic raft
#

So maybe it counts flashed messages as a part of the Form object? Pure guess though

ionic raft
#

Definitely a question you could research. I bet Stack Overflow will have someone explaining that with a related question

noble wing
ionic raft
#

Glad to help. I've had plenty of help here. 🙂

cold latch
#

You're right @languid raptor what do you recommend?

#

Oops sorry I didn't know this rule existed before now

languid raptor
#

I wish I had an answer for you. I don’t make commercial products or do consulting. For me if my Django project does what I intend, That’s satisfactory.

cold latch
languid raptor
#

I’m certainly not pushing any rules on you. Just FYI.

cold latch
#

Thanks for the review too

ember eagle
#

oh crap, i'm not sure if i should have posted this in a #help-chili channel or not... but mine's related to web dev

#

do i post it here instead and close out chili?

ionic raft
#

Can anyone recommend a great book for really learning Django? I need to delve deep into this framework. Tutorials are nice an all...but methinks this is going to warrant some deep learning.

cold latch
ionic raft
opal canyon
#

Im using matpltlib on my dev enviroment, but when I try to push to heroku this error comes up.... 😦 any ideas.

ember eagle
#

ok... so i'm still battling this silly thing and the more i'm doing this the more i realize maybe i have the entire way i'm doing it wrong...

i'm creating a customer and ticket tracking system (that i'm planning on giving away, at least for a little while) as a learning project, but i'm stuck....

i can't seem to fill in the customer ID (i'll figure out note type after that, hopefully)...

models.py

class NoteType(models.Model):
    name = models.CharField(max_length=40)
    color = models.CharField(max_length=7)
    icon = models.CharField(max_length=50)


class Note(models.Model):
    customer = models.ForeignKey(Customer, on_delete=models.DO_NOTHING) # <---  HOW DO I GET THIS?
    note = models.TextField()
    time = models.DateTimeField(editable=False, auto_now_add=True, auto_created=True)
    created_by = models.ForeignKey(User, on_delete=models.DO_NOTHING, auto_created=True, editable=False, related_name='notecreatedby')
    type = models.ForeignKey(NoteType, on_delete=models.DO_NOTHING)```

I know that customer ID is defined in the URL as follows:

**urls.py**
```py
    path('update/<int:pk>', views.CustomerUpdateView.as_view(), name='update_customer'),
    path('update/<int:customer_id>/savenote', views.CustomerCreateNote.as_view(), name='add_customer_note'), # <-- HERE SHOULD BE WHERE I CAN GET THE CUSTOMER ID```

How do I get that ID?
#

I guess I'll include my views.py as well:

class CustomerCreateNote(CreateView):
    model = Note
    fields = ['note']
    customer_id = 0

    def post(self, request, *args, **kwargs):
        pass

    def get_success_url(self):
        return reverse_lazy('view_customer', kwargs={'id': 1})

    def form_valid(self, form, *args, **kwargs):
        obj = form.save(commit=False)

        obj.created_by = self.request.user
        obj.customer = Customer.objects.get(pk=form.cleaned_data['customer'])
        obj.type = NoteType.objects.get(pk=1)
        # obj.save()
        return super().form_valid(form)

It's under major reconstruction

#

I thought it was originally going to be request['customer_id'] but that didn't work...

opal canyon
ember eagle
#

@opal canyon i tried to do that but was dissuaded by pycharm... NameError: name 'customer_id' is not defined

opal canyon
#

it's all explained there with examples

ember eagle
#

awesome @opal canyon - thank you!

opal canyon
#

For example

opal canyon
cedar cove
#

Hey guys, question, best way to store a list of floats on the database using models?

#

Honestly I've got no clue of what would be the best practice in this case

inland oak
#

if unknown... then better just creating table with float element for row

#

it will be auto ordered by primary key

#

you would have some problems with inserting new elements in the middle of the list though
depending on what you exactly need perhaps integer element with your own element counter is in order
Though forget about it. It does not sound good to use SQL db for that

inland oak
#

you will be able to store your list of floats exactly as list of floats

#

without any extra trouble

dusk portal
#

hey i need a very small help i am doing pagination and my home page is working perfectly but when im opening the detailed (paginated ) new post added page it's showing some error

inland oak
dusk portal
#

my views

#
def detail(request,question_id):
    n1=Posts.objects.get(pk=question_id)
    return render(request,'app1/detail.html',{"n1":n1})```
#

plz help

#

i just forgot how to paginate lol

#

im too dumb

#

ok done

#

thanks alot

waxen lion
#

Hey guys
Anyone familiar with apscheduler in django?

native tide
#

whenever i do open with liver server google hangs , i have tried 100 times still not working

latent cosmos
#

[Help] flask html/css divs:
I have 2 divs next to each other in div container. But on mobile I want them to be moved to below each other. I cannot do it, I tried different displays: flex/ grid. Did not help:

# main container which will have 2 divs inside next to each other:
.main{
  display: flex;
}

.div_1{
  text-align: left;
  font-size: 14px;
  padding: 15px;
  margin: 15px;
}

.div_2{
  /* empty */
}

so html looks like:

<div class="main">
  <div class="div_1">
    Some Left Menu Data
  </div>
  <div class="div_2">
    Main article Content
  </div>
</div>

How to break them on mobile? (div under div)

jovial cloud
merry kelp
#

I have a flask application and i want to create routes that can only be visited when a button on the current route is clicked and not on the adress bar
thx

thorn igloo
#

else what you are looking for is impossible

chilly falcon
#

hello

#

i want to know i have create django project and i have written mysql localhost server password in it and added that project folder to github in public repo ! ! Do u think that good to share you local host mysql server username password with project

#

anyone??

#

if not how to add folder of django to the github repo?? only app?

bright lodge
#

My css changes wont get applied no matter what i do

merry kelp
merry kelp
latent cosmos
#

@jovial cloud @merry kelp Thank you very much guys, appreciate the info

inland oak
#

is it possible to make django ORM request with closing db connection right after that
creating threads in django exhausts database limit connection, how to fix that? I don't even need active db in my child

desert estuary
#

im using the datetime module to display the current day
but i don't get it why sql is bothered

from flask import render_template,redirect,url_for
from Flaskiproject import app
from Flaskiproject.forms import Login_formcall
from datetime import datetime
@app.route('/')
def login():
   form=Login_formcall()
   ademail="@direwa"
   useremail="@ecolewa"
   if form.validate_on_submit:
      if ademail in form.email_user.data:
         return redirect(url_for('admin'))
      elif useremail in form.email_user.data:
         return redirect(url_for('user'))
   return render_template("Layout_log.html",form=form)
@app.route('/admin')
def admin():
   date=datetime.now()
   elegante_date=date.strftime("%A %d %B %Y")
   """
   for temporary use only we will give some dumbass data
   """
   return render_template('Admin/Layout_Admin.html',date=elegante_date)

routes.py

from enum import unique
from Flaskiproject import db
# from sqlalchemy import Column,Integer,String
class Students(db.Model):
   id=db.Column(db.Integer(),primary_key=True)
   fullname=db.Column(db.String(50),unique=True,nullable=False)
   dialling_num=db.Column(db.String(int,15),unique=True)

models.py
init.py

from flask import Flask
from secrets import token_hex
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
app=Flask(__name__)
xa=token_hex(16)
app.config['SECRET_KEY']='abcdef5fe2659e'
app.config['SQLALCHEMY_DATABASE_URI']='sqlite:///PFA_DB.db'
db=SQLAlchemy(app)

import Flaskiproject.routes
here's the error
https://pastecord.com/agukirafeg

latent cosmos
#

@desert estuary try only date=datetime.now
without parenthesis

merry kelp
#

@desert estuary try only date = datetime.now

desert estuary
#

thank you

desert estuary
#

actually i solved the problem before hand it gave me a weird error and i restarted the computer and now it worked
would such a problem would happen if i hosted it if yes how should i deal with it

tiny violet
#

Hello... I am unable to validate a php contact form on my website.

#

<div class="container">
<div class="form">
<form action="forms/contact.php" method="post" role="form" class="php-email-form">
<div class="form-row">
<div class="form-group col-md-6">
<input type="text" name="name" class="form-control" id="name" placeholder="Your Name" data-rule="minlen:4" data-msg="Please enter at least 4 chars" />
<div class="validate"></div>
</div>
<div class="form-group col-md-6">
<input type="email" class="form-control" name="email" id="email" placeholder="Your Email" data-rule="email" data-msg="Please enter a valid email" />
<div class="validate"></div>
</div>
</div>
<div class="form-group">
<input type="text" class="form-control" name="subject" id="subject" placeholder="Subject" data-rule="minlen:4" data-msg="Please enter at least 8 chars of subject" />
<div class="validate"></div>
</div>
<div class="form-group">
<textarea class="form-control" name="message" rows="5" data-rule="required" data-msg="Please write something for us" placeholder="Message"></textarea>
<div class="validate"></div>
</div>

        <div class="mb-3">
          <div class="loading">Loading</div>
          <div class="error-message"></div>
          <div class="sent-message">Your message has been sent. Thank you!</div>
        </div>

        <div class="text-center"><button type="submit">Send Message</button></div>
      </form>
    </div>
#

Above is the index.html code

#

above is the first half of the php code

#

this is the second half of the code

native tide
#

Hello, I'm using Django and right now I'm creating web. Tell me it is better to use django admin web or create my own to CRUD?

stark tartan
#

Anybody can suggest or Any article for doing messaging system in django with Javascript and jQuery

merry kelp
#

i am using flask and sqlalchemy how can i delete the table which i have created

#

i mean the model i created

latent cosmos
#

db.drop_all() and try again 🙂

merry kelp
#

i mean a single model

thorn igloo
primal thorn
merry kelp
native tide
latent cosmos
#

so login to your xampp or whatever server its on and go to phpmyadmin, then remove it from GUI @merry kelp

cedar cove
#

I've got no clue how to use mongoDb on Django tho

latent cosmos
thorn igloo
# merry kelp mysql

download DBeaver and connect your database there, you will easily be able to drop tables etc

merry kelp
#

thx

latent cosmos
#

mongoDB is hard to learn? @thorn igloo

thorn igloo
#

I don't know, never learnt it

inland oak
#

but need makes us learning

indigo vessel
#

<html>
</html>

inland oak
#

MongoDB is a must skill anyway for python backend

#

so it is good oportunity to get a hang of it ;b

thorn igloo
#

a must?

latent cosmos
#

you think so, my must is mysql / postgres / sqlite

thorn igloo
#

i think it's an optional thing to learn

cedar cove
#

Any hints on how to set it up?

indigo vessel
#

let me hear your opinion?

inland oak
#

tried its beginning at least

thorn igloo
inland oak
#

and better to skip them

#

at least I did not like them

#

abandoned at the begining 😉

indigo vessel
#

anything... come on I'm just a beginner..... anything will do as long as it's not too harsh

thorn igloo
#

bro, html+css is one of those combos where the code doesn't really matter but rather what it looks like

#

also you're using the label tag wrong

inland oak
inland oak
#

and actually code a bit matters there too

indigo vessel
#

well back to work.

inland oak
#

it is possible to make spaghetti out of html+css as well

cedar cove
glossy scroll
#

guys

#

any way we can create child views in Django

#

like the login required mixin is repeated so many times

#

can i do this in a non repeating way?

merry kelp
#

why i am not able to redirect that

thorn igloo
merry kelp
thorn igloo
merry kelp
#

i am seeing again admin page instead of database page

merry kelp
#

i was not inserting csrf tag into page

thorn igloo
#

oh ok

cedar cove
#

@inland oak why is this so complicated damn

inland oak
steel pier
#
window.addEventListener("load", () => {
    const canvas = document.querySelector("#canvas");
    const ctx = canvas.getContext("2d");

    //Resize Canvas
    canvas.height = window.innerHeight;
    canvas.width = window.innerWidth;
});```
Why is the canvas bigger than chrome? Those scroll bars come and its annoying
#

someone please

thorn igloo
steel pier
thorn igloo
#

ok

sterile swan
#

Guys any tips for CSS. Why is it this way

sterile swan
#

I haven't worked on any real world project so am adking just outa curiosity. Will there be some kinda blueprint for the design of the webpage or the web dev is put in a room and tortured to give the webpage👀 @thorn igloo

inland oak
ember eagle
#

to be fair, @sterile swan it's this way to allow flexibility while trying to convey context at the same time... it used to be that if you wanted elements inside of elements you had to put it inside of a table

#

thesedays, however, you have 150 different screen sizes and types... aka DPI's... so the code has to do more

desert estuary
#

the same error popped up

thorn igloo
#

what's it supposed to do

desert estuary
#

the dialling number of the student

#

so i kinda know how the problem is caused so basically in powershell i called python and did this

lavish prismBOT
#

Hey @desert estuary!

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

thorn igloo
desert estuary
thorn igloo
#

what is int supposed to represent here?

desert estuary
#

to just accept ints i guess

#

so if someone types

thorn igloo
#

bro, where did you get that you can do that? cause there's no such thing on the sqlalchemy docs

desert estuary
#

+1 54sdaze7589
it shouldn't be accepted

#

but to get +1 547 852 96

thorn igloo
#

db.String represents a string, a string can be entirely made of digits etc. my guess is that this is the cause of your error

desert estuary
#

for example

#

i corrected it

#
from Flaskiproject import db

class Students(db.Model):
   id=db.Column(db.Integer(),primary_key=True)
   fullname=db.Column(db.String(50),unique=True,nullable=False)
   dialling_num=db.Column(db.Integer(),unique=True)
   branch=db.Column(db.String())
   occupation=db.Column(db.String)
   def __repr__(self):
      return f'Student:{Students.id} {Students.fullname} {Students.dialling_num} {Students.branch}'
thorn igloo
desert estuary
#

ohh okay i see

#

can you check that link pasted there

thorn igloo
#

you're still getting the error after that?

thorn igloo
thorn igloo
# desert estuary here

also you forgot closing brackets for occupation, should be :

occupation = db.Column(db.String())
#

i should also ask, is this your only table?

desert estuary
#

yes sir

#

here even tho i created it still it's empty

merry kelp
desert estuary
#

already tried

#

still didn't work

merry kelp
#

whats the actual error ?

#

can u send me ss

thorn igloo
#

delete the .db file so it creates a new one

#

class Students(db.Model):
   id=db.Column(db.Integer(),primary_key=True)
   fullname=db.Column(db.String(50),unique=True,nullable=False)
   dialling_num=db.Column(db.Integer(),unique=True)
   branch=db.Column(db.String())
   occupation=db.Column(db.String())
   def __repr__(self):
      return f'Student:{Students.id} {Students.fullname} {Students.dialling_num} {Students.branch}'

i used this and it works

merry kelp
thorn igloo
desert estuary
#

wait it did work but i read both of our code they're identical

#

so why??

thorn igloo
#

why what exactly?

desert estuary
#

why yours worked while mine didn't

#

was it bcz the import

#

bcz i was importing db and models in the same time

#

and if so what's the difference between importing the module and from module import *

latent cosmos
#

make dialing number as A STRING! @desert estuary @thorn igloo

#

varchar *

desert estuary
latent cosmos
#

cmon man, store it in string so you will save memory, you can always cast to int later when processing data, please @desert estuary

thorn igloo
#

no, you can use string, db.String(int,15) this is just wrong syntax

latent cosmos
#

you wanna store 9 digits number in int? lol

thorn igloo
#

int should not be there

latent cosmos
#

even more than 9 sometimes

thorn igloo
#

should be db.String(15) rather

latent cosmos
#

US number has 10, and plus direct number? its even over 12 digits sometimes

#

ofc it should be string

thorn igloo
#

and well, to answer your question, i am using the flask shell context, so i am not sure how you are running your thing, and if you want to create a table or tables with db.create_all(), the class for the table should be visible in the shell you are using, which is why i used from models import *, it imports db along with my classes as they are

latent cosmos
#

right, where you start your main project, there should be a shell, tell him @thorn igloo

#

I use git bash for example

thorn igloo
#

no i mean flask shell

#

like

latent cosmos
#

there where servers runnin you mean

thorn igloo
latent cosmos
#

he can always run jsut shell, go to his main project and then run python from shell, it will be the sdame

#

he can manipulate DB from there

#

just importing 2 lines of db and depends where his models are

thorn igloo
#

it's better to use the flask shell when creating the db because of the app context thing

latent cosmos
#

its ok to use as I wrote too

#

you were programming in Java FX? so your nickname come from there? @thorn igloo System.out.println("Hello world");

thorn igloo
#

no, just a name i came up with, for gaming purposes

cedar cove
#

Is it possible to save a non serializable object on the session?

scarlet spoke
#

what does

#search-result .listvideo li a

select

thorn igloo
scarlet spoke
#

thanks!

pine torrent
#

how to store session as foreign key in database?

thorn igloo
#

do you know what a foreign key is and what it's purpose is?

pine torrent
#

how to select foreign key by session in django

ember eagle
pine torrent
#

how to connect variable with selection tag to be selected in django

gentle ingot
#

I need help passing a return value from a webpage to javascript to create an alert output

cerulean laurel
#

hey fellows

pallid crow
ember eagle
gentle ingot
#

It requires an input to run from a drop down.

#

So I have to get the value, attach it to the end of the url since the app path is game/<move> and it’ll run the python script.

ember eagle
#

wait, forgive my ignorance, you said python script, not JS script

gentle ingot
#

Yeah I edit to make it clear. Not use to using multiple scripting languages at once 😅

ember eagle
#

haha

#

couldn't you simply tell JS to pull an AJAX refresh on said URL?

gentle ingot
#

Honestly I’m only using flask to showcase python skills for potential employment eventually.

#

Okay I’ll look into Ajax. I have to use document.GetElementById on the select box to concentrate the url right?

ember eagle
#

ah, i'm the reverse... well established, well qualified PHP/HTML/CSS/JS/SQL programmer breaking into Django because i want something easier :p

gentle ingot
#

Oooh full stack lol.

ember eagle
#

yeah - it's a difficult place to be :\

#

you're either "great but not exactly qualified" or "we want only this"

gentle ingot
#

Omit the extra from resume. Seen that not listing anything that would over qualify you such as degrees or skills actually help for the “we only want this” situations

ember eagle
#

haha yeah, i broke out and went freelance for now - i'll hit the churn later

gentle ingot
#

The dream. Freelance development and small quantity electronics component store. Radio shack but cheaper.

#

And it services.

ember eagle
#

nice 😄

#

soon for me...

gentle ingot
#

I have a ways to go. Gotta get my CompTIA a+. Anyway, I’ll try Ajax. If I need further help mind if I ping you?

ember eagle
#

nah, feel free - AJAX should serve you well, if you have JQuery installed it could be as simple as one line 😄

#

careful - it can become gnarly if you begin loading content in via AJAX and not keeping track of the "global namespace" for javascript... if you get heavy into it, i can recommend reading for ya

gentle ingot
#

I’m only using it because I didn’t enjoy the idea of loading a new page from my portfolio. Espeically since it’s a small sample of my Rock paper Scissor discord bot.

ember eagle
# opal canyon No Worries

so it turned from that super complex code to something so simple... i hate how django mocks me sometimes...

ocean notch
#

Hi, from the DRF documentation, 'serializer_class' attribute is only for GenericAPIView class, but why does it also work with APIView class? I cannot find anything on it

#

I know that GenericAPIView is a descendant of APIView, so shouldn't it not work? Maybe im missing something related to OOP?

#

for example, extending APIView using some attributes from 'GenericAPIView' works...why?

pale ledge
#

Bro best free resources to learning django anyone

ocean notch
#

Docs are pretty good if you can get into it xD

pale ledge
#

Thanks space

ocean notch
#

np, i tried doing tutorials and skippin docs, but that was a huge mistake

velvet yew
#

Can someone recommend a resource or help with creating a basic Django API that just returns a string for example? I'm following the Django REST tutorial but it's so overcomplicated it makes no sense. Does it take 50 times more code to just return something with Django REST than with FastAPI?

ocean notch
#

bro just use viewset/router and model serializer

velvet yew
#

That's what the tutorial showed also but it's super overcomplicated for such a simple task

#

And I've yet to figure out how to return something specific

#

since the tutorial's code doesn't even have a return

ocean notch
#

just keep the return and request.method

#

and the api_view decorator

#

and return anything

#

thats it

velvet yew
#

But why are the serializers needed

ocean notch
#

its not

#

its only if you have a model

#

if you're returning a string just return a string

velvet yew
#

And how do I set the url etc?

#

Can you recommend a tutorial that isn't 20 hours long?

ocean notch
#

yeah

#

it took like 2 hours to go through all the parts

velvet yew
#

Well I'm at part 1 and don't understand anything

#

Nor see why is 90% of that code even there in the first place

#

FastAPI took me literally 2 minutes to set up

ocean notch
#

yeah its called fastapi

#

its also not a complete framework

#

if you're just trying to return strings then go ahead use fastapi

#

maybe look at django docs

velvet yew
#

I would but it doesn't make much sense to run the web app on django and run a single API function on fastapi

cerulean laurel
#

which is the best frontend framework to work with django?

ocean notch
velvet yew
ocean notch
#

ok, so you might be getting ahead of yourself trying to jump too far ahead

#

maybe take a beginner tutorial on backend development or django

velvet yew
#

I'm almost 100% sure I don't need them

#

I just want to return a function

#

Without having to write 50 lines of code in 5 different files

ocean notch
#

lol you sure as hell need them if you dont understand the basic underlying principles

#

such as serializers

ember eagle
velvet yew
#

So everything in Django is 50x the code length of FastAPI?

#

I haven't had to use serializers once with FastAPI

ocean notch
#

you're going in circles bro

#

instead of blaming the framwork

#

it seems like you really have no idea of the basic underlying principles

velvet yew
#

I don't nor do I care

#

I want to return a fucking function is all

ocean notch
#

you're ganna go far as a developer

#

i showed you the code already

#

just get rid of the serializer part

#

if you just want to return a string

velvet yew
#

So perhaps could you show a code that doesn't have any of the useless stuff in them just what I need?

#

I want to return this is a string

ocean notch
#

dude you're asking the question, you show the code

velvet yew
#

Show what code

ocean notch
#

whatever you have so far

velvet yew
#
def test():
  return "this is a string"
#

There

ember eagle
eternal blade
velvet yew
velvet yew
ember eagle
#

Well, the more abstract you go (more stuff you can do with a language) the more code it's going to take to do it

velvet yew
#

I want authentication & rate limiting etc. which is tough in FastAPI

ember eagle
#

FastAPI is focused on API calls, Django is focused on displaying a website

velvet yew
#

But all I want is to return a fucking function lol how hard could it be

eternal blade
ember eagle
#

I'm probably like... stupid here... but i don't consider 8 lines of code a lot of code

eternal blade
velvet yew
#

Can you send me those 8 lines?

ember eagle
#

in PHP to return a function through an API call you have 5 documents spread out with 38 lines each

velvet yew
eternal blade
ember eagle
velvet yew
#

But I figured I shouldn't use that

velvet yew
ocean notch
#

just remove the unneeded stuff

#

surely you can tell which of the things aren't necessary?

velvet yew
#

But I don't know what's unneeded that's my whole point

ember eagle
#

then comment a line and test it

#

if it breaks it don't remove that line

eternal blade
ember eagle
#

.<

velvet yew
#

I thought the point was to make it even more simpler

ember eagle
#

simpler is a relative term

#

based on what i've seen, in 1.7 things were a LOT harder

ocean notch
#

also it does make things simpler, but there is more setup required, not everything comes without a cost

eternal blade
velvet yew
#

How do I return JsonResponse?

#

I can only import HttpResponse

eternal blade
#
from django.http import JsonResponse

# In your view function
return JsonResponse({"message":"test"})```
velvet yew
#

Ty

#

Was trying to find it in django.shortcuts

eternal blade
#

!d django.http.JsonResponse the docs for it

lavish prismBOT
#

class JsonResponse(data, encoder=DjangoJSONEncoder, safe=True, json_dumps_params=None, **kwargs)```
An [`HttpResponse`](https://docs.djangoproject.com/en/stable/ref/request-response/#django.http.HttpResponse "django.http.HttpResponse") subclass that helps to create a JSON-encoded response. It inherits most behavior from its superclass with a couple differences:

Its default `Content-Type` header is set to *application/json*.

The first parameter, `data`, should be a `dict` instance. If the `safe` parameter is set to `False` (see below) it can be any JSON-serializable object.

The `encoder`, which defaults to [`django.core.serializers.json.DjangoJSONEncoder`](https://docs.djangoproject.com/en/stable/topics/serialization/#django.core.serializers.json.DjangoJSONEncoder "django.core.serializers.json.DjangoJSONEncoder"), will be used to serialize the data. See [JSON serialization](https://docs.djangoproject.com/en/stable/topics/serialization/#serialization-formats-json) for more details about this serializer.
eternal blade
#

Python discords api uses the Django rest framework

velvet yew
#

How can I take in args?

#

For example if I wanted to do

def api_test(request, x, y):

    result = x * y

    return JsonResponse({"result": result})
#

And then make the request like url.com?x=1&y=5

#

The Django docs are so shit

ocean notch
#

So are Arabian sacred texts

#

But do I speak Arabian

velvet yew
#

Great argument thanks for the input

inland oak
#

I would say Django is universal all around tool

#

the only thing it lacks...

#

having a bit better async support. It is only halfly ready, but it is already there.

#

the last part is remaining, Django ORM to be converted

inland oak
# ocean notch Hi, from the DRF documentation, 'serializer_class' attribute is only for Generic...

as far as I understand serializer_class is multi purpose thing, I thought its main usage is needed for mixins
https://www.django-rest-framework.org/api-guide/generic-views/#mixins
creating either CRUD for all operations at once or
for particular operations with mixins like:
CreateModelMixin
RetrieveModelMixin
UpdateModelMixin
DestroyModelMixin

inland oak
velvet yew
#
@api_view(["GET"])
def api_test(request, x, y):

    result = x + y

    return Response(result)
#

Yeah same thing

inland oak
velvet yew
#

Well that just gave me a headache

inland oak
#

well, you can directly extract values from query_params, but you know, converting in advance them a bit better

#

there is another solution though

#

which involves probably less converting.

#

JSON supports transfering ints I think

inland oak
#

as proper JSON

#

it would be better

#

fixed example

#

two ways to input data for you

#

;b

velvet yew
#

Oh that looks a million times better

#

Let me try

inland oak
#

first choice requires transfering input data as query_params
and second way asks you to input json

velvet yew
#

The query_params one worked the way I wanted it

#
@api_view(["GET"])
def api_test(request):

    x = int(request.query_params["x"])
    y = int(request.query_params["y"])

    result = x + y

    return Response({"result": result})

If anyone else searching for this

inland oak
#

xD. the only thing it is missing...

inland oak
ocean notch
#

since it calls self.serializer_class and uses it

ionic raft
grand oriole
gentle ingot
#

Im having troubles with jinja. When i load /rps everything works perfectly fine. When i go to /rps/<move> or /rps/paper it decides not to load any css

inland oak
#

try to use {{ static load }} or something like that, supplied for jinja

#

it will make static addresses attached to your web framework particular things

#

as easy dumb solution...

#

you can just try to replace your current static file address

#

you had like blaablabla
replace with ../blablabla

#

it will make it seeking static file in folder by one level higher

gentle ingot
#

I have no idea what happened but i changed it from static/css/styles.css to url_for and now its worse. nothing works instead of just the one page lmao

#

<link href="static/css/styles.css" rel="stylesheet"> is how i currently have it

inland oak
#

oh. idea.

#

<link href="/static/css/styles.css" rel="stylesheet">

#

what if to try this? 😉

gentle ingot
#

Well my thing is that works. For every other template and app route i have. Except my new one

inland oak
#

the problem is probably because you have relative address

#

while your new one expects having relative address ../static/css/styles.css

#

perhaps absolute one address will work

#

/static/css/styles.css for all pages

gentle ingot
#

I apologize. That worked. Its too late to be coding lmao. I should turn in, its 4 am

inland oak
gentle ingot
#

Got it working. gotta space out the project block and on to sampling my next project

robust stone
dusk portal
#
path('password-reset-confirm/<uidb64>/<token>/',views.PasswordResetConfirmView.as_view(template_name='users/password_reset_confirm.html'),name='password_reset_confirm'),```
#

why errror now

mystic vortex
#

Anyone here

#

@dusk portal

dusk portal
#

@mystic vortex yes

mystic vortex
#

I need help with flask

mystic vortex
dusk portal
dusk portal
drifting nexus
#
import winsound
from time import sleep
driver = webdriver.Chrome(r"C:\users\ARMcPro\Desktop\chromedriver.exe")
driver.get("https://www.google.com")
while True:
    sleep(1)
    if driver.page_source.find("test") > -1:
        driver.refresh()
    else:
        winsound.Beep(500, 1000)```
I am trying to make a program which detects a specific change in a website (google is a placeholder here)
The program works for a while then it raises a `RecursionError: Maximum recursion depth exceeded while calling a Python object`
mystic vortex
shut bloom
#

Does anyone can give me idea on Open Source Contribution in web?
I can not know how to choice or find a project to contribute as beginner

raw jolt
#

Hey my template in django seems to not find css files I'm linking to

#

basically when I run local developement server of template I want styled, nothing changes. I followed file structure in tutorial, but I found in different sources, different structures. However nothing I tried worked

torn torrent
#

did you set your static file directory?

#

your STATICFILES_DIR i mean

#

you should also set a STAT_ROOT as well

raw jolt
#

ehm

torn torrent
#

STATIC_ROOT **

raw jolt
#

yeah I didn't do that. My static folder is inside my app though, and I thought it's when you have some kind of static folder for whole project

#

could be missunderstanding

torn torrent
#

just make sure these lines are there

raw jolt
#

yeah gimme 1min

#

bunch of nothing.

torn torrent
#

ok here is what you do

#

do you have your static folder ?

#

put the static files in your static folder

#

and then go to your console and type "manage.py collectstatic"

raw jolt
#

ok but should my static folder in my project dir or app dir.

torn torrent
#

project dir

#

if you copied the code i put in the image above

raw jolt
#

yeah I used app dir all the time, this is why I included ss above, but yeh

torn torrent
#

app dir wont work if you follow the code i put above

#

let me know if you succeded

raw jolt
#

nah I copied in both dirs, still nothing.

torn torrent
#

did you collectstatic?

raw jolt
#

It really seems like I missed some very simple step or made some typo, because right now I'm super lost

cedar cove
#

Is there a way to have a view send several "responses" after time goes on?
Like, say I have something like:

class FizzView(APIView):
  def post(self, request, format=None):
    data = request.data
    for value in data.get("values"):
      result = doSomething(value)
      report = reportOnThatSomething(result) # This can take up to a minute
      # I should send the report information here to the frontend, any clues how?
      
    return Response({"Ok":"Execution completed"}, status=status.HTTP_200_OK) 

Any ideas?

raw jolt
#

now I'm super confused. I added JS folder with simple document.write('hello') and it works, however damn thing still won't style my html

#

💩

merry kelp
#

i am working in flask with sqlalchemy i want to get all names of tables which are in database

thorn igloo
opaque rivet
#

if I want to expose ports of my docker container to other docker containers, I don't need to specify this in the dockerfile correct?

rigid turret
thorn igloo
opaque rivet
#

In one of my microservices:

# settings.py
ALLOWED_HOSTS = ["*"]

I'm getting the error:
Invalid HTTP_HOST header: 'data_scraper:8000'. The domain name provided is not valid according to RFC 1034/1035.

#

but that should be valid?

#

oh - it's an RFC 1034/1035 thing. the host can't contain underscores

warm igloo
#

just a guess but it may want you to have a tld too?

opaque rivet
#

but regardless, it's fixed, finally getting 200 status code

#

my microservice was called data_scraper, changed it to data-scraper and it works

#

feels much more bulky having django apps all over the place instead of having one monolithic web app

warm igloo
#

there's a balance to strike for sure

#

monoliths themselves aren't bad and you can over-microservice yourself

#

its important to design thinking about the domains and scopes of what is happening and where a monolith is good with satellite microservices in "orbit" more or less around it

#

whereas I'm currently trying to help our team disassemble a anti-pattern called "Big Ball o' Mud" where we have a monolith of monoliths. And slowly breaking it apart. Likely the final version will end up being 5 monoliths that are individual "apps" but communicate to each other and to the outside world via microservices.

dusk portal
#

help im getting this error while i am using django.contrib.auth view

elder nebula
#

Do you know any good guides to creating tests for django projects?

dusk portal
#
    path('password-reset-confirm/<uidb64>/<token>/',views.PasswordResetConfirmView.as_view(template_name='users/password_reset_confirm.html'),name='password_reset_confirm'),
elder nebula
# dusk portal django docs

I mean any general guides, like how to make tests that will expose things like bugs or holes in your code.

dusk portal
barren moth
#

how the heck did you choose me

elder nebula
#

The chosen one

gaunt socket
#

Hello Guys, I need help with this piece of HTML and CSS ```html
<div class="srv-grid">
{% for guild in guilds %}
<div class="card-wrapper">
{% if guild.joined %}
<a class="card-link" href="{{ url_for('dashboard_server', guild_id=guild.id) }}">
{% else %}
<a class="card-link" href="{{ guild.invite_link }}">
{% endif %}
<div class="card-server">
{% if guild.icon_url %}
<div class="card-image-icon" style="background-image: url('{{ guild.icon_url }}');"></div>
{% else %}
<div class="card-image">
<div class="card-image-placeholder">{{ guild.short }}</div>
</div>
{% endif %}
<div class="card-label">{{ guild.name }}</div>
</div>
</a>
</div>
{% endfor %}
</div>

So, the whole grid and cards show perfectly except: the images don't show. This is because the height is 0 in the computed CSS ```css
width: 100%;
height: auto;
``` This is my real CSS but the `height: auto;` seems to somehow just not work. Is it because the cards get added dynamically?
Btw, when I used the exact same HTML just with one hard coded card, the image did show, and it shows too when I set `height: 100px;` for example. So the problem is the `auto`
#

But I can't hard code the height, because it would be messed up on all other screen sizes than mine

elder nebula
#

Height auto will set the image size to the height of it's contents. The content height is 0px so it will set the image size to 0px.

gaunt socket
#

But why is it 0

#

I don't want to hard code any heights because the cards' height will be different for each screen size

elder nebula
#

Maybe you have put it inside of a div or element what height is 0px. Or haven't set the height

gaunt socket
#

And theirs does not compute to 0

elder nebula
#

I don't know because you have provided very little css

gaunt socket
#

I once even copied the discord page's CSS and still didn't work

elder nebula
#

So did you code the css yourself or just copied?

gaunt socket
#

I tried myself and tried with the copied CSS

gaunt socket
#

I see

#

That's why I am asking

#

🙂

gaunt socket
#

The image is gone

#

The image is there when I inspect it but just with height 0

#

That is just changing height auto to height 100px

calm plume
#

What's wrong with that?

#

It looks good

gaunt socket
#

Yea but only on PC

#

lol

elder nebula
#

Looks good

calm plume
#

What's wrong with that?

#

Still looks fine

gaunt socket
#

uh

#

the bottom part

#

is gone

#

And not square

#

anymore

safe monolith
#

today I got a partner to connect to a jupyter lab with ngrok, but they couldn't make changes. does anyone know how I can do this?
please ping with any useful feedback.

gaunt socket
elder nebula
calm plume
#

Assuming height is 100px

gaunt socket
#

But then when the grid is adjusting and making cards smaller, the image is still giant

#

Just not fitting

calm plume
#

Hardcode the card width as well

elder nebula
#

Set the card to fit the images then

gaunt socket
#

Any other ideas how I can get the height auto to just calculate correctly?

elder nebula
#

You should code it from the start by yourself so you understand what it is doing

gaunt socket
#

But the auto thingy just refuses

elder nebula
#

Is the hypixel link what you are working on?

gaunt socket
#

no

#

That's just an image host

elder nebula
#

I mean are you building the site or can you share the code. Maybe I can help you with it

gaunt socket
#

What more code is there to share?

#

The quart backend

#

But

#

That can't possibly matter

elder nebula
#

No I want only the css and html. Is it running on the hypixel domain?

gaunt socket
#

no

#

localhost

elder nebula
#

Alright

gaunt socket
#

Or is there more

#

That you need

#

oh btw the whole HTML block is in a container

#

If that matters

elder nebula
#

Wait

#

can you send a pic how it should look like

gaunt socket
#

wdym

elder nebula
#

is that the whole css?

#

on your original post

gaunt socket
#

Well

#

imported bootstrap and daisyui

#

The whole HTML block I sent is inside a container (bootstrap) inside a flexbot (daisyui)

elder nebula
#

Oh I see

#

Can you set the overflow:hidden and try that. Sometimes it have helped me

gaunt socket
#

on the grid?

#

Or where

elder nebula
#

image

gaunt socket
#

ok

#

With height auto?

#

and width 100%

elder nebula
#

yes

#

it might not work in this case

gaunt socket
elder nebula
#

I am afraid I can't help you without knowing what css goes in to the parent divs

gaunt socket
#

I'll try without the container

#

and the flexbox

elder nebula
#

Yeah, if you can build it with just bootstrap that'll be great. Otherwise it's hard to make while you mix bootstrap and own css

gaunt socket
#

That's just the HTML I sent

#

And the CSS I sent

#

The weirdest part is that when I copied the CSS from discord's card image, the auto still gave 0

elder nebula
#

There might be some css you missed, but I am sure you'll find a solution for it

#

I gotta go

gaunt socket
#

I have tried for 3 hours

#

Also looking at discord's for a while

#

So confused

#

But thanks

mellow shale
#

Is question regarding selenium applicable here or under #unit-testing ?

proper hinge
#

If your question is about testing and you're using selenium for testing, you can ask there

#

If it's about "how to select x element in my website" then maybe this channel is better

gaunt socket
#

Okay so now I figured out that just using bootstrap img-fluid works perfectly, except: when the icon is not found I am trying to add a blank background and centered text. I can't just use the same img-fluid, because it's not an image
https://hypixeI.net/‌⁠​‍‌⁠‍⁠⁠‍​‍‍⁠‍‍‍​‌⁠⁠​⁠​⁠​

Hypixel - Minecraft Server and Maps

Play award winning minecraft games and mini-games with your friends for free. Only on the Hypixel minecraft server!

#

How can I make that responsive too

lapis basalt
#

Hi please I need help

gaunt socket
#

...

lapis basalt
#

am using gunicorn for multiprocessing of parallels clients requests and I want to improve the performance of my app. Does celery works well if applied directly on an api route it is more useful for backgrounds tasks. And check with me if my call to celery is correct:

`from celery import Celery

def make_celery(app):
celery = Celery(
app.import_name,
backend=app.config["CELERY_BACKEND_URL"],
broker=app.config["CELERY_BROKER_URL"],
)
celery.conf.update(app.config)

class ContextTask(celery.Task):
    def __call__(self, *args, **kwargs):
        with app.app_context():
            return self.run(*args, **kwargs)

celery.Task = ContextTask
return celery

We use the Flask framework to create an instance of the flask app

We then update our broker and backend URLs with the env variables

app = Flask(name)
app.config.update(
CELERY_BROKER_URL=os.environ.get("CELERY_BROKER_URL"),
CELERY_BACKEND_URL=os.environ.get("CELERY_BACKEND_URL"),
)

create an instance of celery using the function created earlier

`

cel_app = make_celery(app)
Thxx

proper hinge
gaunt socket
#

How does that help me

#

The grid works and is responsive

proper hinge
#

Isn't responsiveness what you were asking about?

gaunt socket
#

Well

#

For the black avatars

#

The rest is responsive I think

proper hinge
#

Can you clarify what kind of behaviour you want for those black avatars?

opaque rivet
#

You just need each card to take up the same height in each row

gaunt socket
#

yea

#

But the size of the images in managed by the img-fluid. But that does not apply to the black thingys

opaque rivet
#

Img fluid just gives max-width: 100% and height: auto

#

So you should give your cards explicit height and width

gaunt socket
#

I tried adding that to the black thing

gaunt socket
proper hinge
#

You can set a max height, for example

gaunt socket
#

Any ideas how I can make it as big as the img's

proper hinge
#

The images use img-fluid, right?

gaunt socket
#

yea

proper hinge
#

So I think with those settings, it tries to preserve aspect ratio, and fill up the width of the boxes. And the height is whatever is needed to keep the aspect ratio.

#

The width is sort of fixed - it's determine by the grid system

gaunt socket
#

yea

proper hinge
#

But your black box has no notion of an aspect ratio or whatever. It doesn't have anything is can relate to in order to set its height

#

CSS doesn't support relating that to siblings afaik

opaque rivet
#

Is it .img-fluid actually making it responsive? Or is it the grid?

gaunt socket
#

img-fluid

proper hinge
#

So I think you need either to set a fixed height or fixed max-height.

gaunt socket
opaque rivet
#

Well, you could use flexbox (pretty much a responsive grid) and have the cards have explicit sizes

proper hinge
#

Maybe. I think the current reason the image containers have the same height is cause you happen to be providing images with the same aspect ratio. I imagine that if you used images with different dimensions, they would also have the same problem as the placeholders you currently have

lapis basalt
gaunt socket
#

Well those are discord guild icons so they will always be the same

#

I hope

lapis basalt
#

Any suggestions any groups...

proper hinge
#

Sorry I have no idea - never used celery

lapis basalt
#

even in stack overflow anyone replied maybe my question isin't good enough?

#

Please best group to ask about flask

#

or about job queue topics

native tide
#

This might be more a Database error question, I am having trouble with this SQLalchemy error:

#
File "C:\Users\LuMi\crossfit\routes.py", line 123, in signup
            role = 'admin'
            confirmed = True
            created_on = datetime.now()
            password = form.password.data
            newuser = User(username, email, role, confirmed, created_on, password)
            db.session.add(newuser)
            db.session.commit()
    elif request.method == 'GET':
        return render_template('register.html', form=form)
 
 
File "<string>", line 2, in add
 
File "C:\Users\LuMi\crossfit\venv\Lib\site-packages\sqlalchemy\orm\scoping.py", line 23, in _proxied
return self.registry()
File "C:\Users\LuMi\crossfit\venv\Lib\site-packages\sqlalchemy\util\_collections.py", line 1010, in __call__
return self.registry.setdefault(key, self.createfunc())
File "C:\Users\LuMi\crossfit\venv\Lib\site-packages\sqlalchemy\orm\session.py", line 4101, in __call__
return self.class_(**local_kw)
File "C:\Users\LuMi\crossfit\venv\Lib\site-packages\flask_sqlalchemy\__init__.py", line 175, in __init__
track_modifications = app.config['SQLALCHEMY_TRACK_MODIFICATIONS']
KeyError: 'SQLALCHEMY_TRACK_MODIFICATIONS'
#

in Stackoverflow they say this happens when you have two instances of flask app(). But I have just one instance

#

does anyone know what triggers this error?

visual torrent
#

Hi. I have the following problem, I want to create an api in django. I will describe the different steps:

  1. I want to retrieve data from a certain address using requests.get(url).
    2.Then I am going to parse this data and extract what I am interested in. (The data is about cars e.g. Name, year of manufacture, color)
  1. then this data is to be returned using the GET method I created with the ability to filter by name.

My question is this, should I create a model in django from the retrieved data and then use DRF and django-filter for filtering or is there an easier way?

I will add that without filtering I would be able to do it just by returning the json but I don't know how to go about filtering

gritty cloud
#

if your data lives on another server, you don't need drf

#

if it is your own database, then models and drf is for you

#

since, in your situation, you are getting data from somewhere else

#

you don't need django rest frameworjk

#

or at least the serializer part

#

it still is good if you are building any rest api

broken mulch
#

how do I check the "SECRET_KEY" in app.route
(flask)

nimble radish
#

I'm learning Django REST right now, but I can't find anything in the documentation about how to POST foreign keys. I can see the foreign keys when using the API Browser but I have no clue how to do it in Postman with raw json...

#

nvm... I didn't read hard enough, i got it now.

desert estuary
#
@app.route('/',methods=["GET","POST"])
def login():
   form=Login_formcall()
   if form.validate_on_submit():
      if form.email_user.data.split('@')[1]=="direwa.com":
         if Admin.query.filter_by(email=form.email_user.data)==form.email_user.data:
            redirect(url_for('admin'))
         else:
            flash("you don't exist")
      elif form.email_user.data.split('@')[1]=="ecolewa.com":
         if Students.query.filter_by(email=form.email_user.data):
            redirect(url_for('user'))
         else:
            flash("the User doesn't exist")
      else:
         pass
   return render_template("Layout_log.html",form=form)

i wrote this and finding difficulty to understand it

if Admin.query.filter_by(email=form.email_user.data)==form.email_user.data:
  redirect(url_for('admin'))
```im telling it if the filter == form.email.data 
do the redirection to the admin page else he's not existing 
(sidenote :please give me a nicer way to tell the admin he doesn't exist)
and yeah idk if that's the right way to do it or no
rustic sky
#

so, I have a couple questions

#

I'm making a website with quite a few features, and one I have in mind is a top banner message that I or a different admin can set from the Django admin dashboard

#

perhaps I'm missing something in my learning... but how do I just make a single text entry field for something like this?

#

a model seems a bit much for something like that, maybe

inland copper
#

my proj

#

pls give feedback guyz

glacial wigeon
#

Any good/tried and tested books to learn Django from?

lavish prismBOT
#
Resources

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

dusk portal
#

go to books section and see two scoopes of django

native tide
#

Hey, i'm just getting started with django. I wanna ask why people keep creating urls.py on the app folder instead urls.py already been created in the djangoproject folder

blissful violet
#

@native tideI guess for the sake of keeping the main one clear, making it easier to read.

#

As well as making it easier to remove/add apps.

jovial cloud
jovial cloud
restive whale
#

hi, im just leaning basics . so here my qn is how to remove the space between the boarder that i marked?

jovial cloud
restive whale
#

i set all margin{0 px 5px}

jovial cloud
#

The margin is what causes the space. If you want to remove the space, remove the margin on that specific container

restive whale
#

this is what happened when i set the container margin:0px;

#

the green boarder represent the container of the image and text.

#

*border

#

the whole boxes are also in a one big container😆 .. its kinda crazy , i dont know how those big websites are made using flex

jovial cloud
lavish prismBOT
#

Hey @restive whale!

It looks like you tried to attach file type(s) that we do not allow (.html). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a.

Feel free to ask in #community-meta if you think this is a mistake.

#

Hey @restive whale!

It looks like you tried to attach file type(s) that we do not allow (.scss). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a.

Feel free to ask in #community-meta if you think this is a mistake.

restive whale
jovial cloud
restive whale
#

ohh..ok..shey..that was simple...haha.. thanks man..

#

so even if we already set margin to 0px with * there will be margin for those boxes? it wont apply to all elements ?

jovial cloud
bright lodge
restive whale
#

@jovial cloud thanks for help

#

@bright lodge yes, that was tutorial in freecodecamp abt media query

thorn igloo
#

is that a light theme?

ocean notch
#

definitely a designer xP

native tide
#

My eyes hurt lol

native tide
#

hey y'all, i've been trying to resolve this issue since yesterday in various channels, but no avail. so i opened a stackoverflow thread. Please feel free to take a look at it 🙂 https://stackoverflow.com/questions/68284089/what-triggers-the-keyerror-sqlalchemy-track-modifications

jovial cloud
lapis basalt
#

Hi

#

Please help

#

I want to render multiple dicts json to fornt

#

all in the same interface

#

but each one in a specific tab

#

and the tabs have to be created dynamically based on the number of dicts

#

a basic example

#

[{"name" = a, "age" = 29},{"name" = b, "age" = 19}, {"name" = c, "age" = 28}]

#

the first tab with be a table containing the first dict {"name" = a, "age" = 29}, the second tab a table containing {"name" = b, "age" = 19} and so one

#

knowing that I don't now the length of json in advance

honest hinge
#

hello ,what should i give the client when his site is ready?how can i receive him all access to his site?

opaque rivet
#

Make an API call to your endpoint, which returns an array of objects (JSON encoded). On your frontend, decode the data, and iterate through the array making a new table for each object.

#

@lapis basalt

#

Easily done with JS or jinja templates

#

@rustic sky If you want different admins being able to change it, a model is the way to go. Other than that, you can have an API that sets env variables, but anyone could query that unless you have auth

lapis basalt
#

ok thxx

#

@opaque rivet more details plz

crimson magnet
#

How does sending an image work using api work?
Like when you Request an image from this api https://thecatapi.com/ how does it send back an image?

#

I mean it only sends a link with an image but how does that link show the image? When posted like

#

^

calm plume
#

It's not something the api does

#

They just return a link to say, a png file, which the platform, in this case Discord, embeds

crimson magnet
#

But how could a url have png

#

What's going on under the hood?

calm plume
crimson magnet
#

Wdym link

calm plume
#

That might link to a png file

crimson magnet
vital vale
uneven garnet
#

yo there

thorn igloo
uneven garnet
crimson magnet
uneven garnet
#

do you are the slave of java script

crimson magnet
vital vale
#

and then when you request for the file, it uploads it as a file response (you can have json, html, xml, file responses, etc)

#

at a high level

uneven garnet
crimson magnet
#

Url = file system worried

vital vale
#

no mhm

thorn igloo
#

well as Addike said, you normally save them on the server system and then you can create a url that serves this images, as long as the image name is dynamic and exists on the server, the server or your backend will send it back

crimson magnet
#

Server system is like your storage file.png ?

thorn igloo
#

yes, you can save them locally or use something like aws really,

crimson magnet
#

aws? scared

#

Amazon web services?

thorn igloo
#

yeap

crimson magnet
#

What about Firebase thinkmon

vital vale
vital vale
#

so the url that you make the request to would normally give the api information about what file you want

#

This is more or less what cdn's do

crimson magnet
#

I somewhat get it thanks

vital vale
crimson magnet
#

But what about options on where you store them

#

I don't want people seeing some of those images in my github repo

vital vale
#

it would just be a different "route". Maybe this api says that to upload a file, and store it, you need to provide the file, and filename (as request data) in a request to mydomain.com/upload-file/
So you would make a request, with the filename in the request data, and upload the file along with it. Most requests libraries have a simple class/function to allow you to upload files along with a request

vital vale
crimson magnet
#

What's a recommend way

vital vale
#

You could write a cdn (basically the api I'm talking about) to handle serving your files

crimson magnet
#

Alright okayge

vital vale
#

a cdn = fast api to serve files

crimson magnet
vital vale
#

normally a cdn would use many servers around the world to decrease serve time mhm

#

but thats not required

vital vale
crimson magnet
#

:thinkie:

crimson magnet
vital vale
#

wdym?

crimson magnet
#

Changed

#

I wanna use FastApi for my api okayge

vital vale
vital vale
crimson magnet
#

I was thinking about hosting it on heroku

vital vale
#

It would work

crimson magnet
#

But I don't have domain and such

vital vale
#

If you're a student, you can a couple free with github education pack

crimson magnet
#

It takes months to get one sadge

vital vale
#

no mhmr

#

It takes at most, 1 month to get it mhm

#

but if you have a verified school + email id, it would only take a few hours at most

#

if not, it could take upto a month

crimson magnet
#

Verified school is doubt

vital vale
#

might take a few weeks then PepeShrug

crimson magnet
vital vale
#

if your api only handles files, then it would be a cdn, of sorts

crimson magnet
#

I'm am confusing myself too much worried

vital vale
#

😂

dusk portal
#
    price=models.DecimalField(decimal_places=2 ,max_digits=1000)
#
TypeError at /admin/products/product/
argument must be int or float```ig error is in ^^ price instance
opaque rivet
#

@lapis basalt Specify what you want more details on

dusk portal
#

@opaque rivet sir help tmg_cry_sad

#

btw done corey's playlist and i have 2-3 doubts to ask , others things are done made todo app , blog app with all features sign up sign in profile and all , now doing CodingforEntrepreneur video then will do a e-commerce website development on own then django react rest framework

opaque rivet
#

@dusk portal i cant help with that, you're passing a arg to your Product model which isn't a float or int

dusk portal
#

how can i fix bruhh!!!

opaque rivet
#

You get the error after saving the object in the admin dashboard?

dusk portal
#

yes

#

after saving yes @opaque rivet

#

can u tell what should i change here

#

and what is a boleean field it founds tricky

opaque rivet
#

@dusk portal so what are you inputting into the fields once you save the object?

dusk portal
opaque rivet
#

So you're just saving an empty object?

dusk portal
#

when i click on products not even any objects on whole Product app model in admin

dusk portal
opaque rivet
#

Okay... so is this what you're doing?

  1. In django admin, you select product model
  2. Create a new object
  3. Save that object without inputting anything into the fields

?

dusk portal
#

1st option when i click on product model

#

it at that time immediatly

#

throw error

lapis basalt
#

Please how to post a list of str in a flask rest api

opaque rivet
#

I'd nuke the db, delete all of the migrations, and start the db afresh

lapis basalt
#

if request.method == "GET":
word = request.args.get("word")
nb_links = request.args.get("nb_links")
select_filter = request.args.get('filter')
else:
word = request.json["word"]
nb_links = request.json["nb_links"]
select_filter = request.json('filter')

#

like this but words instead of word

#

with words a list

opaque rivet
#

Delete db

#

Delete migrations

dusk portal
#

oh

#

wait a sec

#

lemme do

#

done @opaque rivet

opaque rivet
#

Ok, then just remake your db

#

@dusk portal fixed?

dusk portal
#

Yes @opaque rivet

lapis basalt
#

Please how to post a list of str in a flask rest api
example:
if request.method == "GET": word = request.args.get("word") nb_links = request.args.get("nb_links") select_filter = request.args.get('filter') else: word = request.json["word"] nb_links = request.json["nb_links"] select_filter = request.json('filter')

like this but words instead of word

with words a list

opaque rivet
#

@lapis basalt not sure what you're trying to do, what do you mean by "post"?

#

Can you rephrase

rigid folio
#

Hi, I have a question on Django admin page. I'm trying to register a form (not model) into the admin page, but my form consists of variables like user_id / =kwargs['initial']..., and as a result there's error when i try to add/edit the admin form because i have not passed this variables in... How do i do it ? :/

lapis basalt
#

Thxx

opaque rivet
#

You can convert a list of strings into a JSON string, then send this in the body of a POST request. I assume you're using JS so use axios.

lapis basalt
#

@opaque rivet thxx a lot . I am working on a full api

#

with flask

#

I want to send a bulk request based on a list of words sent by the client

#

after that how to recover please the input sent by the client as a usual list

#

I found a solution or that

#

json_obj = json.loads(json_string)

storm estuary
#

anyone can help me?

#
def register(request):
    form = RegisterForm(request.POST or None)
    if form.is_valid():
        username = form.cleaned_data.get("username")
        password = form.cleaned_data.get("password")

        newUser = User(username=username)
        newUser.set_password(password)

        newUser.save()
        login(request, newUser)

        return redirect("index")
    context = {
        "form": form
    }
    return render(request, "register.html", context)```
tiny furnace
#

I don't really know much about Django - is form.cleaned_data supposed to by a dict?

#

Can you send the RegisterForm class?

storm estuary
#

I don't know, I just started django

#
class RegisterForm(forms.Form):
    username = forms.CharField(max_length=50,min_length=8,label="Kullanıcı adı")
    password = forms.CharField(max_length=24,label="Password",widget=forms.PasswordInput)
    confirm = forms.CharField(max_length = 24,label="Confirm Password",widget=forms.PasswordInput)

    def clean(self):
        username = self.cleaned_data['username']
        password = self.cleaned_data['password']
        confirm = self.cleaned_data['confirm']

        if password and confirm and password != confirm:
            raise forms.ValidationError("Parolalar eşleşmiyor.")

        values = {
            "username",username,
            "password",password
        }
        return values
native tide
#

Can someone help me setup pm2 on my vps so i can start my website with pm2 start ... im using Ngix Gunicorn and flask

storm estuary
#

i think i did

#

let me check the database

tiny furnace
#

Honestly I'm not sure what the problem is - try looking into the value of form.cleaned_data

#

By the looks of the error, it is returning a 'set', which you cannot perform the method 'get' on

#

Ah I think I figured it out - potentially

#

form.cleaned_data = ```python
values = {
"username",username,
"password",password
}

#

because that is returned from your clean method

#

However, values's data type is a set. Did you perhaps mean to put colons instead of commas in your values variable?

#

So perhaps you meant ```python
values = {
"username": username,
"password": password
}

storm estuary
#

ahh

#

i forgot use ':'

tiny furnace
#

exactly

storm estuary
#

thanks for helping

tiny furnace
#

np

ember eagle
#

Django 3.2, Python 3.8, any idea why random.randint(0,255) isn't working? i'm so confused.

olive grove
#

Running into an issues with an app route I have for my website.

The Try-Except-Else block isn't doing what I want it too.

It's supposed to see if di or dn is equal to None then handle the TypeError and return user.html as the rendered template if there is an error, otherwise render thx.html

It currently is catching the error, then running the else statement, then crashes a minute later even though I added an exception handler for the TypeError, so it shouldn't be crashing, and should run the except statement instead of the else.

I'm not sure what I'm doing wrong.
Here's the route:

def addrec():
   if request.method == 'POST':
      try:
        dn = request.form['dn']
        di = request.form['di']

        with sqlite3.connect("tinker.db") as con:
            cur = con.cursor()
            cur.execute("INSERT INTO users (user, user_id) VALUES (?,?)",(dn, di) )
            
            con.commit()
            msg = "Record successfully added"
            print(msg)
      except:
         con.rollback()
         msg = "error in insert operation"
      
      finally:
        if di == '425477636333240331':
          return render_template("result.html", msg = msg)
          con.close()

        try:
          if ((dn == None) or (di == None)):
            msg = "Please fill the required fields"
        except TypeError:
          return render_template("user.html", msg = msg)

        else:
            return render_template("thx.html", msg = msg)
            con.close()```
thorn igloo
#

it evaluates the comparison regardless of whether what i'm comparing is none or not

#

basically,

try:
   if ((dn == None) or (di == None)):
     msg = "Please fill the required fields"

this will never cause an exception unless dn and di are not defined

warped heart
#

so im playing with fastapi, and im trying to spread some routes across files,

code:

from endpoints.contributors import contributor_router

api = FastAPI()

api.include_router(contributor_router)

only problem here is that its not including the routes from the router

eternal blade
#
import random
random.randint(0, 255)``` This should work
hollow apex
#

Hey guys so idk whats gotten into it, it was working just fine but after pasting some html code it happened like this, it does not render/display at it should

#

its django

#

it should display something like this

#

nvm I juts fixed it

dapper belfry
#

Do you use docstrings in a Django project?

zenith river
#

[HELP] Anyway to covert Django app to an exe? I want to serve my Django app as a desktop app and I can't figure out a way to do that, anyone with any experience?

timber thorn
#

should I make shadows in darkmode ?

#

I mean white shadows, or is it too much?

#

it looks ok or?

calm plume
timber thorn
#

I think its too glowy you know what I mean

#

I now have it black, its inspirated by a guy from github, he said its more realistic 👍

vestal hound
#

you want import random to use it that way

daring osprey
#

so here's what I'm trying to do:

i want to embed a python console BUT I want my python code to automatically start (without the user pasting in the code) and I want this to be embedded into a html website

I found this code online:

 <iframe
  
      style="width: 640; height: 480; border: none"
      name="embedded_python_anywhere"
      src="https://www.pythonanywhere.com/embedded3/"
    ></iframe>

but all this is doing is creating an iframe with the console website. Is there any way to achieve what I'm trying to do?
also not sure where to post this

real rapids
#

how can i make a online ide ?

azure kestrel
#

Hey, is anybody familiar with flask? I am trying to route to a custom login page, but I'm having no luck

#

It just goes to the default login page

ember eagle
#

wrong person, but whatever, thanks @vestal hound

real rapids
#

Or @app.route("/login")?

azure kestrel
#

wait

#

redirect

#

what redirect are you referring to

#

@real rapids

#

I used @app.route('/login')

#

it's flask security that is giving me the problem

#

i know how to override the html page now, but i'd like to be able to actually have it use my routing method

native tide
#

@dusk portal dms

ionic raft
#

Django project tree and runserver question in #help-honey

native tide
#

in fact, I believe Discord runs on electronjs. so everything you see in your GUI is just css and js on an html page

#

what should i do to make the background img fit to enitre screen

primal thorn
#

is the django rest framework needed to connect the backend and front end when using something like react or can i do it without

#

for eg i wanna loop through one of my tables with react, is the rest framework needed ?

inland oak
#

if you extract table from some database

#

you need either 1) django rest framework... 2) or some alternative, Node.js for example

#

node.js is the most closest javascriptish thing for react devs

#

I am too much familiar with python to choose anything else though

#

in theory you can even use direct access from frontend to database

#

but... it would need having public login/password to database

#

probably

#

well, nothing prevents to use it, if there is frontend library for direct sql connections

#

except for how much big code complexity and security issues will be with this solution.

#

how much database would be have to tuned to setup correct permissions%

#

it is probably all possible, but you would have to be probably a monster of databases

#

and considering that it will remove from you architecture as code... (since I don't think there are advanced enough libraries for that) it is going to be messy

#

better creating normal backend (Node.js, or Django rest framework or whatever else backend offers) and pulling data from it

lucid lotus
#

Is this a right channel to ask about django?

#

I've having a problem in displaying the profile image.

gentle ingot
#

@ember eagle I forgot to update you. I say screw it and just made a new webpage for my small scripts lmao. Looks nice though.

inland oak
desert estuary
#

so i wanna do a thing when the user visit the site his first visit should render a certain template to modify some data (to change his email or password and other stuff )after it's submitted in the database it should render the homepage idk how to express it here

@app.route('/user',methods=["GET","POST"])
def user():
   formi=Userform()
   return render_template("User/info_gathering.html")
dusk portal
#

oh

#

what is booleanfield

#

what is manytomany relation

#

now i have completed corey schafer's playlist and made some apps like contact form simple app todo app blog app with user sign up login and forgot password

#

how can i get to more advanced to make own projects

lyric granite
#

guys i need some help and suggestions regarding django and stuff if anyone there please tell

desert estuary
# dusk portal how can i get to more advanced to make own projects

so firstly how did you finished that tutorial it's soo confusing i started with him and he start to make some weird stuff instead of making stuff clear from the beginning and also i guess you should go and check the documentation with some forums on the internet

lyric granite
desert estuary
lyric granite
#

cz i am also seeing it and ik its confusing but he is really good with explaining

#

oh ok idk about flask

desert estuary
#

i started with flask and he confused my fucking ass

lyric granite
#

F

#

flask has jinja right so its confusing ig

#

i mean django has it too but flask too

dusk portal
#

all 8

#

then 2-3 simple proj

#

then corey vid

#

1 month

lyric granite
#

oh nice

#

he is doing flask tho

#

if any food django dev online i need some suggestions so please ping me up if someone willing to help

native tide
#

Hello help me pls

#

I need setup nginx with flask python on windows 10

#

?

inland oak
native tide
covert cargo
#

best solution is to move to linux

inland oak
#

indeed.