#web-development

2 messages · Page 194 of 1

limber flower
#

It takes the things and stores it and when the next time i use the same username (yeah, only that) says that account already exists.

wooden ruin
#

form = UserRegisterForm(request.POST)

this takes the POST data submitted and uses it to create a UserRegisterForm, which is a ModelForm. that's why it calls form.save()

#

so lets say i have a model that looks like

#
class User(Model):
  username = models.CharField(...)
  password = models.CharField(...)
  age = models.IntegerField(...)
  email = models.CharField(...)
limber flower
#

Yea.. I have made one like this

wooden ruin
#

right

#

so the example uses what's called a ModelForm

#

lets say you have an html form that's something like

<form method="post">
  <input type="text" name="username">
   ...
</form>
#

and so on

#

in a view, i could access their data values by using request.POST["username"], right?

limber flower
#

yes

wooden ruin
#

so if i wanted to create a user like this, i could do

if request.method == "POST":
  username = request.POST["username"]
  password = request.POST["password"]
  email = request.POST["email"]
  age = request.POST["age"]
  user = User.objects.create_user(username=username, password=password, email=email, age=age)
  user.save()
limber flower
#

ye

wooden ruin
#

that's very, very tedious and repetitive, because you take the data from an object, put them into individual variables, and use those variables to create another object just to save it

#

modelforms come in handy and are quite useful because they make the process alot simpler and faster

limber flower
#

Hmmm okay, I guess

wooden ruin
#
if request.method == 'POST':
        form = UserRegisterForm(request.POST)
        if form.is_valid():
            form.save()
#

all it takes when using a modelform

limber flower
#

So, where does the .save() option save the data?

wooden ruin
#

into the database

limber flower
#

And how do I access that, or it can't be accessed?

wooden ruin
#

you can't access it just by opening it because it's unreable to humans (hard to phrase)

#

you access it by querying for it

#

in django this is very easy

#

user = User.objects.get(username="pancakes")

limber flower
#

Hmm

wooden ruin
limber flower
#

I see, and the authenticate() function, it's just like User.objects.get? or something else?

wooden ruin
#

the authenticate function just checks whether a set of user-provided credentials are valid

#

for example it checks if your username/password combo is correct

#

if it's correct, it returns the corresponding user object that match the credentials. else it returns None

limber flower
#

Ok, so .authenicate() will verify if info's correct
User.objects.get() will get the info
.save() will save it to a db.
And there's no option to manually delete the entered data

#

right?

shadow vine
#

‘’’py
def test():
print(“is this working?”)

#

‘’’py
def test():
print(“is this working?”)
‘’’

limber flower
#

O ok

wooden ruin
#

django docs come in really handy at these sorts of things

shadow vine
#

!code

lavish prismBOT
#

Here's how to format Python code on Discord:

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

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

limber flower
#

lemon_sweat.

shadow vine
#

‘’’py
def test():
print(“is this working?”)
‘’’

wooden ruin
#

python3 manage.py shell

from <app>.models import <whatever models u wanna use>

shadow vine
#

Help

limber flower
#

Ohhh, got it 👍

limber flower
lavish prismBOT
#

@limber flower :warning: Your eval job has completed with return code 0.

[No output]
limber flower
#

Like this

shadow vine
#

!e
‘’’py
def test():
print(“poo poo”)
‘’’

lavish prismBOT
#

@shadow vine :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 1
002 |     ‘’’py
003 |     ^
004 | SyntaxError: invalid character '‘' (U+2018)
shadow vine
#

iOS doesn’t have a back tick key

#

Shoot

limber flower
vestal hound
#

hold on '

limber flower
#

I had my own form

#

But.. django didn't take it

#

and when i'm using the pre-made ones

#

It doesn't put the css

#

You know, what can I do?

wooden ruin
# limber flower How will I add css to the pre-made forms?

you can add html attributes to each input if you like

class MyForm(forms.ModelForm):
    class Meta:
        model = MyModel

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.fields['myfield'].widget.attrs.update({'class': 'myfieldclass'})
#

it's a bit tricky with model forms but that's the idea

native tide
#

how do you move an img to the top middle
part

native tide
#

Yeah i got it with flexbox

ember parcel
#

is there a way to define a new set of allowed http methods for filters? i.e. /api/ can have get, post, but i want /api/?filter= to only have get. the solution im thinking of right now would be to create another endpoint /api/filter/ but i wanted to know if i could avoid that

meager anchor
ember parcel
#

using the django rest framework and the filter comes specifically from the django-filter library

#

in general though, how do people usually do this? do they just leave it as is?

stark tartan
#

(Django authentication ) i am going to build the authentication like **Zoom Meet ** In which those who create the meet have to register thought username,email,password and other who wants to join just have to type(Full name ,email(optional)) and join directly the meet

  • i also have to save to database which user join the meet
  • the blocked users

Any suggestion for this type of user models

fickle garnet
#

@stark tartan what is is that you're missing ?

outer falcon
#

Hey, I am trying to create a synchronized output for everyone using websockets in django. I have the websocket class set up, and I tried starting a "game loop" from __init__() in the websocket consumer. However, that cause a bunch of issues, and I found this: https://stackoverflow.com/questions/42564524/are-django-channels-websocketconsumers-stateless
Anybody know how I could achieve the synchronized output for everyone since I can't achieve it from within the class?

stark tartan
mortal pike
#

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

outer falcon
#

hey anybody know how to start a single loop for django that is always running? I was told somewhere that using AppConfig.ready() will run multiple times if and when I serve it with gunicorn and daphne (gunicorn for http, daphne for websockets)

sonic island
#

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

rain wasp
#

Anyone know how to host django website on netlify?

tepid wren
#

netlify is only good for hosting static websites without backends. If you want a free option with a backend just use heroku.

calm plume
olive tiger
stable sentinel
#

anyone has some straight forward guide on rendering a django form in bootstrap5 modal?

#

I am not sure how to do it, everything renders in the modal except the {{ form|crispy }}

stable sentinel
#

it's a CRUD form that works just fine when I open on separate page. Though when I try and render it as a modal only the hardcoded HTML renders without the input fields

stark tartan
stable sentinel
#

I am new to web development I have loads to learn. Sorry if this is a bad question

#

I have done some digging and all seems to be pointing to AJAX

stable sentinel
#

though than again, no worries, I came across something that might help, just need to wrap my head around it 😄

#

just haven't done much jQuery stuff yet, so I'll have to sink my teeth in to that a bit before I go on with this

tender crater
#

Currently developing a multi-tenant application in Flask (requirement is to support thousands of tenants). There are no strong concerns over security so haivng a single db around will be just fine. Now, I am left wondering which would be a sensible approach:

  1. Having multiple schemas inside the same db
  2. Partition a table by a tenat_id key and bake the multi-tenant logic inside
    I am wondering if having many schemas in a a single db might hamper admin tasks and backups.
inland oak
#

nothing is better than docker to make multi tenancy in the smallest applied efforts

tender crater
inland oak
#

Multi tenancy problems are solved

#

U have full db for each db

#

Lightweight as much as containers can

#

The problem is... If u need it persistent ;b
This solution fits only when u don't need db being persistent

#

Then gcp with its reliability and probably much better features is more preferable

inland oak
#

If money would allow... Then raised separated dbs with terraform

#

Sufficient isolation for multi tenant thing is important parameter too

#

Or even probably we could just plan tables to work for different apps

#

Then we could have same db and tables for your multi tenant thing

#

Actually... U know... I don't know your problem enough to make the right choice

#

We have too many options, and each one is having its own pros and cons

tender crater
#

Hence I think your idea of isolating things a bit more with schemas is probably the way to go

inland oak
tender crater
#

Cheers mate, thanks for the good chat

native tide
#

anybody want to pair program on flask? i'm a beginner but have ruby experience. Mostly for the motivational aspect and that we can code review each others work etc.

solid raft
native tide
river raven
#

Does anyone have experience starlette's SessionMiddleware? I'm using it atm, but having issues since I'm load balancing across multiple containers, so the different containers have different secret keys. Is the fix here to just hardcode a key with an env var or is there something more elegant/secure?

dense ice
#

Can someone here please help me with my django application using heroku

#

like it says its deployed

#

and it works

#

but when i go on the website

#

it says this

river raven
#

To explain further, the issue arises when a user gets redirected and it get's served by another container

dense ice
#

I have been working on this for literally 3 hours

#

and it keeps not wokring

#

if anyone could help

#

it would mean alot

#

@river raven could u possibly help

river raven
#

Sorry no, I have never used heroku

dense ice
#

shit

#

do you have any

#

other like hosting services

#

i can use

#

for django applications

#

that worked for you @river raven

river raven
#

We host our PythonDiscord site using linode

#

I've used linode personally, and they're pretty good

dense ice
river raven
#

You can get servers and then set it up to host django, yea

native tide
#

FastAPI vs Flask vs Django which one's better (currently using fastapi because I've heard it's the fastest)

olive tiger
#

I know django the best, so it would always be the best for me

golden bone
#

If you know FastAPI and it's working well for you then great.

calm plume
#

I like FastAPI for smaller projects, and django if I'm combining many many things

olive tiger
olive tiger
pallid lily
#

What is the difference Between Flask and Django if some one can illustrate (Features, technology..)

calm plume
#

Flask has less features out of the box, while Django comes with everything built in

pallid lily
#

In flask i can handle for example ban IP and detect number of requests and this issues or is it only and best be done with a Django

#

i mean like website security against DDOS, Scrapers etc..

olive tiger
#

flask - not, afaik

pallid lily
#

Okay Thx alot

inland oak
#

django with its train on rails approach will save you from it, as long as you just use its features, instead of trying to reinvent the wheel

pallid lily
#

Okay thx

inland oak
#

btw, there is third option, FastAPI is quite popular too in job market

#

although I should say its second option

#

because flask is not really valid for jobs, only django and fastapi are

pallid lily
#

so basicaly Flask is an educational and introductory for python web development, Django and FastAPI are products for business

inland oak
#

at the moment, yes

#

but it can change

native tide
#

question

#

what is a good cheap vps provider

#

I'm getting bored of waiting for Kimsufi to restock their $5.99 vps'

#

I need a cheap vps to run a MediaWiki install for a wiki I'm creating about Team Fortress 2 cut content

woeful ridge
#

Didn't know that there was a web development channel on here

#

this is awesome

native tide
keen shoal
#

dm if somebody can make me website

coarse yoke
#

Hello everyone. do you have experience with gzip on heroku?

broken harness
#

aahhh

#

getting error

#

;-;

#

Using django. when I try and do this:

def save(self):
        super().save()
        
        img = Image.open(self.image.path)
        
        if img.height > 300 or img.width > 300:
            output_size = (300, 300)
            img.thumbnail(output_size)
            img.save(self.image.path)
``` I get error. But without it, no error.
golden bone
# inland oak 👍

Don't listen to the haters, Flask is even more widely used In production than Django (https://www.statista.com/statistics/1124699/worldwide-developer-survey-most-used-frameworks-web/). I know a number of people who use Flask more than Django professionally. It's just that you only use Flask for APIs and other very simple things. Django is more appropriate for full-featured websites

inland oak
#

uh. flask is used even in mine, all right.

#

Django is still leader anyway ;b

vestal hound
#

cries in Angular

inland oak
#

Django protects from mistakes better ;b

inland oak
#

tried Svelte already, its tutorial and easiness to use is totally awesome

vestal hound
#

Vue disgusts me

#

tbh

#

#SORRYNOTSORRY

inland oak
#

Svelte is definitely awesome ;b

vestal hound
#

if I ever

inland oak
#

clean, and easy peasy

vestal hound
#

got back into webdev

#

I'd look @ it for sure

inland oak
#

with Svelte I learn what's pure CSS/javascript

#

instead of the...

#

framework shenanigans above it

#

Svelte shenanigans are learned within one day hour

golden bone
sand musk
#

Hi, any Flask pros here? I have two routes, one returning some text, and the other an image. Could I return these at the same time, as to not double the computation time?

dire urchin
#

so i never stumbled upon the helpful advice of using virtual environment for your django app so now i have a bunch of stuff in my requirements.txt that i don't know if i actually need, do i just delete it and go the manual way of adding requirements?

#

or is there an easier way to sort out the mess

sand musk
golden bone
dire urchin
#

got it, thanks

stark tartan
eternal thunder
#

Is there any chance mui is available for outside of react?

dire urchin
#

do i add the venv folders to gitignore or not?
edit: yes i should gitignore them

inner nest
#

night everyone, so i am newbie here, and i try to return redirect back, and i reseach but im not find them, can anyone help me

#

?

thick pilot
#

Looking for advacne DRF dev?

native tide
#

Hello any good book or website where i can learn web developement im pretty new to python and i did tried and did probably basic concepts still trying to learn more of it so i would like a book suggestions

latent cosmos
#

[Q] Beautiful Soup / Web Scrape - easy:
Hi, how to scrape 2x tags: a with class linkme and p with class price?

HTML:
<div class="offer">
  <a class="linkme">The item aaa</a> || <p class="price">$100</p>
</div>

So how to scrape "The item aaa" from <a class="linkme"> AND price from <p class="price">

obtuse yarrow
#

i need someone to create a little software

#

if some can mp me 😄

pallid lily
#

@latent cosmos response.xpath("//div[@class='offer']/a/text()").get() +" "+response.xpath("//div[@class='offer']//p[@class='price']/text()").get()

inner latch
#

Can you make a fully featured/stylized website using Django?

#

Without the use of CSS/Javascript?

dense slate
#

JS is for functionality mostly.

#

You can build without JS for the most part, as long as you don't need live changes to the page (aka without refresh).

#

I don't know what you mean by fully featured, but you likely will need css and js to do that.

inner latch
#

Thank you - the 'feature' I'm aiming for is dynamic updates on the page without having to refresh, so it looks like I have to dive into JS - what is the benefit of using Django over just a dynamic webpage using CSS and JS?

dense slate
#

It's not either or, they go hand in hand.

inland oak
dense slate
#

If you're asking why Django and not something else for the backend, then that depends on what you want the backend to be able to do and what you need out of it.

inland oak
#

well...

#

technically the person can go without javascript as well

#

POST requests bring sufficient minimal interactivity to the site

#

we just return to the fully server side sessional times

#

but knowing CSS and javascript (and frontend framework) will make a magnitude better work ;b

#

without it, you will be in a certain limitations in what you can do

dense slate
#

I'm pretty sure you can't make live changes without JS.

inland oak
dense slate
#

A change to the DOM without refreshing.

inland oak
#

but all those Forms work without JS by default

inland oak
#

we return to the old times where we need request per every change ;b

#

it still allows using Forms for logins, Submitting msgs, having videos and e.t.c.

pallid lily
#

the Ai chat bot is made by Django or is it made by javascript

inland oak
#

no idea how your AI is made, just some simple python logic I guess for example?
but chat is made with web sockets stuff, as example to make it Django Channels + Javascript are required both

solid raft
#

I am working on a front end application in reactJS. Which is hosted with a domain A.com. A few images are being served from a different static content end point B-test.com. The domains are different for test and prod. B-prod.com.
Now I don’t want to inject this as an env variable during compile time. Is there an alternative ?

runic lodge
#

Working on basic html templating and Jinja 2 is throwing the error

jinja2.exceptions.TemplateAssertionError: block 'title' defined twice
#
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>{% block title %}{% endblock %} - My Webpage</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="">
    </head>
    <body>
        <!--[if lt IE 7]>
            <p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="#">upgrade your browser</a> to improve your experience.</p>
        <![endif]-->
        <p>TEST</p>
        <!-- {% block title %}{% endblock %} -->
        <script src="" async defer></script>
    </body>
</html>
#
{% extends "base.html" %}
{% block title %}Home Page{% endblock %}
#

Not sure why though

#

somehow works but its not feeding any errors

#

when i run through the documentation which means user error on my end

#

but im not sure what im getting wrong

#

Help?

runic lodge
#

@vestal hound

lilac solar
#

@runic lodge the title is defined twice the second one is commented out of the HTML but not out of the template, it's a common mistake. To comment in Jinja you need to use {# #}

runic lodge
#

@lilac solar oh i see i thought i was referencing it in the first html doc, how do i reference it in the html doc?

#

{ self.title} ?

lilac solar
#

You have it defined twice in the base.html which is what Jinja is complaining about. Line 6 & line 17

runic lodge
#

check

#

but if i wanted to inherit it into the
<title>{% block title %}{% endblock %} - My Webpage</title>
block how would i go about doing that

lilac solar
#
{% extends "base.html" %}
{% block title %}Home Page{% endblock %}

This is correct

runic lodge
#

would i just leave the title blank then?

lilac solar
#

What are you trying to achieve?

runic lodge
#

I want "homepage" shown in the second block of code to render in the title position of the base layout

#

located within the head of the first bit of code

lilac solar
#

In that case, just delete or correctly comment out line 17 in base.html

#

if you want to comment it correctly it need to be <!-- {# block title #}{# endblock #} --> instead of <!-- {% block title %}{% endblock %} -->

runic lodge
#
{% extends "base.html" %}
{% block title %}Home Page{% endblock %}
{# block content #}
<h1>Test But bigger</h1>
{# endblock #}
#

so like this?

#

Let me re-reference what im trying to do.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>{{ self.title }}</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="">
    </head>
    <body>
        <!--[if lt IE 7]>
            <p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="#">upgrade your browser</a> to improve your experience.</p>
        <![endif]-->
        <p>TEST</p>
        <!-- {% block title %}{% endblock %} -->
        <script src="" async defer></script>
    </body>
</html>
#

The position of self.title needs to be populated with what is in the index.html file, this one.

{% extends "base.html" %}
{% block title %}Home Page{% endblock %}
{# block content #}
<h1>Test But bigger</h1>
{# endblock #}
#

Sorry dots not meaning to be condescending.

lilac solar
#

Your inherited template is fine. Your base.html needs to be as follows:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>{% block title %}{% endblock %}</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="">
    </head>
    <body>
        <!--[if lt IE 7]>
            <p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="#">upgrade your browser</a> to improve your experience.</p>
        <![endif]-->
        <p>TEST</p>
        <script src="" async defer></script>
    </body>
</html>```
runic lodge
#

ahhhhh i see now

calm plume
runic lodge
#

@calm plume all good, it's fixed

#

@lilac solar thank you, this is better, so html inheritance in jinja 2 is referenced sequentially like a stack

#

as in it cannot be unordered or can it?

lilac solar
#

I think it can be unordered, but the identifiers for blocks must be unique across the template inheritance tree/stack

runic lodge
#

got it, it's probably good practice to have it ordered

#

I wish there was a way to give points here, appreciate it none the less

night junco
#

Hello! I’m legit new to web dev and trying to get use to this how would I add images? I’m on windows

#

And fonts

marsh knoll
#

Hey

#

for images, use the <img> tag

#

Google fonts has pretty good dev help

#

Here's an example with both

<html>
  <head>
    <style>
      @import url('https://fonts.googleapis.com/css2?family=Roboto&display=swap');

      .some-class {
        font-family: 'Roboto';
      }
    </style>
  </head>
  <body>
    <p>Not in roboto</p>
    <p class="some-class">Epic text in roboto</p>
    <!-- Add file path or url to image src -->
    <img src="/img.png">
  </body>
</html>
#

@night junco

night junco
#

Legend!

woeful ridge
#

Hello, feel free to dm me the answer or just say it in here, but what classifies the use of a database on a website and what would you use for it. In this scenario it an online airplane parts company, needs to be able to have its customers place orders for parts in the store inventory

weak nacelle
#

is a sqlite db recommended for a site handling over 100 r/w requests at the same time

tepid lark
#

per second? SQL can do insane read perf, but writes absolutely not

pallid lily
#

try to make PostgreSQL as your database

#

because having website in same server with database might make it easy for hackers to delete and obtain your data

calm plume
#

I doubt that

#

Having a website and a database together could actually be a really good thing

#

The connection would never even have to leave the server

tepid lark
#

Yeah, especially if you have low to medium traffic

uneven mauve
#

I'm new to django
Im a bit confused about whether I should create a separate app for user authentication
Or just do everything in the same app
I'll eventually have to extend the users model and link it with a database in another app
How do you decide whether to create a new app for something 🤔
also ping me if you reply please thanks

fluid olive
#

Hello, Can somebody please help me with a Bootstrap Hamburger Icon Toggling problem? The menu is not toggling when clicked.

cursive pine
#

I wish to take a 800x800 SVG from my index.html and send it to the bottom of the same page as a thumbnail when user clicks a button, and allow the user to generate another SVG. and so on... Any tips on where I should be looking for such examples?

#

Alternately, its even ok to create a slide-show with subsequent images.

inner nest
#

can anyone help me to make a resize image system, when uploading image using form, in django python, I've tried about 4 or 5 ways, and it doesn't work (im newbie)

waxen forge
#

I'm trying to modify a client that allows/facilitates it. It allows me to edit the css but not the html.

This is the html: html <div class="sc-hBEYId jgcjMZ"><span class="detail"><span class="author">Fenton</span><div class="sc-fodVek Qskju"><time>Today at 04:09</time></div></span><span class="_markdown_8b8eo_2"><p>What's the class for the blob thing behind server icons?</p> </span></div>

This is what i'd like, essentially:

    background-image: url("https://i64.servimg.com/u/f64/12/23/10/57/glitte10.gif");
}```
#

ping on response pls

dusk sonnet
#

Hey, How can i fix this? under my body's size is related to the content of the table. the more row in the table the bigger the body gets and thats why its making so much uneeded white space under the footer thats not used for anything

#

i tried doing the following but nothing changed

body, html {
height: 100%;
}
humble needle
#

Is there anything wrong with using a REST API for a chat app? Or is a websocket based approach better

humble needle
dapper tusk
#

you do probably want websockets just to have messages appear instantly, rather than after the client asks

#

REST does have a resource type for server push, but it works using callback urls, which won't work for a chat app

humble needle
#

So will it work with REST or do I need to learn websockets

dapper tusk
#

it is possible, but websockets are the better tool to use

dusk sonnet
humble needle
dusk sonnet
waxen forge
#

Can someone give me a comparison on using flask vs quart for executing bot commands?

sturdy crater
#

i need a mentor

#

anyine can teach me

dusty moon
#

CSS question:
I have an <a> element which i'm trying to style.
I use float to move it to the right, and position to center it vertically.

Here's its code:

a {
  position: relative;
  line-height: 0;
  padding: 10px;
  float: right;
  top: 50%;
}

Weirdly enough, top does not respect the padding, meaning the text is not centered.

Although, i've came up with a solution:

top: calc(50% - 10px)

The only problem with it is that i want it to automatically take padding's value, and put it in the calc() function.

Any ideas?

thorn flame
dusty moon
#

i see. welp, thanks for your help.

urban whale
#

Hi there! I have a general question about full-stack development: I'm building a frontend SPA with React and on the backend side I have Azure API Manager that serve the endpoints I need in a REST Api, discussing with my team we thought about the idea of inserting a web server as a middleware between the API and the frontend, the main purpose is to hide the API endpoint url and maybe use it to do some fields checks, is this middleware server useful in your opinion or it's only a resource/performance waste?
Thanks in advice!

lilac solar
lilac solar
hazy wolf
#

hey i was wondering if there was someone who knows how django-helpdesk works and could help me in VC i have some trouble with writing my problems down bcs my English is bad so could someone help me ? (if there's someone who knows how to speak french too it could help me a lot but i still can understand English)

quiet blade
#

Hi, I need to create First In - First Out Queue with Django Rest Framework,
where multiple users will have access to endpoint which returns first created Contact Instance, but there can't be the situation where few users will get the same contact.

So i figured out that i could edit a single field "task" on every get request and add "if" to queryset which would return only the contacts where task field is equal None/ "New".

Meanwhile if any user would send get request to that endpoint then the task field would be set to "Processing" or something like that.

But im not sure how to achieve that. I wish i could do that like this

Contact.objects.filter(task="New").first().update(task="Processing")

Is it possible with signals? or i should check the guide about tool called Celery? or something else i don't know about?

opaque valve
#

not sure if this is a right area for this but how do I send out and receive HTTP requests?

mystic crater
#

Hey guys, I just hosted this website that's built using Flask + React. The idea is that it would allow users to comment easily & quickly on YouTube videos that have blocked their comment section. I'd like to hear your thoughts (i'm thinking whether to continue working on this or no). Here's the link: https://make-a-comment-on.herokuapp.com/

severe current
#

hey guys

#

do you think its better to create a website with flask

#

or django?

cursive pine
#

Any front end devs in the house?

golden bone
#

!d requests

lavish prismBOT
wooden ruin
past lion
#

Hello guys

#

How to store images in database?

#

So i can get them with id

#

In django

mystic wyvern
native tide
#

Does anyone know how we can fetch data from the database using dropdowns in Django?

#

I tried so many things nothing's working

mystic wyvern
dusk portal
#

@mystic wyvern hey wanna try to help me

mystic wyvern
dusk portal
#

so the thing is , u know what are signals.py right?

#

@mystic wyvern

past lion
past lion
mystic wyvern
mystic wyvern
past lion
mystic wyvern
#

you just save the dir in the database the not the image

past lion
dusk portal
#

so the thing when im adding any post from admin panel without thumbnail , it's loading default img by signals

#

but when im upload new post without thumbnail from frontend it's throwing error

#

while when i upload it thumbnail on both admin and frontend it works fine

#
@login_required
@cache_page(60*2)
def notes_upload(request):
    if request.method=='POST':
        title=request.POST.get('title')
        subject=request.POST.get('subject')
        desc=request.POST.get('desc')
        thumbnail=request.FILES.get('thumbnail')
        file=request.FILES['file']
        author=request.user
        entry=Notes(title=title,subject=subject,desc=desc,thumbnail=thumbnail,file=file,author=author,published_on=datetime.now())
        print(thumbnail)
        entry.save()
        messages.info(request,'Notes updated successfully!')
        return HttpResponseRedirect('/')```
as admin is working fine == models.py is correct
#

problem is surely here or in html

mystic wyvern
mystic wyvern
fair agate
#

Is this the section to ask about something like web scraping and CSS selection of scraped data?

dusk portal
#

i can help

#

for these ezzz part

past lion
fair agate
#

so for something like the following:

quotes.css('span:not([class])').css('small.author::text').get()

is it possible to combine those two .css() into one somehow?

dusk portal
#
ValueError at /notes/5/
The 'thumbnail' attribute has no file associated with it.```
main prob with this error is it saves info to db then shows error + it renders on home page it's slug and when i go to paigiated shows error
mystic wyvern
mystic wyvern
past lion
mystic wyvern
dusk portal
mystic wyvern
dusk portal
#
<main id="upload">
        <div class="title">
            Upload Notes
        </div>
        {% if messages %}
        <div class="error">
            {% for msg2 in messages %}
            {{msg2}}
            {% endfor %}
        {% endif %}
        </div>
        <form method="POST" enctype="multipart/form-data" >
            {% csrf_token  %}
            <div class="field">
                <label for="title">
                    Title
                </label>
                <input type="text"  name="title" placeholder="video's title" required name="title">
            </div>
            <div class="field">
                <label for="subject">
                    Subject
                </label>
                <input type="text"  name="subject" placeholder="Subject">
            </div>
            <div class="field">
                <label for="vid_desc">
                    Description
                </label>
                <textarea  id="desc" name="desc" cols="30" rows="10"></textarea>
            </div>
            <div class="field">
                <label for="thumbnail">
                    Upload Thumbnail
                </label>
                <input type="file" id="thumbnail"  name="thumbnail">
            </div>
            <div class="field">
                <label for="file">
                    Upload Notes
                </label>
                <input type="file" required  name="file" accept="pdf,doc,docx">
            </div>
            <br>
            <button class="submit">Upload</button>
        </form>
</main>```
#
        <form method="POST" enctype="multipart/form-data" >
<div class="field">
                <label for="thumbnail">
                    Upload Thumbnail
                </label>
                <input type="file" id="thumbnail"  name="thumbnail">
            </div>``` focus here
#

ig here only cez from admin working fine

mystic wyvern
#

i guess something that is when you write here thumbnail=request.FILES.get('thumbnail') and you didn't give it a thumbnail it show error bcz it cant get any data

#

in another hand, there is nothing to get

#

@dusk portal
i think you can do something like that thumbnail=request.FILES.get('thumbnail',Flase) to skip if there not any data

turbid horizon
#

If I want to learn flask, what languages should I learn to be able to make a website

mystic wyvern
turbid horizon
mystic wyvern
native tide
#
def members():
    try:
        print(request.form["invite"])
    except:
        return render_template('members.html')```

This is my app.py its flask and html, bnut i cant get to find the invite link

```<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Detective Voke's API</title>
        <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;700;900&display=swap" rel="stylesheet">
        <link rel="stylesheet" href="/static/style.css">    
    </head>
    <body>
        <header>
            <div class="wrapper">
                <div class="logo">
                    <img src="" alt="">
                </div>
            <ul class="nav-area">
            <li><a href="http://127.0.0.1:5000/">Home</a></li>
            <li><a href="http://127.0.0.1:5000/panel">Panel</a></li>
            </ul>
            </div>
            <div class="welcome-text2">
                    <h1>
            Discord Members<span></span></h1>
            <h1>Enter Invite</h1>
            <form method="POST" action="/members/api">
                <div class="memberinput">
                    <input type="text" name='invite', size="50" height="50" color="transparent">
                    <h1>Enter Key</h1>
                <div class="memberinput">
                    <input type="text" name='key', size="50" height="50" color="transparent">
                    <h1> </h1>
                </div>
                </div>
                <ul class="nav-area">
                    <li><a href="">Start</a></li>
            </form>
            </ul>
            </div>
        </header>

    </body>

</html>```
#

idk why no owkr

#

tbhj

real sparrow
#

look into how to render an html template through flask

native tide
#

wdym

real sparrow
#

can you past the error you are getting?

native tide
#

@app.route("/members", methods=['GET', 'POST'])
def members():
try:
print(request.form["invite"])
except:
return render_template('members.html')

@app.route("/members/api", methods=['GET', 'POST'])
def member(invite, key):
return invite, key

#

but when i fill it in

#

it just resets as its sending to the render_template

#

sure

real sparrow
#

you havent defined the job_elements object @native tide

#

@native tide what happens if you remove the try/except and just leave return render_template('members.html')

#

can you not get from it?

#

you need to define the job_elements object, how you do it is up to you.
what tutorial are you following?

native tide
#

thats what it was

#

but it just doesnt work

#

lmao

real sparrow
#

nice

#

that makes sense

#

ah dang

#

youre missing this line job_elements = results.find_all("div", class_="card-content")

#

its in the tutorial

native tide
#

it just resets me to the same page

#

...

real sparrow
#

how are you testing the POST?

native tide
#

if request.method == "POST":
invite = request.form['invite']
print(invite)

real sparrow
#

how are you performing the request?

#

python requests? or just your prowser?

native tide
#

<form method="POST" action="/members">
<div class="memberinput">
<input type="text" name='invite', size="50" height="50" color="transparent">
<h1>Enter Key</h1>
<div class="memberinput">
<input type="text" name='key', size="50" height="50" color="transparent">
<h1> </h1>
</div>
</div>
<li><a href="">Start</a></li>
</form>

real sparrow
#

browser*

#

that not the request, that's the return.

#

Are you connecting to the endpoint with your browser?

native tide
#

yes

real sparrow
#

try removing the "GET" and leave just the POST

native tide
#

i just need to get the invite so i can send the invite into a channel

real sparrow
#

in the flask file

native tide
real sparrow
#

and still just GETs?

native tide
#

'method not allowed'

#

i cant even open it

#

yes im doing maths

#

shush

real sparrow
#

but if you leave the GET then it allws that request?

native tide
#

no.

#

thats not how it works

#

lmfao

pallid lily
#

is there a difference between request.form.get("invite")

#

and request.form['invite']

native tide
#

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Detective Voke's API</title>
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;700;900&display=swap" rel="stylesheet">
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
<header>
<div class="wrapper">
<div class="logo">
<img src="" alt="">
</div>
<ul class="nav-area">
<li><a href="http://127.0.0.1:5000/">Home</a></li>
<li><a href="http://127.0.0.1:5000/panel">Panel</a></li>
</ul>
</div>
<div class="welcome-text2">
<h1>
Discord Members<span></span></h1>
<h1>Enter Invite</h1>
<form method="post" action="/members">
<div class="memberinput">
<input type="text" name='invite', size="50" height="50" color="transparent">
<h1>Enter Key</h1>
<div class="memberinput">
<input type="text" name='key', size="50" height="50" color="transparent">
<h1> </h1>
</div>
</div>
<li><a href="">Start</a></li>
</form>
</div>
</header>

</body>

</html>

pallid lily
native tide
#

its not that

#

the request is a get request

#

when it is cleartly a post request

#

<form method="post" action="/members">

#

hence

#

post

pallid lily
#

try to do a print statement

native tide
#

if request.method == "POST":
invite = request.form['invite']
print(invite)

#

...

pallid lily
#

did it return a value?

native tide
#

127.0.0.1 - - [12/Oct/2021 20:06:05] "GET /members HTTP/1.1" 200 -
127.0.0.1 - - [12/Oct/2021 20:06:05] "GET /static/style.css HTTP/1.1" 304 -
127.0.0.1 - - [12/Oct/2021 20:06:07] "GET /members HTTP/1.1" 200 -
127.0.0.1 - - [12/Oct/2021 20:06:07] "GET /static/style.css HTTP/1.1" 304 -

#

see

native tide
past lion
native tide
#

it returns as a get request.

pallid lily
#

then try to do it as request.form.get('invite')

#

and see if any changes

native tide
#

omg

#

its sending as a GET REQUESTS

#

this is if its a POST REQUEST

#

SEE

#

it wont change shit

#

...

pallid lily
#

my friend

#

just try it

dense slate
#

wow

native tide
#

it wont change anything

#

i know how to code.

#

and that wont change shit

dense slate
#

@native tide Maybe you shouldn't ask for help since you know how to code.

pallid lily
#

no one is questioning how you code my friend

native tide
#

yall are useless as shit

#

ong

dense slate
#

Glad to help when someone is courteous about it. Go fix it yourself.

real sparrow
#

yeah fuck that guy, can't even explain his problem

pallid lily
# native tide aight

def signup():
if request.method == 'POST':
username = request.form.get('username')
email = request.form.get('email')
password1 = request.form.get('password1')
password2 = request.form.get('password2')

#

this is how i do it and it works well

native tide
#

its my html code

#

i use the exact same thing

#

its in the html file

real sparrow
#

@native tide maybe you added it too early? add it under the "results" variable

#

no I was talking about Detective Voke

#

did the error at least change?

pallid lily
#

do i need to learn OOP well befor starting Django and Tkinter apps for better understanding and code?

#

if so i need good references please ❤️

real sparrow
#

its find_all not findall

calm plume
#

Can you show the code and what's around it?

#

Specifically, what's before the class that you defined?

real sparrow
#

you have issues in your loop, it should be job_result not jobresult

#

for job_element in job_elements:
title_element = jobelement.find("h2", class="title")
company_element = jobelement.find("h3", class="company")
location_element = jobelement.find("p", class="location")

Should be

title_element = job_element.find("h2", class="title")

calm plume
#

Glad I could help 🙂

real sparrow
#

Nice!

dense slate
#

At least for Django

pallid lily
#

i mean for clean functioning and code

real sparrow
#

happy hacking 🙂

dense slate
pallid lily
#

I mean i saw some people make tkinter codes for like top level etc in classes

dense slate
#

That's how Django functions.

pallid lily
#

it was so clean

dense slate
#

I don't know about tkinter.

pallid lily
#

okay thanks

dense slate
#

Classes are an option, sure.

pallid lily
#

for Javascript some times you need to disable javascript from the browser to see if the data you need is rendered by JS or not

#

if it is use splash or Selenium

carmine cipher
#

Hello guys !Can someone tell me what best programming language for backend ?

pallid lily
#

Python (Django,FastAPI and Flask) , Javascript (Node.js)

pallid lily
#

np

real fossil
#

Hey all, can you help me with my poorly explained issue that I will give you more information about but you'll have to fight me for it each time and then I can get mad and tell you off because I don't understand your answer/am incapable of thinking laterally

dusk sonnet
#

Hey, anyone got an idea on how to fix this? my body doesnt seem to be full size and only gets bigger the more content there is. Iv tried the following CSS but it doesnt change anything. Iv been stuck for a whole day on it. ```css
html, body {
height: 100%;
}

crude delta
#

Hey

dusk sonnet
wooden ruin
#

what are things i should look for to put in a personal website? i wanna make a portfolio but i'm not sure how to showcase myself

lucid marsh
#

I have an instance hosted, i want to run a flask app on a specific port, when i tried using app.run(host='0.0.0.0', port=1234), i cannot access it with public IP, anybody know how to use the public IP?

frank shoal
#

Are you forwarding the port?

#

Does your host whitelist the ports? It may give you a PORT variable to use.

lucid marsh
#

i accessed it from my browser with http://ip:1234, but i used sudo ufw allow 1234/tcp

frank shoal
#

You port forward in your router config

lucid marsh
#

i have it hosted on aws

#

i have another flask app running with apache2, it works fine and i can access it

frank shoal
#

I believe in aws, all outside traffic goes through the reverse proxy

#

Or at least you should configure it to do so

lucid marsh
#

hmm

#

oh btw, when i use 0.0.0.0 as host in flask, it hosts in the local IP shown

#

tried to use the public ip too, didnt work, it gives error no.99

frank shoal
#

Is it the public ip, or the local ip?

#

You can't bind to an address you don't have

#

0.0.0.0 just means bind to all interfaces

lucid marsh
frank shoal
#

Is it the ip that shows up in the ip addr command?

lucid marsh
#

the ip that shows up in ip addr is just local, 127.0.0.1

#

ok no its not the ip that shows in ip addr

frank shoal
#

Then how are you connected?

lucid marsh
#

i use ssh -i auth.pem ubuntu@ip

frank shoal
#

127.0.0.1 is just localhost

lucid marsh
#

ik

lucid marsh
#

Theres 3 IPs, the localhost (127.0.0.1), the local IP, and the public ip (which can be accessed anywhere) right?

#

i can access my instance using ssh and with the public ip

#

i want to host flask app in the public ip, but in a specific port

native tide
#

hey, I was trying to deploy a machine learning model on Django. can anybody help me

native tide
#

I have a trained PyTorch and I want to deploy it using Django. when I give both solvent and solute it should predict the energy

#

I have made this interface using forms in Html. when I search on the internet they are saying do the serialization. It's so confusing

#

html page

#

please point out what should i need to do next

indigo kettle
#

@native tide I don't know what the internet means by serializing, I don't think you need to do anything like that

#

you could make your <form action="" method="POST"

#

and then edit your homepage view to handle a POST and GET request

#

then you can get your form inputs using request.POST.get('solute') or something like that

#

you need to name your inputs too <input name='solute'

native tide
#

what should i need to keep for action=??

native tide
#

'directory recivin gthis input I am not rendering any page i was just taking response from two fields in models

pallid lily
#

your not rendering the page

#

your giving it a pathway to send this data to

#

and in the < input attributes

#

you should enter any name for input to identifiy it as key later such as name='input1' id ='input1'

#

so when you call for it on python side you type in this code request.form.get('input1')

#

<input name = 'email' id='email type='email' placeholder='Please enter your email'></input>

#

this is an example..

broken harness
#

Is someone able to help me upload my django site to my website? I am using godaddy

white wigeon
#

any decent library which can escape JSON strings to be safely output into JS from Python? e.g. var foo = "</script>" causes issues so just json.dumps("</script>") is not enough

dusk portal
#

hey

#

still having same issue

white wigeon
native tide
#

how do I make django auto-refresh the server when a non-django script is updated?

#

in this case brython

#

oh nvm I'm an idiot

dusk portal
native tide
#

I was part of a very talented team

#

but I meant it jokingly, I'm actually a genius

pallid lily
#

Team champions?

#

where can i watch this !

sudden bolt
#

is django required to build a py web?

harsh helm
#

How good is Cloudflare for hobbyists

mint marsh
#

Hello guys i got a question :
Say i got a Comment section with x amount of likes and i have two different people viewing that website at the same time,

Say one of them likes it , so the database updates ,

How do i make it so it re-renders the amount of likes to the other person

#

My question is , How to change what a user sees on his screen when the data in the database changes or updates

south stump
#

Hi, i have a bunch of questions, im currently learning Spring-boot (java) and Angular, I was suggested to check out some python implementations because my project wont need the overhead and scalability that those have.

I have seen a tiny bit of DJango and heard about something called flask but this can apply to any in particular.

Here are my questions:

is it something better to avoid if using an OOP design?

can they use html/css/scss?

^ follow up can they use bootstrap?

is it limited to a specific DB?

Is there adequate security, user registration, role management included or 3rd party imports that support it?

Is it reliable?

Apologies for the spam, just trying to get a feel/opinions before I dive into research - i've already swapped out technology like two/three times'

south stump
inland oak
# south stump Hi, i have a bunch of questions, im currently learning Spring-boot (java) and An...

is it something better to avoid if using an OOP design?: Flask, Django, Fast API and any other framework and python are fully OOP compatible.
can they use html/css/scss?: Yes, although it is backend framework. While they can work with html/css, they aren't really meant for extensive javascript usage.
Better to turn them on into REST JSON API mode and use it appripriately with frontend frameworks (Angular/React/Vue and e.t.c.)
Django REST: https://www.django-rest-framework.org/
P.S. i don't know about scss, because never used it.
^ follow up can they use bootstrap? Yes. I already did it. Essentially python frameworks give you only Jinja2 templating syntax {{variable}} {{for each element}} write stuff {{end for each}}. But nothing from javascript syntax (no mounts and e.t.c.)
is it limited to a specific DB? Flask/FastAPI has no limits. Whatever database connecting library you will install, that you can use, I could recommend SQLAclehmy for flask for example.
in django case... it involves a lot of 'train on rails' approach, it has already inbuilt DB library Django ORM. From SQL database family better to use compatible with with the library dbs (for example postgresql is prefered u ll get the most amount of features, although MySQL and others you can use too). NoSQL dbs have no limits, but better to see Django Cache compatible ones.

Is there adequate security, user registration, role management included or 3rd party imports that support it? Django is certainly battery included with everything. Flask is definitely not, it follows microframework approach.

Is it reliable? Sure. I would recommend Django, it helps to make as less mistake as possible, as long as you use inbuilt "train on rails" libraries.

late hollow
#

Is there a good Django or Flask course/content that’s a bit challenging? I’ve heard about Corey Schafer but I want to hear what are y’all’s thoughts

#

I prefer less handholding

dense slate
#

Challenging meaning you know the basics?

#

Any particular thing about it you want to learn how to use?

past lion
#

Hello guys!

#

I have a problem

#

How to get data from database in django and loop through it to get image, name , surname and other data

#

i want to loop this

<ol>
    <li><img src="../../media/{{img}}">{{ first_name }} {{ last_name }}</li>
</ol>
``` to get list of everyone in the database
lusty relic
#

**Authorization using Casbin for a Flask Project
**
I am using flask-jwt-extended for authentication in my project. Right now, I have few custom fields like isAdmin, isSuperAdmin in user table for authorization purpose.
However, I want to have dynamic roles and have RBAC in my project. While trying Casbin, I can see it is capable to do RBAC. But, even if I use Casbin I have to create the policy table for Casbin from my project and the policy table should be dynamic.

I was wondering, if all Casbin really does is look into policy table and say whether an entity is accessible or not, then why use it altogether, I can just write few functions to go through my DB and perform the authorization.
Please kindly let me know if I am missing something.

Also, how scalable is the combination of Flask, Casbin and MongoDB if anyone has tried this stack? I was thinking to use Pymongo Adapter for Casbin.

foggy plover
#

Hey! Has anyone ever deployed a Flask App on Docker? I am able to make the docker image, it's even running but not showing on localhost. I am currently using Windows 10 OS

south stump
jaunty depot
#

hey guys
I'm trying to center a table in a modal, but unfortunately I don't quite get how to make it. I tried "text-align" in css, but it is not helping. I had to implement padding-left with 11%, but I don't get what and why it is 11% (of what?). Could anyone explain to me how to do this?

<div class="modal-content">
            <span class="close">&times;</span>
            <table>
                <th>In our offer we have:</th>
                <tr>
                    <td>X</td>
                </tr>
                <tr>
                    <td>Y</td>
                </tr>
                <tr>
                    <td>Z</td>
                </tr>
                <tr>
                    <td>1</td>
                </tr>
                <tr>
                    <td>2</td>
                </tr>
                <tr>
                    <td>3</td>
                </tr>

            </table>
        </div>```

table {
display: block;
padding-left: 11%;
margin-left: auto;
margin-right: auto;
width: 40%;
display: inline-block;
background-color: rgb(6, 163, 40);
/* text-align: center; */
border-radius: 5px;

}```

 .modal-content {
    background-color: #97adc2;
    margin: auto;
    padding: 20px;
    border: 1px solid #888;
    width: 80%;
    border-radius: 10px;
    font-family: sans-serif;
    font-size: 20px;
    text-align: center;
  }
#

in this state it looks like the table is in center, but when I expand or compress the site, it's going off, it's not in the center like the rest of the site

#

text-align: center in table style does nothing

#

in 50% zoom it looks like this:

#

how to make it in the center for good?

#

the green color of the table is just for reference, to see where are the borders of table

native tide
#

hello

native tide
#

i need help

#

my css doesnt wrk

proven falcon
#

!paste

lavish prismBOT
#

Pasting large amounts of code

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

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

native tide
#

i need help

#

my css doesnt work

#

helpppp pls

shadow vine
#

where is your static directory located?

#

also if using flask, recommendation is to use {{url_for('static/path/to/file/', filename='filename.ext')}}

#

in your html template

native tide
#

from flask import Flask, render_template

app = Flask(name)

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

@app.route('/about')
def about():
return "<h1>About Page</h1>"

if name == 'main':
app.run(debug=True)

#

it worked before until i changed my code around

#

only the code

shadow vine
#

can i see your index.html?

#

directly from your source code?

native tide
#
<!DOCTYPE html>
<html>
  <head>
    <title>Clicker</title>
    <meta charset="UTF-8" />
    <link rel="stylesheet" href="static/css/style.css" />
    <script src="static/js/myjs.js" type="module"></script>
  </head>
  <body>
    <div class="cont">
      <label id="progresslabel" for="file">Progress to Level</label>
      <progress id="file" value="" max=""></progress>
      <!-- bar stays same length even after changing max which is good -->
    </div>
    <div class="btn-wrap">
      <button id="btnLevel" data-func="levelUp" disabled>
        <img src="static\images\level.png" />
      </button>
      <button id="btnCookie" data-func="click">
        <img src="static\images\cookie.png" />
      </button>
      <button id="btnMenu" data-func="menu">
        <img src="static\images\list.png" />
      </button>
    </div>

    <!-- # is for id and . is for class-->
  </body>
</html>

shadow vine
#

change your href when linking stylesheet to: {{ url_for('static/css', filename='style.css') }}

#
{{ url_for('static/css', filename='style.css') }}
#

this is the preferred way of referencing static files within your templates

spark dagger
#
app = Flask(__name__, static_url_path='')
shadow vine
#

excellent

stark tartan
#

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

shadow vine
stark tartan
#

Or React will fine

dim river
#

from flask import Flask, render_template, request
from flask_mysqldb import MySQL

app = Flask(name)
app.config['MySQL_HOST']: "localhost"
app.config['MySQL_USER']: "root"
app.config['MySQL_PASSWORD']: "password"
app.config['MySQL_DB']: "flasktest"
mysql = MySQL(app)

@app.route("/", methods=['GET', 'POST'])
def loginpage():
if request.method == 'POST':
userlogin = request.form
password = userlogin["password"]
email = userlogin["email"]
cur = mysql.connection.cursor()
cur.execute('SELECT * FROM details WHERE email = %s AND password = %s', (email, password))
details = cur.fetchone()
print(details)
cur.close()
return "success"
return render_template('loginpage.html') error :-MySQLdb._exceptions.OperationalError: (1045, "Access denied for user 'balla'@'localhost' (using password: NO)")
127.0.0.1 - - [13/Oct/2021 22:19:46] "POST / HTTP/1.1" 500 -

spark dagger
stark tartan
#

@spark dagger shall I try it then we will discuss

dim river
spark dagger
#

correct this one

#

enter you db username and password

#

it will work

stark tartan
#

Django channels

tepid wren
stark tartan
#

I built a test application with DC and Webrtc it works.. now I am working with Google meet like project

#

Is anybody is Webrtc expert are you @spark dagger ??

shadow vine
#

not me lol

stark tartan
tepid lark
#

Would it be sane to just use a sqlite database in a Docker container plus dynamodb backed sessions ?

dusty moon
#

CSS question (again(:
I have a <div> and an <a>.
I'm trying to use padding to vertically stretch the <a>, I'm doing that with 100% unit. With height it respects the height, but not centers the text...

tepid lark
#

We're talking maybe a hundred users in total for this important but low volume app.

native tide
tough oriole
#

Hi
I'd like to start a project together with a buddy. I'd like to practice backend development, as this is a huge black-box for me. The only question I've is how do I deploy the backend so that my buddy can develop the UI for the frontend using the provided interfaces / APIs / endpoints?

runic lodge
#

Has anyone tried to host with heroku before?

#

I'm trying to push a node.js file with yarn gulp and a few other dependencies but it's not deploying the front end. The log information is as follows

-----> Building on the Heroku-20 stack
-----> Using buildpack: heroku/nodejs
-----> Node.js app detected
       
-----> Creating runtime environment
       
       NPM_CONFIG_LOGLEVEL=error
       USE_YARN_CACHE=true
       NODE_VERBOSE=false
       NODE_ENV=production
       NODE_MODULES_CACHE=true
       
-----> Installing binaries
       engines.node (package.json):  v10.19.0
       engines.npm (package.json):   unspecified (use default)
       engines.yarn (package.json):  unspecified (use default)
       
       Resolving node version v10.19.0...
       Downloading and installing node 10.19.0...
       Using default npm version: 6.13.4
       Resolving yarn version 1.22.x...
       Downloading and installing yarn (1.22.15)
       Installed yarn 1.22.15
       
-----> Restoring cache
       - yarn cache
       
-----> Installing dependencies
       Installing node modules (yarn.lock)
       yarn install v1.22.15
       [1/4] Resolving packages...
       [2/4] Fetching packages...
       info fsevents@1.2.4: The platform "linux" is incompatible with this module.
       info "fsevents@1.2.4" is an optional dependency and failed compatibility check. Excluding it from installation.
       [3/4] Linking dependencies...
       [4/4] Building fresh packages...
       Done in 13.90s.
       
-----> Build
       
-----> Pruning devDependencies
       yarn install v1.22.15
       [1/4] Resolving packages...
       [2/4] Fetching packages...
       info fsevents@1.2.4: The platform "linux" is incompatible with this module.
       info "fsevents@1.2.4" is an optional dependency and failed compatibility check. Excluding it from installation.
       [3/4] Linking dependencies...
       [4/4] Building fresh packages...
       warning Ignored scripts due to flag.
       Done in 4.48s.
#
-----> Caching build
       - yarn cache
       
-----> Build succeeded!
 !     This app may not specify any way to start a node process
       https://devcenter.heroku.com/articles/nodejs-support#default-web-process-type
-----> Discovering process types
       Procfile declares types     -> (none)
       Default types for buildpack -> web
-----> Compressing...
       Done: 40.6M
-----> Launching...
       Released v5
#

But I'm not seeing what errors it's throwing at me.

#

The only one is

info fsevents@1.2.4: The platform "linux" is incompatible with this module.
stable sentinel
#

in django form what attr do i need to set a default value to a MultipleChoiceField? and to have the said field disabled? (greyed out)

calm plume
runic lodge
calm plume
#

I've never used gulp, so I doubt I'd be of much help

runic lodge
#
{
  "name": "particle",
  "version": "1.0.0",
  "description": "An awesome app.",
  "main": "index.js",
  "engines": {
    "node": "v10.19.0",
    "yarn": "1.22.13"
  },
  "scripts": {
    "start": "gulp"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "browser-sync": "^2.26.3",
    "gulp": "^4.0.0",
    "gulp-concat": "^2.6.1",
    "gulp-csso": "^3.0.1",
    "gulp-imagemin": "^5.0.3",
    "gulp-plumber": "^1.2.1",
    "gulp-sass": "^4.0.2",
    "gulp-uglify": "^3.0.1"
  }
}
#

ah okay

runic lodge
#

So it deploys on localhost 3000 but not 5000

#

so weird

carmine cipher
#

Hello guys , can someone tell me what best frameworks for JavaScript and CSS?

runic lodge
#

Best for simplicity and power is VUE, most syntactically complicated is Angular, most widely used is React.

sonic hearth
#

hey folks - i am using flask trying to setup some user signup, getting an issue when i import routes file into my main app

from flask import Flask, render_template

app = Flask(__name__)

#Routes
from user import routes
#

and routes file is just this

from flask import Flask
from app import app
from user.models import User

@app.route('/user/signup', methods=['GET'])
def signup():
    return User().signup()
#

when i try to load /user/signup page i am getting 404

calm plume
runic lodge
#

so progress made... basically im able to host it at local host 3000

#

but it needs to be at 5000

#

in order for it to properly function on heroku

native tide
runic lodge
#

which makes no sense because in order for an application to work it needs to have a client facing ports of either 80 or 443.

jaunty magnet
#

when making a fullstack app, do yall usually start with the frontend or backend? Making a chat app and not sure if I should making my models, views first or start with basic react layout and build backend as I build out my react side?

carmine cipher
runic lodge
#

Thats how development teams work and thats how I choose to approach it but feel free to choose what you want

jaunty magnet
#

like all the views I need and which ones

runic lodge
jaunty magnet
#

django views like do I need a get view for this page or a full crud view for another page blah balh

runic lodge
#

That tells me nothing

jaunty magnet
#

Like if I click chatroom ill need a GET view because it needs to grab all the messages from that chatroom model, but I'll need to probably delete messages too. So it's hard to visualize all the cases of views ill need without the frontend, but im new to django so im guessing its my current mindset

calm plume
#

Or sometimes vice versa

#

So that it lets me visualize it, while still making sure both are being worked on

jaunty magnet
calm plume
#

Yeah, pretty much

jaunty magnet
runic lodge
# jaunty magnet Like if I click chatroom ill need a GET view because it needs to grab all the me...

Backend is what you do with the user data.
So take login information, security will be important. So when a user signs up or enters a password you want to store that information in a database. I recommend sqllite for your case at the moment. Import that data and store it then work on retrieval.
You can then build out the client facing backend Django and feed that information to your client facing front end html and css.
I made a diagram to help me visualize whats occuring which may help you.

#

I would take a step back and visualize what you want to do. Look at the broad concepts of the design. What do you want to do, then break it down into bite sized chunks of information.

#

Just replace flask with Django in the above diagram.

jaunty magnet
runic lodge
zinc ferry
#

how does css define discords window title?

#

even in the dev console it seems its title isnt changeable

calm plume
#

Assuming you're talking about the desktop client

zinc ferry
zinc ferry
#

it was like this

calm plume
#

I have no idea how BD works

zinc ferry
#

thanks for the help anyway 👍

native tide
#

how do i redirect to another page using Javascript

#

maybe window.location?

#

but it doesnt work

#

for me

rare nimbus
#

Try

#

window.location.href

native tide
#

mk

#

ty worked

#

im so dumb

rare nimbus
#

you ain’t

#

Might be able to help

#

With your upcoming question

#

@low pasture you going to ask the question then?

low pasture
rare nimbus
#

😑

valid crane
#

i have a meld component and the flask's flash function does not work after successful registration, everything's fine and working and i think it's because of context issues but i don't know what else to do

class RegistrationForm(Component):
    def save(self):
        self.submitted = True
        if self.validate():
            form = self.form
            #generate hashed password for the password
            hashed_password = bcrypt.generate_password_hash(form.password.data).decode('utf-8')
            
            user = User(
                    first_name=form.first_name.data,
                    last_name=form.last_name.data,
                    username=form.username.data,
                    email=form.email.data,
                    password=hashed_password
                )
            db.session.add(user)
            db.session.commit()

            flash('Your account has been created!', 'success')
            return redirect(url_for('user.login'))
#

heres the template

{% extends "layout.html" %}

{% block title %}Register{% endblock %}

{% block content %}
    {% meld "registration_form" %}
{% endblock %}
tepid lark
#

Does anyone here use or have experience with Pyramid?

#

I'm evaluating frameworks for an SPA backend. I've tried Django and Flask and they both have their ups and downs.

#

I only wish Django didn't so tightly couple the User model to the ORM. ohhh

calm plume
#

I've never used Pyramid, but can I just take a moment to promote FastAPI? It's really easy to use, but does things right.

tepid lark
#

Flask, very nice for small projects, easy to dig yourself into a hole of bad design.

#

I guess I hadn't considered FastAPI for this, it seemed very focused on well, APIs.

calm plume
#

Isn't that what you'd typically want for an SPA?

#

Or did you have something else in mind?

indigo kettle
#

you can customize the user model in django as well, does that not work for you?

tepid lark
#

no, that's it, I just didn't see anything aside from api key or oauth auth and we're stuck with SAML.

indigo kettle
#

you should be able to use sso with django just fine

tepid lark
#

yeah, I have a working server rendered Django app.

#

some of this is driven from a cost prospective, it would be nice to not have to provision an rds instance just to handle django users.

indigo kettle
#

fair

tepid lark
#

it looks like the sessions are extensible in that way, at least

#

because there's only maybe ~100 people in an org using this, i considered just using sqlite in the django docker container

#

oops, we redeployed? just recreate you on the next login or when we see your session

indigo kettle
#

there's no other persistent data you'd need stored in a database though?

tepid lark
#

oh there's plenty, just those databases already exist

indigo kettle
#

so this app is just going to be a middle man to make calls to other apps?

tepid lark
#

pretty much

indigo kettle
#

I see

tepid lark
#

i'd hope whoever has to touch it after me would find django easier than whatever homebrew we came up with

#

but I'll check out FastAPI too

indigo kettle
#

fastapi does seem pretty cool

#

also the sqlmodel orm wrapper around sqlalchemy that the same guy made

#

typehints to define db columns? :mindblown:

tepid lark
fallow temple
#

hi

#

I need an open source django web demo

#

Does anyone have one?

pallid lily
fallow temple
#

ok thank

dusk portal
#

@eternal blade hey

dusk portal
#

i am working with signals.py when im adding any post from my admin panel without adding img it renders it by signals.py (that's what i want ) but when i am not selecting img and adding post (from frontend)

#

it's adding post to db

#

but when i open post it throws error

#
ValueError at /notes/6/
The 'thumbnail' attribute has no file associated with it.```
#

so ig models are correct as it's working from db

#

problem is in my views or my html

#

one thing that i noticed more is when i add from admin panel it adds default.jpeg automatically , but when i add post from frontend it leaves that field empty

queen nest
#

Hey, I am making a Django application with opencv. I am using Websockets to establish a real time connection between Python and JS. What I need help with is to send Images from python to JS in real time. I tried encoding image and sending but the decoding is not working properly. Can anyone provide a basic code snippet for Python (image encoding) and JavaScript (decoding)?

pallid lily
gilded talon
#

my next message is propbably going to get me banned

native tide
#

Then... don't send it?

gilded talon
#

Just use HTML/CSS/JS instead

#

oh wait im still alive

#

this was unexpected, thank you

native tide
indigo kettle
#

since you have a serializer with fields password2 and old_password with model=get_user_model

#

the serializer is trying to save user.password2 and user.old_password

#

which aren't actually fields.

#

I've never used a serializer for change password form, I'm not sure if this is a good use of them

#

I would just use django forms

#

it might be possible to set required=False on password2 and old_password but still validate them normally and then in your validate method, right before you return attrs, do attrs.pop('password2') and attrs.pop(old_password)

#

because you don't actually want the serializer to try to save those onto your model

dusk sonnet
#

hey, How can i place images under each other? i wanna place "arsenal" and "westham" right under "manchester city" and "liverpool"

native tide
#

guys i have a weird css problem can someone help

#

overflow:clip is not working with images but only on phones

#

it works on pc even when i scale it the same size as a phone

#

how it should look

#

how it looks only on phones

#

CAN SOMEONE HELP ??

#

PLS

dire urchin
#

if i'm using s3 buckets for user file upload, how big of a deal is setting the bucket to be public? i feel like aws is really trying to discourage me from doing that

#

actually let's not xyz around the problem, what i'm trying to do is set up uploaded files' urls to never expire, which seems to happen because of query string authentication (i think)

hollow anchor
#

hello, i have a python program to do but im biig noob, can someone help me ?

queen nest
swift wren
#

does anyone know how to log out a user who was logged in using google authlib

#

im using flask and flask_login

#

when i go to current_user

#

it shows the account that i logged into like way back from

#

even if i log out

#

the logout_user() works

#

but when i login using another google account

#

it still shows the same one

pallid lily
queen nest
native tide
# queen nest Hey, I am making a Django application with opencv. I am using Websockets to esta...

I did what your talking about but used vnc and got the framebuffer data. sounds like you're trying to do it with screen shots. but the canvas code in my example should show you how to unpack pixel data from a websocket... https://github.com/byteface/vnc2browser/

GitHub

an experiment with vnc, python, websockets and html canvas - GitHub - byteface/vnc2browser: an experiment with vnc, python, websockets and html canvas

queen nest
native tide
#

we should go back to your original question i guess.

#

if it's just 1 image

#

save the image. on disk. the load it from teh server the way you would any image

queen nest
#

Not one image. Its like video streaming. So I process each frame and send it via channels.

native tide
#

you may need ffmpeg and not going to get a quick answer then depending on your needs as there will be things to learn

empty inlet
#

hello?

#

anyone with python flask knowledge?
need small help

queen nest
empty inlet
empty inlet
#

what error is this, why

#

Im I testing it correctly?

#

@queen nest

native tide
native tide
#

you should instead send a DELETE request to users

#

GET POST DELETE UPDATE is same as crud

empty inlet
#

ah

native tide
#

POST is creating something

#

DELETE deletes it

#

same endpoint

empty inlet
#

so what should I write in the

#

sql

#

it doesn't recongnize delete as it do for get/post

native tide
#

hmmm. u can do it easier.

#

dont try to code it

#

get an example that works. and start back to learning REST

#

you have 1 endpoint

#

/users

#

you can GET

#

to read info

#

POST to put info

#

DELETE to remove it

#

flask will have many REST API plugins. that set this up for you

#

and you may not have to do any sql. as the model will update based on the request type

#

i.e EVE is very good and can be done by configuration. but better for very static datasets

#

flask-restful was anothter. and paired with marshmallow will save you a lot of serialisaiton

queen nest
civic crater
#

hey

queen nest
civic crater
#

what is suggested using media url or static to store imgs. in Django
does they matter?

queen nest
#

Use Static

civic crater
#

okk

#

can i get a reason to use that

queen nest
#

I think it loads faster in browser

civic crater
#

ohh

dire urchin
#

I think you use media url for user uploaded files, and static for assets that are part of your website design

civic crater
#

how can i set rows of a textarea using django forms textarea widget

dire urchin
#

could be wrong I'm not too familiar with django

jovial cloud
# empty inlet

The error is that the req object(NoneType) is not subscriptable. This is because request.json is a method not an attribute. The correct code should be

req=request.json()
or
req = requests.json()
civic crater
vestal hound
#

or, more generally

#

any file that won't change without redeployment

civic crater
vestal hound
civic crater
#

Thanx

vestal hound
#

honestly

#

most "REST" APIs aren't really RESTful

#

in particular, when you have deeply nested data, a RESTful style can be complicated to do efficiently

hidden crown
#

Hi everyone. I'm trying to implement a feedback form on my Django error pages. Currently I've setup a custom 500 handler which I'm pointing to, but when I trying a 500 error, I need a function to give me the latest error log event id (I'm using sentry.io for those who are curious). But the custom 500 view is never triggered when responding with the 500 page, so I cannot inject the even_id as data into the template

#

anyone any experience with this?

jovial cloud
native tide
#

Hey folks,

I'm new to DRF (Django REST Framework) and just have setup my first usable POST endpoint, please see my code to create a new User object using POST:

views.py:

    @api_view(['POST'])
    @permission_classes([AllowAny])
    def user_create(request):
        if request.method == 'POST':
            serializer = CreateUserSerializer(data=request.data)
            if serializer.is_valid(raise_exception=True):
                serializer.save()
                return JsonResponse(serializer.data, safe=False)

serializers.py

    class CreateUserSerializer(serializers.ModelSerializer):
    
        class Meta:
            model = get_user_model()
            fields = ('user', 'password')
            extra_kwargs = {'password': {'write_only': True}}   # We don't want to show the hashed password
    
        def create(self, validated_data):
            password = validated_data.pop('password')
            user = User.objects.create_user(
                    validated_data['user'],
            )
            user.set_password(password)
            user.save()
            return user

So far so good. If I now want to create a User Object using POST it works fine for the first time. But if I send the same request twice, the second request just returns "Bad Request". Well that also makes sense as the User object is already existing.

It would be awesome if I would be able to catch this behavior somehow and return a message instead of a Bad Request.

Thanks in advanced

native tide
# vestal hound honestly

which REST api isn't restful?. you have an example of one of these data structures? (that isn't a json blob in the db)

vestal hound
#

but say your frontend wants a domain object

#

that involves several joins

#

okay

#

for example

#

you have an Album model

#

an Album has an M2M relationship with a Track

#

a Track has an M2M relationship with an Artist

#

in some cases, you want the Album with the full representations of its Tracks and Artists

#

in others, you don't

#

this is difficult to model RESTfully

vestal hound
#

one of the big things about REST

#

is HATEOAS

#

I very rarely see any sort of discoverability in a purportedly RESTful API

#

much more likely is

#

some sort of external spec (like OpenAPI)

native tide
#

i was about to say HATEOAS

#

but yes. people don't implement it. which is why eve was nice

#

how ever

#

couchdb invented a http interface

#

which mongo nicked and then put mongo query language on top

#

writing off the need to do apis for json dbs

#

as you can do REST direct to the db

#

my point being for that persons issue. is with a hello world flask restful. they wouldn't be even having that problem. they are at the delete user step

#

which is probably paragraph 3 on the intro docs

native tide
#

ye. to your point. in eve they were called 'projections' and joined records were configured by an exlude or include rule in the query. hence using a lib rather than trying to code your own is often better. as it acutally just does it for you and is easier.

vestal hound
#

not sure what Flask has for this

#

but

#

DRF does it p well

errant junco
#

So I'm new to Docker but not Django, and sometimes when I don't like the server I move it (manually), should I use Docker to deploy my django website?

strong oak
#

do you guys use flask or a framwork like django?

cerulean badge
#

logo_django2 how do you filter by object not in m2m?
like the opposite of Chat.objects.filter(members=user) where members is m2m field in Chat model

#

i just had to exclude instead lol

#

logo_django2 how do you add an object to m2m field to all objects (of other model) in queryset?
like below but with queryset

obj = MyModel.objects.get(pk=1)
obj.my_m2m_field.add(some_object)
native tide
#
  document.querySelector(".btn-wrap").addEventListener(
    "click",
    (e) => {
      if (!e.target.matches("button, button img")) return;
      const btn =
        e.target.tagName === "BUTTON" ? e.target : e.target.parentElement;
      game.buttonFunctions[btn.dataset.func]();
    },
    { passive: true }
  );
  
#

what does that code do

stark tartan
cerulean badge
stark tartan
#

What is dj

#

??

native tide
#

django?

cerulean badge
#

dj bravo

cerulean badge
native tide
stark tartan
native tide
#

not rlly

native tide
eternal blade
#

Hello, is there a way to set a default permission_classes for every view in django-rest-framework?

eternal blade
#

Thanks

eternal blade
eternal blade
native tide
#

Suggest a library that takes a PNG photo from an HTML file

indigo kettle
stark tartan
#

The better way is to make permission.py and import permission from their

frigid elm
#

Hey guys! Probably someone can help me!

#

How can I make a migrations if I wrote models not in models.py?

#

Follow me in the answer

hushed copper
#

What is the best way to use for scraping 2000 URL addresses?

indigo kettle
mortal pike
#

Quick question,
Why Am I getting the error name 'SERVER' is not defined
My View:

class RobotDetail(UpdateView):
    model = models.Robot
    form_class = RobotUpdateForm
    template_name = 'dashboard-home/robotdetail.html'
    robo = Robot.objects.get(pk=pk)
    PORT = robo.port
    SERVER = robo.server

My Model:

port = models.IntegerField()
    server = models.CharField(max_length=200, default='10.10.19', blank=True, null=True)
#

Plz Ping When Replying

dull isle
#

is it possible for python to interface with html?

dusk portal
#

how can i create a google forms like application

#

by django

#

where ppl can share link by creating there form and there will be mcq's

#

designed by the link sharing (admin/host of the form)

#

and it will contain responses same as google forms

#

@eternal blade

barren moth
#

how to write a mock api? eg I want to mock an api my program relies on for testing

#

any recommended libraries to best do that?

#

I want to have minimal dependencies, but also easiest to write

dusk portal
#

yes

#

u mean u wanna

#

limit the user

#

for sending requests

eternal blade
barren moth
#

so I'll make requests to a test server which doesn't do anything

pallid lily
#

may i ask what is does it mean when i do as following ```
def function(variable: int = 0):

#

def function(variable:int =0) => list:

frank shoal
#

You mean type hints?

pallid lily
#

yea

frank shoal
#

It tells you that the function expects an int and returns a list.

pallid lily
#

ohhh