#web-development

2 messages Ā· Page 180 of 1

clear bone
#

thats all i have haha

valid void
#

is django.contrib.staticfiles installed in your settings.py -> INSTALLED_APPS ?

velvet yew
#

Path looks correct so yeah check for the django.contrib.staticfiles

clear bone
#

yep it is

velvet yew
#

Hm

#

Can you show your full folder structure for the image?

clear bone
#

and this is in the base directory

valid void
#

I think you have to add a STATIC_ROOT that contains the path to your Static folder

velvet yew
#

The full django project path please

clear bone
valid void
#

Have you executed the collectstatics function from manage.py ?

velvet yew
#

Is the static in the app's folder?

clear bone
velvet yew
#

Move it

clear bone
broken mulch
#

how do I get the IP address of a request that I can request back some data?

valid void
#

Yes it is

clear bone
valid void
#

But it's working fine with Debug=True

#

For me

broken mulch
#

like I can do requests.get(the_ip)

#

maybe in headers?

valid void
velvet yew
clear bone
clear bone
#

wait no it is not

velvet yew
#

I just recreated the same and worked fine for me

clear bone
#

@velvet yew my project and app are on the same "level" in the directory

valid void
#

😮

dapper tusk
#

django.contrib.staticfiles will not serve static files when not in debug mode

valid void
#

Project and app are on the same directory ?

clear bone
velvet yew
#

That's how it should be

valid void
#

Not really, you should have project/project (setting.py etc.) and project/app1, project/app2 etc.

velvet yew
#

I'm rather confused at your directories let me double check

valid void
#

project/manage.py

velvet yew
#

Yeah that's what I meant

#

Just not sure it's what he meant

winter adder
#

Anyone?

broken mulch
#

when I visit that IP it's loadin forever

velvet yew
valid void
#

wdym ? @broken mulch

#

Show code

clear bone
#

C:\Users\Me\Desktop\alb2_rec\albumApp\static\albumApp

broken mulch
#

and I'm visiting another web server with that IP

#

when I type the IP i received in the browser (and with a correct PORT)

#

it takes too long to respond

valid void
#

I'm currently using an ubuntu VPS to dev my Django Application. There is no Apache installed, no Gunicorn or nothing. Just using the manage.py runserver ipserver. What is the best way for me to add a domain name to my django app ? Do I need a webserver (like apache or Gunicorn) ? Thanks !

opaque rivet
gritty cloud
#

you should type your domain name into your browser to test if it exists

#

then buy it from the person selling it

#

note that this takes real money

#

you can also go to sites like godaddy.com do get a domain

late creek
#

or you can just use a free domain on launch to save money

valid void
#

I used DigitalOcean to create a django Droplet and a Postgresql database

late creek
subtle sun
#

Flask gives the warning to not use it's built-in server in production. If my (open-source) package spins up a server local to the user, is that considered production ? In other words, do I need to include tornado , aiohttp or something similar?

sand glen
#

is there a way to pass the same variables through every render_template?

#

i have multiple pages that all rely on a variable that represents the current user session, and i have to pass it through every time

manic crane
#

django.core.exceptions.ImproperlyConfigured: Field name user,status is not valid for model Post.

#

someone please help

sonic heron
#

Hi everyone, I am new to FastAPI and web development in general. I am looking for a reference code structure for my project. I want to create a website and looking for some references on how to structure a web project with FastAPI. Any links/suggestions ?

valid void
#

Hey, I reinstalled my project, I imported everything from the other server, but in HTML file I can't use {% block %} etc. I have set my template dir in project settings. Do you have a solution ?

#

If I create a new HTML file into templates, it works, if I copy it from my computer with scp, it doesn't work

wispy ice
#

Hello

#

How to make a file download?

#

Im making print(filebytes)

#

But nothing happens

#

This is not working

native tide
#

can you post your code?

#

!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.pydis.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.

wispy ice
#

Check the link, is almost the same as the stack overflow one

#

I use python CGI

#

And sys.stdout(file)

#

Not print

#

But it does not trigger the download file

#

Im using lighttpd

#

Ubuntu

#

And python 3

native tide
#

it would be useful if you still could give us the code snippet

wispy ice
#

There is not much many code. I just add headers, and then stdout the file readed

#

And nothing happens

#

I expected a file downloading

#

Maybe it's impossible

#

I call the cgi-bin from a ajax/jquery post

#

And i want in response the file

native tide
#

do you see data from other prints

#

in response

#

to your request via cgi-bin

wispy ice
#

Yes

#

If i print text, the text is displayed in consile

#

F12 console

#

If i catch the response

#

So the program works, but not as intended

native tide
#

what do you see in response

#

can you post it and redact all sensetive data

wispy ice
#

In 12h ill return and post it to you @native tide

#

Ty for helping

#

Now ill go and sleep, my brain hurts

native tide
#

i might be off to sleep soon so dm me

#

if anything

ionic raft
#

Question. Anyone familiar with Django and class based views? I'm trying to use an UpdateView form to save to the DB. It works on a follow up Save, but not the first. I am only saving to the same object.
EDIT: I've got an idea...I either need to work with the form.instance properly or add a method to the model

valid void
#

My static files don't want to work at all. I don't know why, STATIC_URL is setup, STATICFILES_DIR is setup

#

Everytime I have "404 not found"

normal coyote
#
Traceback (most recent call last):
  File "main.py", line 1, in <module>
    from website import create_app
ImportError: cannot import name 'create_app' from 'website' (unknown location)
#

why am i getting that

#

trying to import from folder

#

@kind sluice

subtle sun
#

Flask gives the warning to not use it's built-in server in production. If my (open-source) package spins up a server local to the user, is that considered production ? In other words, do I need to include tornado , aiohttp or something similar?

real fossil
subtle sun
real fossil
#

I believe so, as long as it's not public facing and just local

toxic basalt
#

Hi guys

ionic raft
#

So...I've just finished the first major part of LanesFlow. This screenshot is of the dashboard for projects (PIPs - or Process Improvement Projects).
And I've pretty much completed the Project Management part of the app, along with the initial part of the dashboard. There is a fair bit of automation behind the scenes. Project rating for evaluating if a project should be taken on (and where projects can be compared to each other is now working). This screenshot shows three stages of the journey being described by the dashboard.
Project Selection Summary...shows projects with automated ratings based on 5 drop down field selections.
PIP Progress...shows the PIP in progress, what phase they're in. In this one, a target date for the end of the phase is missing, so the heading "Target Date" is highlighted red.
Completed PIPs...shows those PIPs that have been completed.
All in all this is very exciting and is looking and working better than I could have hoped. Lots of functionality behind the scenes to make this happen.

Feedback on initial impressions of the presentation layer welcomed. Being in a sole-developer bubble is tough. Looking forward to alpha testing.

kind sluice
sudden pewter
#

Good morning one and all..
Im going complete my MSC (cs ) with in few days, so i want start my career as a web developer. Any suggestions for what concept's should learn in front and backend in 2021.

honest tartan
#

Hey guys im developing an small api with Django for a test, but a got some issues with the data modeling. Can anybody helpeme?

#

Basically, the relations are ok, but when i make the queries on the service, the response that i got its not the users name(for a example), but its the Id.

here an img of my service:

#

and this one is my models:

#

and thats is the response of the check in and chack out endpopints

#

check_in

#

check_out:

#

can anybody help-me?

thorn igloo
#

if the username is in another table and you're using the user id as a foreignkey, you need to use joins to combine the data

honest tartan
#

hold

#

here

#

usuario = is the username

#

and Check In usuario takes the nome of Usuario Table

versed lotus
#

usuario seems to be a foreign key. A one-to-one-field is likely just the refence to the other table. meaning it only contains the id of the user, and you need to resolve the correct record from the user table (no idea how exactly that works in django)

thorn igloo
#

one way to get the username would be to do a join when querying the data, i'd suggest looking at how to achieve that in django. i'm not familiar with it

versed lotus
#

though it's probably specific to the rest framework you're using

honest tartan
versed lotus
#

it's probably an issue with your serializer then? not sure

thorn igloo
#

if that's the case, are you sure you specifying the right column?

#

cause if the id is appearing, it probably means that's what you are referencing

honest tartan
#

well i only follow the documentation:

here a example: class CheckoutViews(viewsets.ModelViewSet):
queryset=CheckOut.objects.select_related('quarto').all()
serializer_class=CheckoutSerializado

#

quarto its the column of the related table

thorn igloo
#

like the query

#

in the docs

#

too many

honest tartan
#

the last one, um look for select_related

#

you*

thorn igloo
#

i mean is queryset a list etc

#

if it is,

#

if you do something like this

#
for item in queryset:
  item.usuario # this is your userobject, 
#

item.usuario will represent an object for the user table or class in this case,

#

so you can just reference the username like item.usuario.username etc to get the username

#

if i understand what select_related does correctly

honest tartan
#

hmmm let see here if this works

vestal hound
#

it doesn't change the output of your query

thorn igloo
vestal hound
thorn igloo
#

i don't understand what your statement is in relation to

#

i was just telling the guy how to get the related data he wants, as suggested in the docs

vestal hound
#

I'm clarifying that select_related is not needed to perform a join in Django

thorn igloo
#

i see

vestal hound
#

it serves only to avoid the N+1 problem

thorn igloo
#

how would you actually perform a join in django though?

vestal hound
#

in other words, if you're not getting the related objects that you were originally looking for, select_related wouldn't help

#

okay so this is something I found a bit hard to wrap my head around at first?

#

but

#

say you have two models: Country and Person, with the latter having a FK to the former

#

okay, backtrack a bit

#

the concept of "join" doesn't exist in the same way in Django

#

so it depends on what you want to get out of it

#

say the country has a gdp column and you want it to be present in each instance of Person

#

then you would do Person.objects.all().annotate(country_gdp=F('country__gdp'))

#

which I believe is similar to what the original question wanted

#

(two underscores mean "go through this table" in Django)

thorn igloo
#

it's a simple case of linking related data in this case .. i.e primary key exits as a foreignkey on the other

vestal hound
#

like clearly if you want to perform a join, you must want some column from the related table

thorn igloo
#

how are you relating the foreign key here? and checking if it's actually in the two tables?

vestal hound
#

but

#

I mean

#

so on each instance of Person

#

there will be a country_gdp attribute

#

and that represents the value of the related Country's gdp attribute

#

i.e.

#

equivalent to

#

SELECT person.id, country.gdp FROM person LEFT JOIN country ON person.country_id = country.id

#

or something like that, I don't often write raw SQL

thorn igloo
#

ok, and an inner join?

vestal hound
#

in this case they would be the same

thorn igloo
#

what? left join and inner join will never return the same thing

#

left join shows everything on the left side and only filters the right

#

while inner join filters both

#

so, if you're saying what you showed me is a left join, surely there has to be some sort of different syntax for an inner join

vestal hound
#

where every row in the left table has a match in the right table, they will return the same thing.

#

and that must be the case here because of the FK constraint

#

i.e. every Person has a Country

vestal hound
#

there is no way to perform an arbitrary join, AFAIK

#

you would need raw SQL for that

thorn igloo
#

you said that performs a left join, i asked you about an inner join and said it would be the same thing?

vestal hound
#

which I think is a reasonable interpretation of ā€œsame thingā€

vestal hound
thorn igloo
#

you're saying an inner join and a left join would produce the same thing?

vestal hound
#

yes?

thorn igloo
#

bruh

vestal hound
thorn igloo
#

i guess that would make sense in that case

honest tartan
#

thanks for the help

valid void
#

Hello everyone, I created a Django Doplet in DigitalOcean, and I tried to create a domain name using 1&1. So I created my domain, I used a subdomain that I linked to DigitalOcean DNS. It worked well, but I don't want the site to be accessible anymore, so I deleted all existing links between DigitalOcean and 1&1, but the site is still available. Do you know why ?

#

And I deleted everything after

#

But the site is still available...

#

Is it linked to the TTL value ?

true kernel
#

hey so i know this isnt a postgres server but

#

in django I do have to fill in the location of the database right?

#

if yes, how do I find out the location of my server from pgadmin4?

#

i cant seem to find it in the properties section of the database

next comet
#

Hey guys, anyone familiar with Cloudinary for django, i have a question

dense slate
versed python
dense slate
#

You just supply the db name, port (of postgres, 5432 by default), ip (of the linux server), username, and pw in your settings.

valid void
honest tartan
#

@vestal houndman didnt work

#

still on the same

valid void
versed python
vestal hound
honest tartan
#

the solution that yougave about djabgo

#

django*

native tide
#

guys i have a problem my page is redirecting on all devices

vestal hound
lethal cedar
#

Is there a common way in Django where to save for example a custom Mixin?

dense slate
native tide
#

redirecting loop

lapis basalt
#

Does postman provides good documentation for API. If yes why when doing some research, I found always that swagger and openAPI and few other are always more recommended.
It is a documentation that must be prepared for a front-end developer to ingrate the services in front.

lethal cedar
versed python
#

i created an app called core which holds all these general stuff

lethal cedar
#

Okay thanks

lapis basalt
#

Does postman provides good documentation for API. If yes why when doing some research, I found always that swagger and openAPI and few other are always more recommended.
It is a documentation that must be prepared for a front-end developer to ingrate the services in front.

velvet yew
#

I've got a Django project I'm working on as my web development training, and while I'm decent in Python + backend/devops stuff, I'm struggling with the JS parts. I'm looking for someone who would like to contribute with some JS knowledge and learn/practice JS (and Django) together on the project. Shoot me a DM if you'd like to collab

dense slate
velvet yew
# dense slate What's your project, out of curiosity?

It's a SEO/marketing toolkit, I'm automating a lot of stuff I'm doing on a daily basis for me and my SEO peeps, and I'm creating a dashboard for it, but doing it with Django only without any JS has quite a few limitations hence why I'm looking for someone who's familiar with JS

wispy ice
#

Okay

#

How do i use html to request a file and python code to download it

#

Is there a way?

#

In my html page i click a button and python downloads it through response

#

Im using python cgi and ajax/jquery

#

But i cant find anything

dense slate
#

I'm confused. You're using a solution already so what can't you find?

#

Or that's what you want to happen.

wispy ice
#

Im using that to return plain text

#

But i want a solution that lets me download a file

glacial yoke
#

Hello there people of the internet, is it better to use react together with django, or just use normal html, css and javascript through the django templates?

wispy ice
#

For other related thing

dense slate
#

Depends what you need, as always.

limpid python
#
.info {
    width: 80%;
    margin: auto;
    text-align: center;
    padding-top: 100px;
    background: #3e4c61;
}
#

how to I set the background color to the full section, without changing the width

glacial yoke
dense slate
wispy ice
#

Not really @dense slate, i need to click the button, the file is generated in the server, and then its downloaded

#

Its not something static

limpid python
dense slate
#

Ok so the content of the file can be dynamic?

wispy ice
#

Yes, but size will be always the same

limpid python
#
.info {
    width: 80%;
    margin: auto;
    text-align: center;
    padding-top: 100px;
    background: #3e4c61;
    display: block;
}
```?
dense slate
#

Yea I mean you would ajax a request to the backend, handle that on the server and return the data. then just download however you would normally do that on the front end.

#

I don't have any actual examples.

glacial yoke
glacial yoke
limpid python
#

nope

wispy ice
limpid python
#

i have the margin set to 80, but i cant change, but i want the background to cover it all

glacial yoke
dense slate
wispy ice
#

Ty, appreciated

glacial yoke
limpid python
#

oh yea

#

ay, thanks!

glacial yoke
# limpid python ay, thanks!

or use a separate class, like "container", and set the width to whatever you want there, so that it's more neater, and you can use it on several objects in your website, if the design is the same

limpid python
#

oh yea, i may change that later on depending on how I want the site to look

quick cargo
#

err <@&831776746206265384> Im not quite sure what this is

manic frost
#

@native tide We don't allow recruitment here, please read our rules. Also... that's really racist

daring gust
#

!mute 816978312756330500 3d We neither accept offers for paid work, nor casual racism here.

lavish prismBOT
#

:incoming_envelope: :ok_hand: applied mute to @native tide until <t:1628956088:f> (2 days and 23 hours).

daring gust
#

Please make sure you read and understand our rules and code of conduct.

chilly mesa
#

hi lads!!

#

i want to update an object through this view. but i couldnt. you guys have any idea ?

#

i've tried the using '-' but it doesnt seem to work

mortal mango
#

My website 1 nginx conf file is rendering website 2 on my server. Does anyone know why?

Website 1:

# the upstream component nginx needs to connect to
upstream django {
    server unix:///home/webserver/exo_dashboard/dashboard/exo.sock;
}

# configuration of the server
server {
    listen      80;
    server_name beta.exobot.xyz www.beta.exobot.xyz;
    charset     utf-8;

    # max upload size
    client_max_body_size 75M;

    # Django media and static files
    location /media/  {
        alias /home/webserver/exo_dashboard/dashboard/media;
    }
    location /static/ {
        alias /home/webserver/exo_dashboard/dashboard/static/;
    }

    # Send all non-media requests to the Django server.
    location / {
        uwsgi_pass  django;
        include     /home/webserver/exo_dashboard/dashboard/uwsgi_params;
    }
}

Website 2:

server {
  
        root /home/webserver/website;
        index index.html index.htm index.nginx-debian.html;

        server_name exobot.xyz www.exobot.xyz;

        location / {
                try_files $uri $uri/ =404;
        }

        location = /arc-sw.js {
                proxy_pass https://arc.io;
                proxy_ssl_server_name on;
        }


    listen [::]:443 ssl; # managed by Certbot
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/exobot.xyz/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/exobot.xyz/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}
server {
    if ($host = exobot.xyz) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


        listen 80;
        listen [::]:80;

        server_name exobot.xyz;
    return 404; # managed by Certbot


}
#

both of the websites render website 2

#

I want website 1 to render a django website

dense slate
chilly mesa
#

i figured it out !. i was supposed to do the arithmetic operation between brackts().

#

anyways thank you

timber pulsar
#

So I am making a web page for a game that files outputs

#

that file has data the user needs to submit

#

The issue I'm having is finding a way to open explorer on the directory on upload button or through anchors

dark sun
tribal forge
#

heyo

#

anyone there who can help me with this error

#

this error is throw on an async msg when i try to find by id in a mongoose database

quasi field
#

Is this just a bug in Pyharm, or am I doing something wrong with the HTML? page displays fine, just that Pycharm is bugging me with this warning

#

(Django template)

quasi field
#

Oh sorry, it's just saying that the "closing tag matches nothing" although it should be closing the <dt>

#

I'm guessing that Pychamr Community can't parse the Django for loop and is thinking that the HTML is invalid, but that's just my suspicion

#

the <dl> tag is closed btw, just not in the image

ionic raft
# quasi field Is this just a bug in Pyharm, or am I doing something wrong with the HTML? page ...

On a related but divergent note...I have some complex template conditioning that appears to result in errors in PyCharm around tags. PyCharm is suggesting to remove a tag, but methinks there's a bug in their parser that means PC doesn't always nail errors. My experience is that I occasionally get false-positives...I'm getting a red-underline and "remove tag" suggestion and yet the web page renders perfectly...According to PyCharm this screenshot shows a web page that should be broken, and yet to my eye is rendering exactly as intended.

quasi field
#

Yep sounds like what I'm experiencing, the page loads fine (not as pretty as that one) but Pycharm doesn't like the HTML

proven elk
#

hi everyone

#

do u know how to use clound mongo database with django frame

ionic raft
#

This is the end of the html file...
In all fairness to PyCharm, sometimes the conditioning and looping for a template can be really quite intense. There's a lot of things going on in the application layer to make that page possible. And I'm only using the presentation layer to filter/condition or loop. However, the net result is still some intense template layout.

native tide
#

How can I use aiohttp to make clickable buttons that trigger functions?

vocal lake
#

how do I send the contents of a text file through a flask websocket?

mortal mango
native tide
quick cargo
#

Python as a language is arguably the hardest language to try embed into wasm

#

Outside of shipping an entire interpreter with the wasm code

#

If you want to do frontend systems you're far better of just using normal js

#

And js frontend frameworks

#

Wasm in general is still very new and had many limitations which vary across browsers

#

Will wasm ever become viable as a frontend framework for production? Maybe, yew.rs with rust is probably the most promising, but that still requires interfacing with js and wasm binaries are still just massive blobs leading to slow timez

#

Will python ever become a frontend browser framework language with wasm? Almost definitely no

native tide
#

Would be nice tho, I like python a lot and I want it to be my primary and only programming language.

gusty edge
#

Trying to make an API with fastapi
How do I go about managing tokens? like generating/regenerating them and saving keys/secrets?

quick cargo
#

E.g. Java and kotlin for android apps

#

Lua for embedded scripting

#

Swift for IOS apps

#

Js for frontend web work

rare oar
#

Good day everyone, I am wondering how you all approach integrating your front-end with your back-end source without putting everything in the same project. For instance, looking to use React on a small portion of my site. How can I keep my React code in another project, but have easy access to development?

#

some kind of script that copies over the compiled javascript? But then you have to build each time?

ionic raft
rare oar
#

Yeah I did it once before where I was lazy and just dumped it all into a package on my back-end. It just felt wrong and out of place

ionic raft
#

As for the direct answer, I've been making extensive use of the application layer to query the DB, and to set up the front end through context dictionaries.

#

It's working really, really well so far. But it's all text/file data. The final app for phase 1 will be an diagramming and that's a whole different bag

ionic raft
#

I'm actually blown away by how fast you can build in Django when you get the hang of it. Just built a full on complex app in under a day.

rare oar
#

hmm, I suppose I could make the api first. Front-end is just a quick admin dashboard to change some settings. So it'll have access to a very limited private api

ionic raft
rare oar
#

Very nice. First project I did was Django. Probably did every bad practice in the book

#

This one I'm trying out FastAPI. So far liking it

ionic raft
rare oar
#

This channel so dead 😦 It's just you and me haha

ionic raft
#

I'm doing all my querying through views.py files. Likely not best practice for other devs working on this. But right now I'm the sole dev...

#

and it's working

rare oar
#

tbh ActiveRecord patterns really promote you doing it in views.py so I don't think you are doing anything wrong

ionic raft
#

The thing is, once I worked out how to query and update the DB on form saves, you know, save the field they filled in the form, and did coding to update fields not showing...all I needed

ionic raft
#

But the speed of dev in Dj is astonishingly fast

rare oar
#

site looks good. Congrats. DId better than me on my first try

#

by second try is a monolithic abomination

ionic raft
# rare oar site looks good. Congrats. DId better than me on my first try

This is a monolith. But it's fitting. it's a web app for business to improve quality and their profits. Built on 20+ years of consulting experience and tools I train. It's automating me as a business consultant.
The tagline. Complex Made Clear.
The vision. A business consultant in your pocket.
The entry-point. A free subscription to try it out.

rare oar
#

Are you pitching me? šŸ˜„

ionic raft
#

Nah. Always curious to see reactions.
Besides, the entry point is free. There's nothing to pitch.

#

It's a business to business tool tho. Nothing like it out there that I'm aware of. The final app will be a diagramming one for something i call Collaboration Mapping. That's the BIG one. When I nail that...
In the meantime, I don't know a scrap of JS. I'll be learning that next.
But then, Apr 15, 2021 I didn't know a scrap of Python...so I figure I'm solid ;D

rare oar
#

That's awesome man

#

I'm actually along similar lines of work, primarily in franchise restaurant operations

ionic raft
#

So, always curious to hear about React. It's the tool I'm hearing good things about for the front-end and diagrams

rare oar
#

patterns are fairly similar to most businesses I find though

ionic raft
#

OK...I may be pitching you at some point. Interested in being an alpha tester?

rare oar
#

Sure. I don't have decision making power for an app like this in full disclosure. Mid-level management here working on behalf of the franchisor

ionic raft
#

Hey...that won't matter...Friend req incoming. I'll follow up in a few weeks...

native tide
#

hey i have question how to use postgresql on django? i have been trying and download everthing like libpq-dev and still i can't use postgresql on django. Please help!, thanks

rare oar
native tide
#

i have been instaled and this happening when i type 'python manage.py makemigrations'

rare oar
#

can you post your urls.py? Doesn't sound postgres related tbh

native tide
rare oar
#

sorry your post/urls.py

native tide
#

it's still empty i just wanna prepare for database

rare oar
#

rename urlpattern to be urlpatterns

#

That will atleast allow it to go past that first error

vestal hound
#

delete that screenshot

#

and change your secret

#

paste errors as text

#

screenshots are hard to read

native tide
vestal hound
rare oar
#

Ok so there's your postgres error. Its saying it can't connect. Did you install postgres on your machine or are you running it in a container?

native tide
#

i installed but i can't opened idk why

rare oar
#

not a linux guy, but quick googling (and this would be distribution dependent) but make sure you start your service. an example I believe for ubuntu is pg_ctl start

#

ok repasting my earlier question so its not lost

#

Good day everyone, I am wondering how you all approach integrating your front-end with your back-end source without putting everything in the same project. For instance, looking to use React on a small portion of my site. How can I keep my React code in another project, but have easy access to development?

native tide
#

can i ask about d.js here

#

šŸ¤”

rare oar
#

wait... d.js is a discord thing or no?

#

if not, then sure ask here

native tide
#

alright

#
const { Client, MessageEmbed } = require('discord.js');

module.exports.run = async(bot, message, args) => {

  var pingembed = new MessageEmbed();
  var editingembed = new MessageEmbed()
  editingembed.setColor("#40E0D0")
  editingembed.setDescription("Pinging...")
  const diff = Date.now() - message.createdTimestamp;
  let msg = (` šŸ“  **|** Pong! **Bot Latency:** \`${diff} ms\``)
  pingembed.setColor('#ff7100')
  pingembed.setDescription(msg);
  message.channel.send(pingembed)
 

}

module.exports.help = {
  name: "ping",
  aliances: []
}
```for some reason this command wont work
no error is provided in the terminal either
This is my command handler: https://hastebin.com/rabatiqobe.http
#

and its javascript

rare oar
#

heh yeah that is a discord bot. #discord-bots is the right channel

quasi field
#

I don't know about you all, but my website is making me hungry I think I'm almost ready to deploy

vestal hound
#

you mean like Git repo?

#

this is quite a devops question

rare oar
#

ok I'll post there

#

but yes, essentially how to have them in different repos, but actively develop on them

opaque vale
#

Hey guys can someone show me some example code for getting a response dictionary and printing it to command line? for some reason when i execute print(reponse.POST) it prints a blank line

inland oak
#

for ubuntu (and probably debian too) systems, all you need to install those additional packages

apt update
apt install -y python3-pip python3-dev libpq-dev postgresql postgresql-contrib curl
apt-get install -y build-essential
#

plus your pip should have installed psycopg2

pip3 install psycopg2

(This library will not install itself properly until you installed the apt things above)

#

and that's basically it. then all is left to insert the right settings for connections

#

i have as default sqlite3

DATABASES = {
    "default": {
        "ENGINE": os.environ.get("DB_ENGINE") or "django.db.backends.sqlite3",
        "NAME": os.environ.get("DB_NAME") or BASE_DIR / "db.sqlite3",
        "USER": os.environ.get("DB_USER") or "",
        "PASSWORD": os.environ.get("DB_PASSWORD") or "",
        "HOST": os.environ.get("DB_HOST") or "",
        "PORT": os.environ.get("DB_PORT") or "",
    }
}

but in .env file I rewrite them with those ones to conect to postgresql

DB_ENGINE=django.db.backends.postgresql_psycopg2
DB_NAME=postgres
DB_USER=postgres
DB_PASSWORD=postgres
DB_HOST='127.0.0.1'
DB_PORT='5432'
#

you should be obiously having setup password for your database

#

password postgres is bad one btw šŸ˜‰

strong girder
#

How do I make a script know how to type in a specific place (say the Discord chat box for example)?

inland oak
#

every chat box is some channel

#

all you need to use their send function with providing in which channel to send the message

inland oak
strong merlin
#

Plz anyone refer me a beginner project for django

versed python
#

A bit more advanced can be something like Spotify

#

With users and liking songs etc

twilit needle
#

would you guys recommend graphql or rest, especially if I were to build an api with python

#

after having some experience with python graphql server libraries, I found out that they are really young and not mature enough. It will still take some time.
However, graphql promises a lot more than rest

strong merlin
versed python
stark tartan
#

how to make a date time filed in django models so that it take millsec also as a timestamp

dark sun
#

how to make text color and font in flask.py

thorn igloo
ionic raft
#

Time to learn...InLine Formsets šŸ™‚

dusk portal
#

Are my python and web development skills enough for a good job
Or ds algo
And
As I'm 16 and ig good on development now working on django rest Framework so should i countinue Development or start with data structures

ionic raft
#

My recommendation...look for projects to build that solve valuable problems. If you've got an idea of the type of coding you'd like to do focus on that

#

Your project portfolio gives you something to show. The experience building those projects gives you depth to talk about

gritty coyote
#

Can someone please let me know if there exists a job board in this server??

ionic raft
gritty coyote
#

oh okay thanks for letting me know.

long jackal
#

I am making a website with a game, and I want to add sounds to that game but the sounds seem a bit delayed and they can't overlap, the game can require a few sounds per second. But the sounds will not play, or initiate (as in if I hit something, a sound plays, but if I hit something else as the first sound is playing, it won't play the second sound, even after the first sound is finished) until the current sound has finished playing.

Code

var gameOverSound = new Audio('/audio/player_lose.wav')
var enemyHitSound = new Audio('/audio/enemy_hit.wav')
var enemyPopSound = new Audio('/audio/enemy_pop.wav')

// then in some loops
gameOverSound.play()
//...
enemyHitSound.play()
//...
enemyPopSound.play()
cursive sorrel
#

Was hoping to ask some advise, just taking my first early steps into Django and was wondering on best practice.

#

Where should the data manipulation occur, within the SQL or bring it out into Pandas

#

with a view to exposing the results to the end user

tulip beacon
#

hey guys, I have a problem in css of my website, I used position relative in the Todo List script, and when I click the add button on the top, it adds HELLO but also there is a blank space increasing in the bottom, which is the white area at the bottom of the image

sturdy sapphire
#

do you have a link to this page?

#

and what is the problem with the white part again?

#

what do you want it to be

#

what do you expect to happen

#

what happens when you add a new tag

#

there are also no html or css code shown

#

!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.pydis.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.

tulip beacon
#
.todo{
    position: relative;
    left: 290px;
    bottom: 500px;
    margin-bottom: 15px;
    font-size: 25px;
    background-color: aliceblue;
    height: 43px;
    width: 650px;
    border-radius: 10px;
    font-size: 20px;
}

.trash-btn{
    position: absolute;
    left: 670px;
    top: 1px;
    border: none;
    border-radius: 5px;
}

.trash-btn:hover{
    border-radius: 15px;
}
#

this is the css

cursive pine
#

can someone help with this basic q on Flask in #help-candy

tulip beacon
#

is there any fix for that?

#

@sturdy sapphire what should I do?

weak nacelle
#

i think you should provide the html too for easier reference

native tide
#

I had watched a couple of videos about web development they told us that we must know javascript for it, is that true? or python can handle that

inland oak
#

I mean...

#

if you are backend web developer, then no, python is enough

#

but if you make back and front at the same time.

#

Then you need to know python and javascript at the same time too, preferably.

#

Technically you can make beautiful things even if you know only python + html + css

#

but knowing even a little bit of javascript will help anyway.

native tide
#

thanks

cursive pine
#

I have a question in #help-croissant
How do I get a user input from my html textbox and pass it to a variable in another .py file within the project? All online examples and SO answers simply "return" the value within the @supple flame.route function

cerulean badge
#

(context django) when using custom user with all auth do you need to do email = models.EmailField(unique=True) as well if you are going to set ACCOUNT_UNIQUE_EMAIL = True?

dusk portal
#
@api_view(['GET'])
def test_prog(request):
    data={'Age':16,'Name':'Aryan'}
    return Response(data)


class TaskList(generics.ListAPIView):
    queryset= Task.objects.all()
    serializer_class= TaskSerializer
    permission_classes=[IsAuthenticatedOrReadOnly]
    throttle_classes=[UserRateThrottle,AnonRateThrottle]
    filter_backends = [filters.OrderingFilter]
    search_fields= ['task']``` in cbv we can filter ezily but how to filter in ```@api_view```
#

plz show how to do it by doing in def test_prog

inland oak
#

bad name šŸ˜‰
test_* is conventional way to name unit test functions

#

it is not in your case. you have a view function.

lime frigate
#

Guys should i learn django or flask? I have already know the basics of python

#

I want to use mongodb with it also

#

Which is more useful?

sudden steeple
#

I imagine that there's a way to hook mongo up to almost anything.

#

Flask is really easy to get up and running with

versed python
#

Among flask and Django I'd recommend Django though it's a bit more difficult

#

But it gives you more out of the box

versed python
#

I'm sure it is

inland oak
#

it is just has totally a different usage from SQL databases

#

don't mistake one for another

versed python
#

Yeah you're right

#

Edited my initial reply :)

inland oak
#

good for beginners

sudden steeple
lime frigate
#

I already knew sql

inland oak
#

well, then it is fine to go with MongoDB, cool thing to know too

lime frigate
#

So i wanna expand my knowledge

#

So basically i shouldn't use mongodb with python?

inland oak
#

I still can't find a time to expand my knowledge in this direction 😭

inland oak
#

there are libraries for python integration with mongo

#

multiple ones

lime frigate
#

So in conclusion.... should i learn flask or djangošŸ˜‚

sudden steeple
#

You can write a basic flask server in 5m

#

try that and if you don't like it try django

inland oak
lime frigate
#

Based on functionality?

inland oak
#

flask follows micro framework approach

#

you have nothing at the start and you add micro libraries of its functionality.

#

good for starting learning curve I guess

#

django is having batteries included approach

#

everything is already enabled, you are like train on the rails (hehe ruby on rails)

#

you need to navigate through its documentation a lot in order to not reinvent the wheel

lime frigate
#

So is there anything that one can do but the other cannot.

#

?

#

Smthg like shortcomings?

inland oak
#

mm there are things actually.

#

main difference = Django offers already made Admin/moderator thing easily being made

#

+its good ORM for SQL usage

#

for Flask you choose your own SQL ORM thing

#

Flask made recently a step to become Async friendly framework

#

it is a bit too fresh probably though

#

Django made a step too, but a bit behind, since it can't transfer its ORM to asyncness yet

lime frigate
#

Hmmm

sudden steeple
#
from flask import Flask

app = Flask(__name__)

@app.route('/')
def index():
    return '<h1>Hi There!</h1>'

if __name__ == '__main__':
    app.run()
#

That's a flask web server

lime frigate
#

Still needs some consideration

inland oak
#

usually people...

#

who don't choose Django...

#

they choose Fast API

#

it is sort of...

#

having a lot of things already enabled for you too, but from a different sphere

lime frigate
#

So which one do you prefer personally?

inland oak
#

Fast API is fully async friendly framework, without ORM already installed, but as far as I heard it has almost setup REST documentation tools

#

I tried only Flask, Quart and in love with Django

#

I work with Django extensively, but eyeing quite a lot Fast API

#

wishing to try Fast API

lime frigate
#

Hmmm i see......

#

I think i will go with Django then

#

Thanks for the info mate

#

I'm going to sleep now byeee

sudden steeple
#

Does anyone have experience sending mail from the backend?

#

Some of the stuff that I've read says skip doing it yourself through smtp and use a service like SendGrid instead

#

Does anyone know if this is good advice?

inland oak
dapper tusk
#

my suggestion is to use ariadne for APIs these days, I have found graphQL much nicer to work with than rest

inland oak
#

I wonder how true those words are

dapper tusk
#

it depends on how you measure and is a completely meaningless number

inland oak
#

anyway, when you are going to use some custom database connecting library, I think Fast API could work better than django perhaps

#

like GraphQL I guess, or async postgres library

dapper tusk
#

graphql is a replacement for rest, not for a query language

#

though afaik there are databases that support graphql

inland oak
#

for graphql

dapper tusk
#

no need

inland oak
#

hmm

dapper tusk
#

I have done a graphql API running on CGI using mysql as the db

#

it wasn't very fast (because cgi), but it does work

inland oak
#

caching database requests with redis

#

caching incoming requests even earlier with varnish

#

enough of things to cache and speed up šŸ˜‰

dapper tusk
#

now yes, there are databases that work well with graphQL, but well, you can use whichever one you want

#

web framework benchmarks are not a good way to pick a web framework

#

also, they are really easy to make misleading

inland oak
#

i like Django for simplicity to develop

#

fast and comfortable.

dapper tusk
#

yeah, Django is great

inland oak
#

rapid blazingly fast šŸ˜‰

dapper tusk
#

everything you need has an existing solution

#

probably even a builtin solution

inland oak
#

like... when you are going to develop a web chat... there is Django channels thing and e.t.c.

dapper tusk
#

even ariadne has django integration, so you can use the django ORM for a graphql api

inland oak
#

yeah, I saw the guys in imagine had a template

#

to presetup django with GraphQL as an option

#

with already made 100% coverage

#

cools guys.

#

I think I saved for myself their example, just in case to dig whatever they made šŸ¤”

dapper tusk
#

that is one thing where django feels a bit lacking compared to sth like springboot, testing. But at the same time, I did not do a lot of django automated testing, so it may be better and I just haven't found the correct solution yet

inland oak
#

I feel myself good, when testing in django

#

pytest

#

coverage

#

mypy if I wish

#

whatever else I need? everything works.

inland oak
#

they are extended with Django Rest Framework

#

it provides everything you need for testing of APIs I think

#

probably I guess it would be a bit contradictory to use them with GraphQL, or not šŸ¤”

inland oak
#

what would you recommend as a backend besides python+django to cover most of other situations?

#

Go+Jin I think? / Springboot + Java ? Ruby on rails? Something else?

dapper tusk
#

I would not recommend springboot tbh

#

it is not better than django for most things

random jolt
#

Hello, so I'm a beginner and I need someone to please help me out as an accountability partner, we could be friends here and grow together . Thanks in advance

dapper tusk
#

what I really liked was ruby on rails, but that is actually resource hungry enough to matter

inland oak
#

Golang is quite recommended for devops people

#

since I go with being backend+devops

#

perhaps some Go backend could benefit me better, since it would benefit me being as devops too

dapper tusk
#

I am very opposed to some solutions go takes to problems (byte sequences are not text, no matter how hard you squint), but it is indeed a good language to know for devops

gritty cloud
#

i use graphene lol

dapper tusk
#

ah, it is similar

inland oak
#

plus Go is quite fast one šŸ˜‰
it could be fill the niche

dapper tusk
#

if you need fast and web, there is rust

gritty cloud
#

i feel that python servers' speeds are fine

dapper tusk
#

yeah, haven't ever had any issues

#

but it has you write the schema and bind the resolvers to the schema, it does not generate the schema from a class

gritty cloud
#

see graphene

dapper tusk
#

couldn't tell you whether that's a better approach than writing the schema in python

inland oak
#

I guess I will compare available job vanacies

#

in Rust and Go

#

to make a choice

dapper tusk
#

oh, for jobs for sure go

gritty cloud
#

i probably won't learn anohter language other than python and js

dapper tusk
#

Rust is still niche

inland oak
#

Bleeding edge technologies ;b

#

keep up with time and all these things

gritty cloud
#

speaking of which

inland oak
#

Golang will serve me better I hope to remain popular

gritty cloud
#

im using svelte nowadays

inland oak
#

or more like becoming a popular

#

since it only grows

dapper tusk
#

yeah, I recently tried svelte and I am a fan

#

the right mix of react components and old style MVC separation of concerns

versed python
#

do you like it? would you recommend it?

#

im a vue guy and svelte looks easy

#

and svelteKit looks really interesting

dapper tusk
#

yeah, so far the best frontend framework I have used

ionic raft
dapper tusk
#

no idea

ionic raft
#

DJango - Inline Formset question in #help-pie
Need to work out ManagementForm...

gentle jasper
#

serializer is convert to json?

#

Dict -> Json

ionic raft
#

I'm stuck on Django Inline Formset and this error: "ManagementForm data is missing or has been tampered with. Missing fields: VOC-TOTAL_FORMS, VOC-INITIAL_FORMS. You may need to file a bug report if the issue persists"

ionic raft
ionic raft
#

Will keep on researching this one...stumped

calm plume
calm plume
ionic raft
#

Worked it out...Inline Formsets are BELONG TO US! šŸ˜„

ionic raft
#

Can I just say how profoundly brilliant I find crispy forms to be!

#

This...so. much. this!

fossil loom
#

Hi I want to do a small website and i heard that Flask is better than Django for small project, what do you think?

#

It's going to be a website just for fun

gentle jasper
#

What is a MVP in Django?

gritty cloud
limber laurel
#

Yeah but when you start using even a basic database, I have a feeling django is easier to use

#

Because of migrations and no need for seperstely installing SQLAlchemy and things like Flask-Migrate

vocal lake
#

hai can I get help pls

So I have a text file thats gonna be constantly updated and want to receive the contents near instantly. I got websockets kinda working but its still not updating when the text file changes

native tide
#

For someone who is learning back end development, learning html and css is important?

vocal lake
#

for a career or just a hobby?

#

career absolutely hobby you only need to know enough to make sure the back end is working

eternal blade
lavish prismBOT
#

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

ionic raft
native tide
#

hello can you help me, i have some trouble about post method to api by library requests and urllib, the code not works and i dont know about mistakes.

When i'm trying with postman it works

how can solve this problem?, thankyou very much

#

this is my code with using library requests

#

this is my code with library urllib

#

and this is i test from post man. it works

opal quest
#

Anyone knows how to create a domain web server for vscode local host can help me pls thank you

lunar stream
#

can someone help me out hosting a flask python website into pythonanywhere?

near bison
#

I have a project with

  1. Two python processes (web + worker)
  2. Redis
  3. Mongodb

Where can i host this ?
Is aws ec2 a good choice. i would love to hear about a free option. so that i can test this out. Thank you

cursive pine
#

I'm having trouble setting up uvicorn through cmd. says could not import module "working"

stark tartan
#

i want to user to change username but when i want to write the username that already existed the clean_username method not working and thus giving IntegrityError at /users/profile-edit/ UNIQUE constraint failed: users_user.username
HOW TO QUERY IN clean_username SO THAT IS SHOW ONLY USERNAME ALREADY EXIST ValidationError

class UserEditFrom(forms.ModelForm):
    username = forms.CharField(label="",max_length=254,widget=forms.TextInput(attrs={'id':"user-name",'type':"text" ,'class':"form__input"  ,))

    def clean_username(self,*args, **kwargs):
        username = self.cleaned_data.get("username")
        if User.objects.filter(username=username).exclude(username=username).exists():
            raise forms.ValidationError('username is alraedy taken try another one')
        return username
wicked tide
#

If anyone's got experience with Django and Django-Graphene, please check out #🤔help-banana and shoot me a ping. Getting weird issues at the start. :/

hollow minnow
distant charm
#

Hello guyes

#

anybody know how to implement conditional rate limiting in fastapi

outer venture
thorn igloo
native tide
#

Someone may have tutos or codes to implement newsletter in django app blog? and make it work when someone subscribe with his email?

sleek pine
#

How to get requests from a drop down select box?

true kernel
#

Apps arent loaded yet??

#

django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
This happened after I deleted my database, made a new one and set AUTH_USER_MODEL = "account.Account", account is my app and Account is a class in its models.py

gritty cloud
#

but if you are

#

have you added apps to INSTALLED_APPS?

true kernel
#

i had to buiild a custom user model

#

it has something to do with my postgres table im sure

gritty cloud
#

and is your AUTH_USER_MODEL after INSTALLED_APPS?

true kernel
#

no its before

gritty cloud
#

there's your problem

#

the apps literally haven't loaded in yet

#

so django has no clue what your talking about

#

move AUTH_USER_MODEL to the end of the file or at least after INSTALLED_APPS

true kernel
#

I did, it still shows the same error

gritty cloud
#

have you ran the migration commands

true kernel
#

although your reasoning makes perfect sense to me

#

yeah

#

i just did, and same errors

gritty cloud
#

is your postgres server up?

true kernel
#

itis

gritty cloud
#

hm

true kernel
#

it worked

#

i actually had imported accidentally account before installed apps declaration

gritty cloud
#

happens to the best of us lol

true kernel
#

it should not have been a problem but

true kernel
#

my files have erroneus lines that I dont remember writing

#

its almost spooky

gritty cloud
#

perhaps your computer is possesed

#

or maybe you drank too much caffiene

true kernel
#

its highly unlikely but, you know what they say

#

when you rule out the impossible, whatever remains, however improbable must be the truth

#

my laptop is possessed af

gritty cloud
#

ncie

#

nice

gritty cloud
true kernel
#

lmao i love my it no matter what

#

i aint sellin it even if it automatically shuts or starts

sleek pine
#

How to get requests from a drop down select box? In flask

brazen tree
#

Where should I ask question about fbprophet? I wanted to add legend to the plot

dusk portal
#

@odd root ask here

native tide
#

@sleek pine request.form

sleek pine
native tide
#

yes

true kernel
#

my login is broken!

#

when i try to login with my superuser it says Please enter the correct email and password for a staff account. Note that both fields may be case-sensitive.

signal nova
#

Does anyone here know how django's F() expressions work?

reporter = Reporters.objects.get(name='Tintin')
reporter.stories_filed = F('stories_filed') + 1
reporter.save()

The docs says that the F class overrides the standard Python operators, but I dont understand how. Like, is the assignment operator (=) overriden? Or how does the F instance know about which Reporters entry to look at, and even on which model should it search?

#

Also how can you just temporarily override operators?

indigo kettle
#

and you can define how that operator should work and what it should return

fossil rivet
#

Hi is there some change in Github Policy today?

true kernel
#

Hello

#

I made a custom user model, and i am facing the issue that password is not being encrypted when a new user is added

#

and im not even able to login with that new user

#

Alright so turns out you can only login when the password is hashed. They should have mentioned this in the docs.

fossil rivet
#

I just typed wrong password. then I tried to log in as token. I can't install cli even

calm plume
#

You'll need to use SSH or a PAT

quasi field
#

#help-kiwi If anyone would like to answer a simple question about Django templates

ionic raft
rare oar
#

http verbs are confusing. guildconfig/{id} alters a config but can't change the id. Is that put or patch?

#

I'm thinking put since you need to supply the entire body?

quasi field
# ionic raft Just logged in. Do you still have that question?

Yes I am still wondering if it's possible to have something like a 'global variable' that I can use in my templates, for now I have just changed it so that all mentions of the site title are in the base template html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>PyBlog - {% block title %}{% endblock %}</title> </head> <body> <p> <b><em>PyBlog - {% block page_title %}{% endblock %}</em></b> | Then in other templates I do this html {% block page_title %}{{ page_title }}{% endblock page_title %} where page_title is passed in as context from the page specific view function. Here is how that looks on the index page

ionic raft
#

Maybe have it in a file that you import into each view file?

#

Load it as a context within each view.

#

I am not aware of another way of doing this...

quasi field
#

Ahh ok, yeah I guess that is probably the simplest way to do it. I was wondering if there was some sort of way to pass it from the base template, but that will work too!

ionic raft
#

However, template inheritance does take care of presenting it front end. But the context var needs to be in every view. Importing it would save a bit of code

#

current year for the footer is a good use case for that. Although, I build the var in each view file. So I've not tried what I suggested.

quasi field
#

something like views.py ```py
from django.shortcuts import render, redirect
from datetime import datetime
...
DATE = datetime.today()

#

Is that what you do for the footers?

#

I suppose this will work, it's easy enough to just pass this as context in one of the views (I only have one views file right now anyways)

ionic raft
#

Just finished dashboard prototype design today... I welcome any UX feedback...

ionic raft
quasi field
#

Looks very clean! I would maybe move the Profile and Subscription buttons closer to the sign out button, I think it might be better to have one side of the header for Tools and resources and one side for account related actions. But over all looking very good! Is this all possible with just html / css / django? Or are you using Javascript etc..?

ionic raft
manic frost
#

it's not really supposed to be a constant

ionic raft
ionic raft
quasi field
manic frost
quasi field
#

ahh yeah that is a good point...

ionic raft
manic frost
#

yes

#

or, well, make a function

ionic raft
#

Good to know. Ty

quasi field
#

I love django already

#

There's a template tag for that

ionic raft
#

Lovely

nimble raft
ionic raft
ionic raft
fast lava
#

Guys i need a lotta help

#

anybody there

#

ping me

wary pecan
#

Anyone here well versed in html or css or in general webdesign? Trying to master webdesign (html, css etc etc) and would like to know what I should prioritize to see sustainable progress I know basic html tags and a couple css style selectors and how classes work somewhat and would like some outside input

vestal hound
#

"parts" of HTML/CSS

#

you should focus on how to do things

lime valve
#

I have bugs in my django project can anyone help me please

#

If I complete the project I will shortlist for interview pls help me

native tide
#

Hi there, I'm trying to figure out how to configure a custom user for my DRF project. I have attached my directory structure.

I have created a custom user like so:

from django.contrib.auth.models import AbstractUser

class User(AbstractUser):
    pass

Added my application to INSTALLED_APPS:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',

    # custom apps
    'apps.api'
]

And tried to change the AUTH_USER_MODEL like so:

AUTH_USER_MODEL = 'api.User'

However, I'm getting the following error:

django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'api.User' that has not been installed

I have tried many ideas, but it still won't work. Could you help me?

Thank you!

versed python
native tide
# versed python AUTH_USER MODEL='apps.api.User'

I also tried this and getting another error.
Fortunately, I have solved the issue by creating an __init__.py file in the models directory, and added the following line to it:

from .User import User

Then it worked.

inner flame
#

Hi myself Onkar and I am working on a Django Project. I am working on implementation of encryption techniques. This is my first project in Django.
Can anyone help me with the file handling in Django?
Condition: I want to encrypt file in my system and then immediately give user the key and encrypted file. I have code for file encryption using Fernet. Now all I need is solution to how to open the file in Django site??

#

def generate_key():
    key = Fernet.generate_key()
    with open("secret.key","wb") as key_file:                          key_file.write(key)
          return key
def load_key():
    return open("secret.key", "rb").read()
# keygeneration done
# encryting the file
def encrypt(filename):
    key = load_key()
    f = Fernet(key)
    with open(filename, "rb") as file:
        file_data = file.read()
    encrypted_data = f.encrypt(file_data)
    with open(filename, "wb") as file:e
        file.write(encrypted_data)

# decrypting the file
def decrypt(filename):
    key = load_key()
    f = Fernet(key) 
    with open(filename, "rb") as file:
        file_data = file.read()
    decrypted_data= f.decrypt(file_data)
    with open(filename, "wb") as file:
        file.write(decrypted_data)

key = generate_key()
file = __File-Name__
encrypt(file)
print("Your file has been encrypted.")
print("Your key for encryption is: ")
print(key)
decrypt(file)
print("Your file has been decrypted.")
#

This is my encryption code

true kernel
#

why does django need {load static}?

#

why is simply using images and other files not sufficient?

pliant shoal
#

Hello i got doubts in django DRF

proper iron
#

I'm working on this book, https://pgjones.dev/tozo/, that I aim to show how to build a production quality web app with a Python backend and React frontend starting from scratch. As well as building the app it includes how to setup your local computer, remote repositories and deployment. It has a companion codebase, https://gitlab.com/pgjones/tozo and the app itself is live at https://tozo.dev.

I'd really like to talk to you if this is what you are learning at the moment - specifically I'd like to know if this book makes sense, what it is missing, and whether it helps.

pliant shoal
#

Hello everyone, This doubt is about Django REST framework.
I am currently building a web app API from scratch. I'm totally new to django and web development. I have three models and each of them are linked in this order 1-2-3. I have serialised the data like the below code.

what I actually want is to make a API output like below:

Models1 {
pass
model 2 {
pass
model3 {

    }
}

}

and i want endpoints like this :

/api/v1/anime
/api/v1/anime?genre=

models.py - https://gist.github.com/jokerhacker22/6951d8667a32b069708884a296357c28#file-models-py

serializer.py - https://gist.github.com/jokerhacker22/219453bf3fdcbbeed316b98ab04cfebd#file-serializers-py

I am looking forward to get help from the experts here.
thanks in advance

Gist

GitHub Gist: instantly share code, notes, and snippets.

Gist

GitHub Gist: instantly share code, notes, and snippets.

thorny quartz
#

How to dynamically add / remove input fields in Django anyone help please ?

#

I am new in Django

pliant shoal
#

you mean adding and removing input fields in admin?

thorny quartz
#

i want to add and remove input fields in html using a button

#

like want to add a value then i have to click a botton to add a input field or if i want to delete a field then i can do that using a button

pliant shoal
#

that's some kinda intermediate level yet i'm also new in django

#

i can help with some basic one's

thorny quartz
pliant shoal
#

you are building this in front end?

#

i use django for backend only, tried react once for front end

thorny quartz
#

front end is for user and back end for us

#

that html page will be connected to sql to store values

pliant shoal
#

yeah

#

why not django admin or default cms?

thorny quartz
#

i didn't understand

pliant shoal
thorny quartz
#

yeah

#

i mean page will be connected to django as well sql for security

pliant shoal
#

Django default admin panel does this

#

connects to the database, you can view or edit data and you have security there

thorny quartz
#

default*

pliant shoal
#

you want to use any other database? like postgreSQL

#

you can do that easily

thorny quartz
#

i use postgreSQL alreday

pliant shoal
vestal hound
#

well, you can, but not easily

#

that sort of dynamism would be much better done with JS

#

on the frontend

thorny quartz
#

idk JS 😢

thorny quartz
#

can i make using html only or I really need js

#

@vestal hound

#

??

vestal hound
#

I wouldn't tell you to use JS

#

if it wasn't necessary

#

HTML and CSS alone

#

only allow you to create static pages

vestal hound
thorny quartz
#

😢 😢 😢 😢 thanks for the help bro can you please suggest any video or page so i can learn that

pliant shoal
#

like 1-2-3

pliant shoal
#

oh

pliant shoal
#

how?

thorny quartz
vestal hound
#
class ModelASerializer(serializers.ModelSerializer):
    b = ModelBSerializer()

    class Meta:
        model = ModelA

class ModelBSerializer(serializers.ModelSerializer):
    c = ModelBSerializer()

    class Meta:
        model = ModelB

class ModelCSerializer(serializers.ModelSerializer):
    
    class Meta:
        model = ModelC
        fields = '__all__'
#

like this

pliant shoal
#

and one more thing sir

#

i want to make a querystring in api endpoint the query will be one of the objects in the model

vestal hound
#

with an example

pliant shoal
#

let me sir

#

i am building a anime backend API

#

i have episodes models

#

season model which is foreign key to episode

#

and anime model which is foreign key to season

#

and as ya said i have made a enpoint like this /api/v1/anime/

#

where all anime will be displayed

#

here i want to filter anime which is higher in rating

#

rating, popularity , created_at and start_date

#
class Anime(models.Model):
    """Base Class for Anime models"""

    name = models.CharField(max_length=80, blank=False, null=True)
    slug = models.SlugField(max_length=50,help_text="Slug name", null=True)

    original_name = models.CharField( max_length=70, help_text="Original Name of the Anime(optional)", null=True, blank=True)
    description = models.TextField(help_text="Desription about anime.")
    cover_image = models.ImageField(upload_to="Anime/cover_images/", verbose_name="Anime Cover image")
    bg_image = models.ImageField(upload_to="Anime/bg_Images/", verbose_name="Anime Background Image")
    created_at = models.DateTimeField(auto_now_add=True)
    genres = ManyToManyField(Genre)

    rating = models.FloatField(
        validators=[MinValueValidator(0), MaxValueValidator(10)],
    )
    popularity = models.FloatField(
        validators=[MinValueValidator(0), MaxValueValidator(100)],
    )

    author = models.CharField(help_text="Author name of the anime", max_length=50)
    country_of_origin = models.CharField("Country Of Origin", max_length=20)
    start_date = models.DateField("Start Date")
    end_date = models.DateField("End date", null=True, blank=True)
    status = models.IntegerField(choices=RELEASE_STATUS, help_text="Current status of the anime")
    seasons = ForeignKey(Season, on_delete=CASCADE, related_name="animes")
    staffs = ManyToManyField(Staff)
    studios = ManyToManyField(Studio)

    def __str__(self):
        return self.name
    
    class Meta:
        ordering = ['id']
        verbose_name_plural = 'Animes'
vestal hound
#

WTGF

pliant shoal
#

my anime model

vestal hound
#

okay

#

so...

pliant shoal
#

i just want to filter the enpoint with querystring

dry crater
pliant shoal
#

Oh thnx

vestal hound
#

if I get what you're saying...

#

you want to extract optional arguments passed in the query string

#

and possibly use them to filter the returned results?

pliant shoal
#

yeah yeah yeah

#

you are right

#

how to do that

vestal hound
#

from the request

#

request.query_params

#

that would be a good start

#

(in your view)

pliant shoal
#
class EpisodeViewSet(NestedViewSetMixin, ModelViewSet):
    queryset = Episode.objects.all()
    serializer_class = EpisodeSerializer

class SeasonViewSet(NestedViewSetMixin, ModelViewSet):
    queryset = Season.objects.all()
    serializer_class = SeasonSerializer

class AnimeViewSet(NestedViewSetMixin, ModelViewSet):
    queryset = Anime.objects.all()
    serializer_class = AnimeSerializer

this is my views

#

I tried this but don't have any idea how to present it in urls.py

from rest_framework.routers import DefaultRouter
from rest_framework_extensions.routers import NestedRouterMixin

from api.views import (AnimeViewSet, EpisodeViewSet, GenreViewSet, NewsViewSet,
                       SeasonViewSet, StaffViewSet, StudioViewSet)

router = DefaultRouter()

router.register('episodes', EpisodeViewSet)
router.register('season', SeasonViewSet)
router.register('genre', GenreViewSet)
router.register('news', NewsViewSet)
router.register('Staff', StaffViewSet)
router.register('studio', StudioViewSet)

class NestedDefaultRouter(NestedRouterMixin, DefaultRouter):
    pass

router2 = NestedDefaultRouter()

animes_router = router2.register('animes', AnimeViewSet)
animes_router.register(
    'seasons', 
    SeasonViewSet,
    base_name='episode-seasons',
    parents_query_lookups=['episodes']).register('animes',
    AnimeViewSet, base_name='episode-seasons-anime',
    parents_query_lookups=['season__episode', 'season']
    )
vestal hound
#

if you're using generic views

#

then

#

you need to use...filters

#

this

#

or write a non-generic view

pliant shoal
#

ok

#

thanks for the proper guidance and help sir

#

ā¤ļø

vestal hound
#

yw! šŸ‘‹

austere relic
#

@cerulean badger did you figure it out?

cerulean badger
austere relic
#

pytube

cerulean badger
#

yea I just looked up docs

austere relic
#

alright

cerulean badger
#

why?

austere relic
#

I was gonna help you

valid charm
#

I am wanting to setup a database scheduler based on celery, similar to django-celery-beat but specifically for Flask. Does anyone know if there is a library / example of this?

past delta
#

@austere relic

austere relic
#

hi

#

go ahead

past delta
#

so can you help me display the reference webpage

austere relic
#

I still don't understand what that is

past delta
#

at least the webpage?

austere relic
#

if you wanna display a webpage open the url in your browser?

livid mason
#

Hey! Would anyone be up for helping with a Flask project?

#

I am completely new to using Flask but would love to finish creating a web application but I am a little stuck šŸ™‚

austere relic
#

just ask

valid charm
#

@austere relic any ideas on my question above?

austere relic
valid charm
#

ok thanks

livid mason
#

Thanks, does anyone know how I can create quizzes using Flask with a nice interface that allows for users to click one of the options and see if the answer is correct? And have the ability to add questions too....

austere relic
#

sounds like something you can do purely client side

#

oh, except for adding questions

livid mason
#

True, I am just not too sure where to start with programming the functionality....

austere relic
#

well, you know how to make a header that says "QUIZ", which is a start

#

so what exactly are you in doubt about?

livid mason
#

Yes, I am not sure how to create an interface that as 4 different options come up in boxes and be able to select them. Or how to have a form where you can input in questions. I am really sorry, I am quite a beginner!

austere relic
livid mason
#

No, only really Python unfortunately, though I have messed around a little with HTML.

pliant shoal
#

Oh

#

šŸ˜•

austere relic
#

alright well, you can get away without using JS

#

using the form element

#

however, I don't know how flask handles forms, so can't help you with that

pliant shoal
#

Django is better in handling data

livid mason
#

Thank you for the link, looks great.

austere relic
pliant shoal
#

Yeah

dusk portal
#

i dont have any big issue but sometimes i face problems while i work in drf in making exceptions

#
local variable 'serializer' referenced before assignment```
#
@api_view(['GET'])
@permission_classes([permissions.IsAuthenticatedOrReadOnly])
def detailview(request,post_id):
    if Post.objects.filter(id=post_id).exists():
        try:
            q2=Post.objects.get(id=post_id)
            serializer=PostSerializer(q2,many=False)
        except Post.DoesNotExist:
            raise Http404("NOT FOUND")
    return Response(serializer.data)
pliant shoal
#

Can someone tell me how I make AUTH_USER_MODEL for my User model

I have app named api which is installed in settings and I have models directory inside the api directory and in models directory I have accounts.py file having User model

versed python
#

Move the return inside try

dusk portal
#

done

dusk portal
versed python
dusk portal
versed python
#

Yeah

#

Inside the except block you need to return something

#

Not raise an error

pliant shoal
versed python
#

Django doesn't know how to convert exception to responses

dusk portal
#

ohh

dusk portal
#
@api_view(['GET','DELETE'])
@permission_classes([permissions.IsAuthenticatedOrReadOnly])
def detailview(request,post_id):
    if Post.objects.filter(id=post_id).exists():
        try:
            q2=Post.objects.get(id=post_id)
            q3=Post.objects.get(id=post_id).delete()
            serializer=PostSerializer(q2,many=False)
        except Post.DoesNotExist:
            raise Http404("NOT FOUND")
    return Response(serializer.data)```
#

this is current code

versed python
#

I already told you just do that

#

I'm on my phone so can't edit code anyway

dusk portal
#

ohk btw one last question that is in my mind @versed python

#

btw fixed that exception error

dusk portal
#

u can see code
In that q3 is to delete and my models are properly configured with foreignkey to identify which user is filling the form/post request
So i want only that user can delete only his/her Posts
I have done kind of same thing in e-commerce site so he/she can see only his/her order history
But it was ezz in that bcez i used for tag in html n all but in rest api we don't use html templates so how can i do that

#

@versed python

versed python
dusk portal
#

Umm like

#

Can u show