#web-development

2 messages · Page 232 of 1

native tide
#

well, im still 16 but im working on a small project rn with flask

#

its rlly stupid but

#

it was pretty fun to work on

golden bone
#

In that case I would focus on getting a degree after high school, but you're in good shape... I definitely didn't know how to do that at 16

native tide
#

yeah but its still pretty not good

#

i barely know how to put these stuff

#

its really unorganised

golden bone
#

looks fine to me, but it's all about practice, just keep at it and you'll keep getting more comfortable doing more challenging things

native tide
#

yeah, thanks

#

im rlly paranoid about my future haha

#

since i dont really see anything i do as good, i feel like the only good project ive done is my pico8 player thats virutally useless

#

as you have to go to the original website to get the games haha

#

...and it didnt even use flask

sudden sierra
native tide
#

yeah im playing with names rn

#

i didnt know how to make the app start from /catboys so i did it like that

#

lol

sudden sierra
# native tide i didnt know how to make the app start from /catboys so i did it like that

If you want to redirect users from / to /catboys when they visit / then create another view function that redirects the user to /catboys, see this answer:
https://stackoverflow.com/a/14343978/14169295

#

Ohh just I noticed you did something similar to handling HTTP 404 status code lol, btw 404 stands for "Not found", I guess you should rename that function to "not_found"

native tide
#

yeah ik

#

but i couldnt make it so / redirects to catboys

#

so i made it when it cant find anything it just sends you there

sudden sierra
native tide
#

ive been working so hard on this website and its finally looking up owo

ocean slate
#

your problem solved?

ocean slate
wind dove
#

So this site I'm working on will have groups, I want to have an option to create groups based off your school. Any ideas on how to do this while keeping some form of security in the sense of stopping anyone from joining any schools group?

#

I'm considering doing it off of school email but some schools limit emails from being sent/received from outside, untrusted domains. I'm thinking of possibly doing it through oauth but want more opinions first.

native tide
#

but

#

i dont think i can add this to my resume-

wind dove
half osprey
#

Hey guys I have a quetion about web scraping. Id like to get all the facebook posts my friend makes, but dont have a facebook account. Can I still do it?

indigo kettle
#

is it possible to see someone's posts without being their friend?

#

probably not

torn glacier
nova flower
#

Is async sqlalchemy worth it in fastapi?
Or should you do everything sync?

iron tusk
#

can someone help me

#

where do i fit python flask

#

in html css js

#

is python flask replaceing any of it

#

or is it a addition to any of it

#

i dont see the point of it really?

#

or is it to avoid JS

#

and under hood it deos translate to it still?

tender dust
#

Hi, how do I pass JS data to Flask?

severe lily
#

How do I set Flask Environment to Development? set FLASK_ENV=development ain't working

frank shoal
#

Also try FLASK_DEBUG=1

sacred cape
#

How can I write a program to make it interact with webpages on chrome, like I want it to react with the Discord reactions, every 10 min.

I want the script to be able to run even if chrome is minimised.

I don't have much experience in coding, but please tell me the libraries and other things I will require

Please tag me while answering

Thank you

obtuse robin
quick valley
#

Hi

obtuse robin
#

in javascript to call to the flask api

inland oak
serene prawn
deft crow
#

mhmm do someone know how to post into a django website?
im troubling with csrf tokens

delicate ore
#

need some help with flask
I'n my first route i'm sending a request to the second route
is there a way to share the client with them?

@app.route("/course/<int:course_id>")
async def course_route(course_id: int):
    async with httpx.AsyncClient(headers=headers) as client:
        responses: list[httpx.Response] = await asyncio.gather(
            client.get(course_url),
            client.get(f"{course_url}/public-curriculum-items"),
            client.get(f"/api/get-course-reviews/{course_id}")
        )

    return render_template("course.html", course=data)


@app.route("/api/get-course-reviews/<int:course_id>")
async def get_course_reviews_api_route(course_id: int):
    """
    Api route for getting course reviews also takes JSON 2 parameters page and page_size
    """

    return jsonify(data)
snow edge
#

how can I add a date field in django user authentication for storing user's date of birth?

sudden sierra
# snow edge how can I add a date field in django user authentication for storing user's date...

You can create a custom user model that inherits from AbstarctUser or AbstractBaseUser (Depending on if you want to change the authentication process or not) and add a DateField if you're just starting a project. Or you can extend the User model using one-to-one relation with another model.
See this article:
https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html

Simple is Better Than Complex

The Django’s built-in authentication system is great. For the most part we can use it out-of-the-box, saving a lot ofdevelopment and testing effort. It fits ...

sudden sierra
lapis spear
#

im just beginner is it still part of django?

obtuse robin
#

it is flask

#

i think

lapis spear
#

oh i see it thanks

sudden sierra
# native tide i dont think i can add this to my resume-

Why not? You can add stuff to it and make it a big project. Add user registration and authentication stuff, let users bookmark images, let the app send an email to users about popular entries every week, and many many other things you can do.
What you can do in this project you can definitely to it in another one.

hoary brook
#

@native tide Even if the topic isn't very serious, that project still shows your skills pretty well. As others have said, you can always expand it or transfer a lot of what you've learned to a different project. I'm working with Flask as well and never had any 'serious' projects, but I learned a lot from experimenting and ended up transferring much of that code to a 'proper' project - in my case that was an project/issue tracker.

native tide
#

hello guys

#

i need some help in css

#

is there anyone here???

#

so this is a <div> element, in which I am trying to add the "<_" text. But it seems no matter how I try to align it, it doesn't. So can someone pls tell how to center the text, vertically and horizontally in the box

#

it is horizontally centred, by doing text-align: center;, but how to do it horizontally??

obtuse robin
#

for css

native tide
#
.logo {
  border-radius: 25px;
  background: #2fc4ab;
  opacity: 0.5;
  padding: 20px; 
  width: 370px;
  height: 320px;
  margin-left: 180px;
  font-family: Product Sans;
  font-size: 200px;
  text-align: center;
}
obtuse robin
#

and of the <_

#

?

#

or is it just a giant text

native tide
#

its just a text yes

obtuse robin
#

if so pls put a div around that

#

and put all the styling for the text in that

obtuse robin
#

and the text divs position absolute

native tide
#
<div class="logo">
    <p><_</p>
  </div>

look ive wrote this in the html file

obtuse robin
#

oh okay, then just put a class for the p

native tide
native tide
obtuse robin
#

and so when you put the p tag as absolute, also put this in

top: 50%;
left: 50%;
translate: transform(-50%, -50%);
native tide
#

okay i'll

obtuse robin
#

the reason you put translate transform -50% is because the left and top 50% translation starts from the top left meaning you need to balance it and bring it to the center

native tide
#

oh lol its even more separated now... it has gone more far

obtuse robin
#

did you put the logo class as relative?

native tide
#

yes

obtuse robin
#

it’s either transform: translate

#

or translate: transform i forgot

native tide
#

lol

#

wait

#

i think i should delete the text portion in the logo class right??

obtuse robin
#

oh yeah 😭

native tide
#

i'll just copy and paste that part

obtuse robin
#

let me pull this up on my laptop real quick lmfao

native tide
#

lol

#

i've worked in css before too... but that was 2 years ago lmao... i've now forgotten almost all of it

obtuse robin
#

i see

native tide
#

what should i do now

obtuse robin
#
<style>
    .logo {
  border-radius: 25px;
  background: #2fc4ab;
  opacity: 0.5;
  padding: 20px; 
  width: 370px;
  height: 320px;
  margin-left: 180px;
  font-family: Product Sans;
  font-size: 200px;
  text-align: center;
  position: relative;
}

.logo_text{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -150%);
}
</style>
<body>
    <div class="logo">
        <p class="logo_text"><_</p>
      </div>
    
</body>
native tide
#

oh wow

obtuse robin
#

its just a bit buggy for some reason

obtuse robin
#

yea

native tide
obtuse robin
#

meaning its going upwards by 150%

native tide
#

yes

obtuse robin
native tide
#

wait

#

but thats not working for me

#

its just stuck for some reason

obtuse robin
#

send the code

native tide
#

okay

#

theyre two different files

obtuse robin
#

thats fine

native tide
#

should i send them both?

obtuse robin
#

yea

native tide
#

okay gr8

#
.header {
  padding: 30px;
  text-align: center;
  font-family: 'Product Sans';
  font-size: 40px;
  background-color: white;
}

.header p {
  font-size: 40px;
}

.logo {
  border-radius: 25px;
  background: #2fc4ab;
  opacity: 0.5;
  padding: 20px; 
  width: 370px;
  height: 320px;
  margin-left: 180px;
  font-family: Product Sans;
  font-size: 200px;
  text-align: center;
  position: relative;
}

.logo_text{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -150%);
}
``` thats the css
#

and

#
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Bash Commands</title>
  <link rel="stylesheet" href="style.css" />
</head>
<body>
  <div class="header">
    <h1>Bash Commands</h1>
    <p>Scripts made with Python!</p>
  </div>
  <div class="logo">
    <p class="logoText"><_</p>
  </div>
</body>
</html>
``` thats the html
obtuse robin
#

is the logo inside header?

native tide
#

no

obtuse robin
#

the class is named different LMAO

#

its okay weve all been there

native tide
#

😂

#

lol

#

wait i'll change it 😂

#

YES!!!

#

NOW IT WORKS!!!

#

SUCCESSFULLY

obtuse robin
#

there we go

native tide
#

yeah silly me

#

thanks a lot mate

obtuse robin
#

welcome welcome

#

absolute positioning is a life saver

native tide
#

i was working on that for more than 3 hours now... it finally worked

obtuse robin
#

when you want to create interesting looking things

native tide
obtuse robin
#

because positioning is very easy with it

native tide
#

yeah

obtuse robin
#

same with flexbox but you can be more creative with absolute positioning

native tide
#

hmm... i'd prefer absolute positioning

#

thanks again mate

#

now say if i want to change the background color of the entire website at once... can i do that??

obtuse robin
#

yes just do

body {
  background-color: color;
}
native tide
#

okay thanks

#

ah yes it works gr8

tall sentinel
#

.

robust tulip
#

Hey pls help me
<html>
<head>
<title>Practice test </title>
</head>
<body>
<h1 align="center">
Welcome to the world of the environment</font></h1>
<iframe width="560" height="315" src="https://www.youtube.com/embed/bKSGKFUBrGc" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</video>
</body>
</html>

Can u tell me the attributes nd tags

#

In this code

#

Plzzzzzz

#

@native tide @tall sentinel @obtuse robin @native tide

#

@west chasm

unique shore
#

refrain from pinging people

robust tulip
#

Sorry

#

Sorry

#

Ok can u help me

#

XD

robust tulip
unique shore
#

sure, but can you be more specific

robust tulip
#

Like attributes nd tags

#

In that code

#

It's an html code

#

A*

unique shore
#

html tags are just the things between the angle brackets

robust tulip
#

Nd tags?

#

Ohk

#

Ik

unique shore
#

<title> is a tag

robust tulip
#

About tags

#

Idk the attributes

unique shore
#

any other thing inside a tag like align is an attribute

#

src is an attribute

robust tulip
#

Ohk

robust tulip
#

Tysmmmmm

gusty sky
#

Hello guys, I am able to get a response with jwt token via axios in vue3, but it looks like setting the axios header with bearer and jwt token not work.

#
    async submit () {
      const credentials = {
          username: this.form.email,
          password: this.form.password
      }
      axios.post('http://127.0.0.1:8000/login', credentials)
      .then((response) => {
        localStorage.setItem('jwtToken', response.data.token);
        setAuthHeader(response.data.token);
        console.log(response)
      })
      .catch((err) => console.log(err.response));
#
import axios from 'axios';

const setAuthHeader = (token) => {
    if (token) {
        axios.defaults.headers.Authorization = {'Authorization': `Bearer ${token}`}
    } else {
        delete axios.defaults.headers.Authorization;
    }
};

export default setAuthHeader;
#

in main js i have this

if (localStorage.jwtToken) {
    setAuthHeader(localStorage.jwtToken);
} else {
    setAuthHeader(false);
}
#

it works fine with via curl. but it does not seem to be working via vue...

zealous elk
#

I am stuck at a JavaScript problem. The details are in #help-rice, please help me

ionic raft
native tide
#

and noww im angy

#

why wont it work

#

i did everything every tutorial told me

#

anyone knows what to do?

#

i alr have my project interpreter configured

sudden sierra
native tide
#

i did

#

like 4 times

sudden sierra
native tide
#

still nothing,,

sudden sierra
sudden sierra
native tide
#

hm

#

maybe those errors mean smth?

sudden sierra
native tide
#

okay i am restearting my laptop

#

when life gives you error

#

turn it off and on again

sudden sierra
#

I guess it has nothing to do with the laptop, but it never hurts to restart

native tide
#

nothing

#

i am losing hope

#

i need that tb to save the links from the images

#

so it can show it on the bookmark section

sudden sierra
# native tide i am losing hope

You should be able to use flask_sqlalchemy if it's installed, it's just VSCode that's complaining, and run the app from the terminal

native tide
#

i can try

#

idk how to activate my venv from the terminal tho

#

i would have never switch from pycharm if it wasnt so expensive to use css :/

sudden sierra
native tide
#

thankss

#

oh youre right

#

thanks

#

so from now on,, only terminal

#

UGH

#

i swear im gonna switch to atom

sudden sierra
#

No problem
Definitely it's good thing to get used to the terminal

native tide
#

yay

daring isle
#

How are we handling multiple entries for a single column ?
I’m tempted to abstract it with a linked table . But is it normal to maybe put some sort of delimiter for the values instead ?

#

So option1;option2;option6

#

More specifically when it comes to database storage

#

Or would it be better to create a reference table and say
Id 1 - related table id 4 - value option1

Id2- related table id 4 - value option2 etc

gilded hound
#

hey any idea on how to fix this ?

mystic wyvern
zealous elk
#

I am not getting my desired output in a flask app I am working on. The details are in #help-coconut, please help me

tepid shard
#

how are web browser games…made?

native tide
#

Js

tepid shard
#

hm, ok

polar bison
#

Is it feasible to build a website using Django through which a user can perform data analysis on a file they have stored on their local machine?

manic garnet
#

i wanted to show a project i made

#

its a platform to share your secrets and confessions openly on the internet

#

but anonymously

native tide
#

It‘s

#

Quite

#

Black

manic garnet
#

That's the theme

#

Of the site

steel delta
#

Hey I've been following this tutorial step by step
https://youtu.be/CTrVDi3tt8o?list=PLCC34OHNcOtqW9BJmgQPPzUpJ8hl49AGy
and I followed whatever was in here but why do I get an error like this?

In this video we'll start to build out the user authentication system by creating a login page.

Django comes with a pretty nice user authentication system that we'll tap into and use for all of this.

First we'll create a new 'members' app to hold all of our authentication stuff. Then we'll create a login page that allows users to log in.

#d...

▶ Play video
eternal blade
#
class MessagesViewSet(viewsets.GenericViewSet, mixins.ListModelMixin, mixins.CreateModelMixin):
    pagination_class = pagination.PageNumberPagination

    def get_queryset(self):
        # The pagination limit is set to 50 items per page,
        # so we don't need to use .limit here
        return Message.objects.filter(chat__id=self.kwargs["chat_pk"])

    def get_serializer_class(self):
        if self.request.method in ("POST", "PATCH", "PUT"):
            return MessageCreateSerializer
        else:
            return MessageSerializer

    def perform_create(self, serializer):
        serializer.save(chat_id=self.kwargs["chat_pk"])
``` When a new message is being created I want to use `MessageCreateSerializer` but when the data is returned I want to return the representation from `MessageSerializer` since it gives a more full serialization, any way to do that?
sudden sierra
sudden sierra
eternal blade
#

when returning a response I want to serialization of MessageSerializer

sudden sierra
#

Try it out, I have to go right, now, I have a meeting

#

If things didn't go well ping me

eternal blade
steel delta
eternal blade
native tide
#

its trying its best lmao

eternal blade
#

I'm using PageNumberPagination to paginate the messages, but how do I order the messages at by the created_at field

mystic wyvern
sudden sierra
eternal blade
#

oh

#

how can i do that, the last time i checked the only way was to only subclass the mixins i needed

eternal blade
sudden sierra
eternal blade
#

thanks lemon_pleased i did not know that

sudden sierra
sudden sierra
sudden sierra
viscid valley
#

With Django's admin, is it possible to use non fields, like custom functions inside of inlines? I always get field not found.

#

For instant list_display for inlines, or any way to add to them

#

Aaaahh readonly_fields is the solution

steel delta
dusk totem
steel delta
digital hinge
#

Hi all,
I’m trying to make a website that can show results from my SQLite database, something like this: https://imgur.com/xNP95TA
I’m wanting to query a database of
information and narrow down the
query via multiple simultaneous user inputs. Anyone have something that may be able to give me a headstart? Cannot find much on GitHub

#

Like a live filter fields

main jasper
#

Flask + SqlAlchemy: Is it good practice to use data model classes for general purposes across the app? Example class Order will not only store data, but will process order logic, calculate package weights...

distant storm
#

Django can do the work too.

harsh ivy
#

hey guys I am making a website and I am using cdnjs libraries to import files (linked to my html file) that allow my site to include a box slider. I was wondering how do I edit the default code that is in a cdnjs library and change the css?
thanks

dusk totem
worthy lake
#

is anyone here good at tailwindcss?

#

like, in terms of being good at implementing your designs

#

with it

#

what resources did you use to learn the framework?
I love the lack of dependencies it uses... but im not good at it

#

i need to learn all the classes i suppose.

sullen pilot
#

hey can you help me with flask

golden bone
late gale
#

is there a way to automate my workflow with REST like whenever I add a recipe on my app I need to fill 8 forms lol

#

or just make it bit easier because this job is tedious

shy current
#

Hey people, do you know any way to do SSO integration of social media, with Python? using Django Rest Framework like login and such authentication?

#

perhaps an good nowdays tutorial.

#

Thank you so much since there

dusk totem
lavish prismBOT
#

Integrated set of Django applications addressing authentication, registration, account management as well as 3rd party (social) account authentication.

late gale
#

and here's a video how to use it
https://www.youtube.com/watch?v=NG48CLLsb1A

In this video, I talk about how to set up Google authentication for your Django project.

https://learn.justdjango.com
☝ Get exclusive courses & become a better Django developer

New to Django Allauth? Watch this tutorial
https://youtu.be/dXZim_jgaiI

✌️ Stay in touch

Facebook: https://www.facebook.com/justdjangocode
Instagram: https://www.inst...

▶ Play video
solar nexus
#

interesting...

#

ah yes

native tide
#

does flask and js mix well together?

brisk mortar
#

How to move top block left down

willow root
#

give it a class (or select it however you want) and to that class write display: flex

digital hinge
#

Yep without hitting submit would be better, so Ajax magic maybe 🙂

wooden ruin
# native tide does flask and js mix well together?

flask is a backend server library. js is a language that is commonly used on the frontend of applications. they don't depend on each other as they have different purposes. however yes you can use js to talk with a flask server

worthy lake
#

It can be very simple or very not simple. It depends on how much communication has to go on between front and back.

#

if its more than just light effects here and there, it usually makes the app very complex and on another level if you are just starting out with web apps.

#

but that is what you call a "fullstack application", one with heavy js interface and a backend api.

modest zodiac
#

can fastapi serve basic html pages or do i need to use flask for that

worthy lake
#

you dont need flask to serve static html if that is what you mean. any web server can do that.

sudden sierra
native tide
#

Hello.
I tried to create a model on my new Django project, using the following code in my models.py file:

from django.db import models

class userProfile(models.Model):
    userID = models.IntegerField()

afterwards, I inserted "userProfile" into my installed apps in settings.py

then I typed makemigrations in my terminal but I get this error:

ModuleNotFoundError: No module named 'userProfile'

Any ideas on what I'm doing wrong?

sudden sierra
tired fable
daring isle
#
export const ReportForm = (props) => {

Can we not pass props to export const components?
Nothing im trying is working

#

undefined

royal ferry
#

can anyone here please tell me what's the use of "span" !?!?

dusk totem
# royal ferry can anyone here please tell me what's the use of "span" !?!?

According to the MDN, it's basically nothing. https://developer.mozilla.org/en-US/docs/Web/HTML/Element/span

The HTML element is a generic inline container for phrasing content, which does not inherently represent anything. It can be used to group elements for styling purposes (using the class or id attributes), or because they share attribute values, such as lang. It should be used only when no other semantic element is appropriate. is very much lik...

royal ferry
#

could've just said it's an inline container

dusk totem
#

Well its used for styling and other things. So its an element that doesn't do anything and we can practically abuse it in HTML markup

royal ferry
#

yea just tried it in some examples

limber basalt
#

sidebar css file

.vertical_navbar ul {
    position: absolute;
    list-style-type: none;
    margin-top: 116px;
    padding: 0;
    width: 250px;
    height: 100%;
    top: 0; 
    left: 0;
    bottom: 0;
    background-color: white;
    box-shadow: 17px 0px 14px -19px rgba(0, 0, 0, 0.45);
}

.image_section {
    background-color: #F8F5F5;
}

.navbarImage {
    width: 200px;
    height: 200px;
    margin-left: 20px;
}

.navbarIcon {
    float: left;
    width: 30px;
    height: 20px;
    padding-right: 10px;
}

.dropdownIcon {
    float: right;
    width: 33px;
    height: 20px;
    padding-left: 15px;
}


.collapsible.active .dropdownIcon {
    transform: rotate(-180deg);
    -webkit-transform: rotate(-180deg);
    float: right;
    width: 33px;
    height: 20px;
    margin-right: -15px;
}

.vertical_navbar li a {
    display: block;
    color: #000;
    padding: 8px 20px;
    text-decoration: none;
    font-family: 'Open Sans', serif;
}

.vertical_navbar li a.active {
    background-color: #2176FF;
    color: white;
}

.vertical_navbar li a:hover:not(.active) {
    background-color: gray;
    color: white;
    ;
}

.content {
    max-height: 0;
    overflow: hidden;
    transition: max-height 0.2s ease-out;
    text-align: center;
}

how do i dynamically increase the height of the side bar as more <p></p> content are added?

frank shoal
#

Use min-width instead of width

#

Er, height

limber basalt
frank shoal
#

Which class is this?

#

Content?

limber basalt
#

_sidebar.handlebars

<div class="vertical_navbar">
    <ul>
        <li class="image_section"><img src="/img/defaultUser.png" alt="User icon" class="navbarImage"></li>
        <li class="collapsible"><a class="active" href="#MyProfile"><img src="/img/profile.png" alt="icon"
                    class="navbarIcon">My profile<img src="/img/triangledown.png" alt="dropdown"
                    class="dropdownIcon"></a></li>

        <div class="content">
            <li><a href="#changePassword">Change password</a></li>
        </div>
        <li><a href="#MyPurchases"><img src="/img/schedule.png" alt="icon" class="navbarIcon">My purchases</a></li>
        <li><a href="myRewards"><img src="/img/voucher.png" alt="icon" class="navbarIcon">My rewards</a></li>
    </ul>
</div>
#

the content class is a dropdown list under "My profile"

native tide
#

am i a real web dev guys

lavish dirge
#

Hello, guys. I have faced with problem of converting tdata (telegram api) to json file, opentele does not help me. What could you recommend to me?

zealous elk
# native tide am i a real web dev guys

Depends on whether or not you've built actual websites that you've deployed out there or whether you've helped in the development of one that was deployed

#

I'd say you're a web dev as soon as you start learning about web dev, but you won't be recognized as one until you have some projects to your name

zealous elk
lavish dirge
#

Thanks🤝.

zealous elk
#

Lastly, if you can't find any libraries, use the existing libraries to create your own library. Although I won't recommend doing so until you've thoroughly done your research

#

I tried to create a custom library for MySQL for a flask project of mine and it was a horrible experience. Eventually, I got around to using the SQLAlchemy library

#

So I can speak from experience

#

Anyway, good luck 👍

native tide
#

That's actually really useful

#

Thanks

zealous elk
#

I'm quite a novice myself so I can't distinguish between jokes and well, serious stuff ¯_(ツ)_/¯

zealous elk
native tide
#

Gorls

#

It's still in early access

zealous elk
#

Good luck 👍

wide harbor
#

Hi so I've a question regarding how to solve an error with a form updating /creating model. Details are in help-donuts. Its a simple enough problem I can tell that, very simple. However I've not managed to get anyone to tell me how to resolve the issue in a way that will make it do what I want. So asking on here. Thanks.

native tide
#

Hey, for django testing do you use: built-in django unitest? pytest? django-pytest? Thank you for your answer

zealous elk
#

@native tide from what I know, PyTest seems to be the best option

native tide
#

Hello all, i have a question about Django/IPFS/Video

#

I need a little help about video loading on IOS. Videos are stored via IPFS.

#

Players work well on Desktop but on IOS, the video never load

native tide
hexed current
#

hello

#

I need help with something

#

now, is it possible to to post a parameter that is not listed by a specific api

#

{
  "sleep_time": {
    "end_time": null,
    "enabled": false,
    "start_time": null
  },
  "use_cookie_personalization": true,
  "trend_location": [
    {
      "name": "San Francisco",
      "placeType": {
        "name": "Town",
        "code": 7
      },
      "woeid": 2487956,
      "country": "United States",
      "url": "http://where.yahooapis.com/v1/place/2487956",
      "countryCode": "US",
      "parentid": 23424977
    }
  ],
  "language": "en",
  "discoverable_by_email": true,
  "always_use_https": true,
  "protected": false,
  "geo_enabled": true,
  "show_all_inline_media": false,
  "screen_name": "oauth_dancer"
}
```\
#

like for example here, I would like to change "protected" to true

#

but, the twitter API is not listing it as a parameter

native tide
#

hi im currently building a chat application using flask and using ngrok to change its url every launch so only users in the know can access it. however im running into an issue where when i use ngrok to connect to the site it shows the ip as localhost and doesnt let me use request.user_agent to gather data such as platform,language and browser which is necessary for fingerprinting users for bans etc. is there any alternative to using ngrok or any way i can make it still able to get the client ip and user agent data?

#
data=f"""
ip: {get_remote_address()}
platform: {dataagent.platform}
browser: {dataagent.browser}
version: {dataagent.version}
language: {dataagent.language}
useragent={dataagent.string}"""
``` code for getting user data
#

dataagent=request.user_agent btw

#
ip: 127.0.0.1 
platform: None
browser: None 
version: None
language: None```output from above code on request via ngrok
pallid hill
native tide
pallid hill
native tide
#

using the same base for my chat app

pallid hill
native tide
#

i also have a similar issue

pallid hill
#

Well then, maybe you can help.

pallid hill
#

What's ur issue?

native tide
#

my messages dont always send to the server and i think its an issue with socketio

pallid hill
#

hmmm I see.

#

I want to be able to send file through the chat app.

native tide
#

ill enter text click send but the message doesnt actuallly get sent to backend

dim rover
#

I have some selenium code I wanted to share in case it helps someone simplify their code and/or remove explicit sleeps

from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.remote.webelement import WebElement

def wait_for(selector: str) -> WebElement:
    """
    Wait for and return the element matching `selector`.
    
    Waits until an element matching the specified
    CSS selector becomes visible and interactible,
    after which the first such element is returned.
    """
    return WebDriverWait(driver, 10).until(
        EC.visibility_of_element_located(
            (By.CSS_SELECTOR, selector)
        )
    )
#

was able to remove all sleeps from some selenium code. Usage is just:

wait_for("button.any-button").click()```
#

oh it is expecting a webdriver instance named driver for brevity's sake; update that if you're calling it something else or make it a parameter if you prefer

native tide
#

this is my webpage... so i have a navigation bar at the top of the page... but i want the text in it to be in the center... it just doesnt work no matter how i try it... i tried to use margin... but the text gets separated a lot from each other... pls help me with this

#

anyone??

minor sedge
#

i'm trying to learn django, everything is fine, i'm loading templates i even have like a main html, but when i try to load some data with a for loop in another html it just won't load

#

what part of the code should i send, so you guys could help me ?

daring isle
hearty pendant
#

hi, can anyone search on Google thefacepeek.netlify.app

rustic sequoia
#

Using flask
i want to render a template i made before
but i get TemplateNotFound Error

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

how to i fix the path?

vernal thistle
#

I am creating a flask app which is basically an UI for the API of a game. The user should be able to enter their private API key and this key will be used to make requests to the game's API from this flask app. What is a good way to store this key without the user having to create an account? Is using the session storage or local storage a good idea? Or should it be handled on the server side, and if yes, how?

tidal ore
#

Can somebody recommend a basic CMS: minimum of features, zero or minimum dependencies, production ready?
I'm looking to quickly build a small website, but hoping that it's good enough to build on it a few features.

tidal ore
vernal thistle
tidal ore
#

anytime VVoozy

rustic sequoia
vernal thistle
#

All small I think. templates

rustic sequoia
#

yeah like it is...

vernal thistle
#

Still doesn't work?

rustic sequoia
#

nope

rigid yoke
#

I don't think that you can have index.py in another folder

vernal thistle
#

Is templates in the same directory as index.py?

rustic sequoia
#

now it worked, thank you :D

#

my images dont load but i think i will figure this out later

crystal quiver
#

Or make the topnav display:flex and then justify-content: center;

thorny quartz
#

hey guys I want to ask that vscode is better or pycharm for djangp

#

django

#

do pycharm has extensions like vscode ?

thorny quartz
#

ok

#

thanks bro

unkempt sky
#

hey!!, can someone please help me with middleware structure in flask

robust kettle
#

hi this might be a noob question but how is python helpful in web development? is it used for back-end?

tidal ore
#

yes

robust kettle
#

oh sweet thanks

tidal ore
#

np

#

Skelly just write the question, somebody may know the answer

brisk mortar
#

Why is the square rotated but not enlarged?

ionic raft
ionic raft
# robust kettle hi this might be a noob question but how is python helpful in web development? i...

Yes. Flask and Django are the two most popular web dev frameworks. Flask is simpler; Django is enterprise grade. You use Python to code the application and database layers. You use html to structure front-end web pages, css to style them, and js/htmx to manage dynamic behaviour.

In short, Python is very helpful in web development. With the width of the community combined with the depth of Python libraries, there is a lot that can be accomplished.

minor sedge
#
    <h1>You can see info here about the {{product.name}} desk</h1>
    <h3>Price: {{product.price}}</h3>
    <img src={{product.preview}} alt="{{product.name}} Preview">
"GET /product/images/gseriesbk/image1-gseriesbk.jpg HTTP/1.1" 404

from flask import Blueprint, render_template, request

views = Blueprint(__name__, "views")

ids = ["gseriesbk", "gserieswh", "88seriesrb"]

desks = {
    "gseriesbk": {"name": "G Series", "color": "Black", "price": "7.200.000", "preview": "./images/gseriesbk/image1-gseriesbk.jpg"},
    "gserieswh": {"name": "G Series", "color": "Black", "price": "7.200.000", "preview": "./images/gserieswh/image1-gserieswh.jpg"},
    "88seriesrb": {"name": "88 Series", "color": "Red & Black", "price": "12.900.000", "preview": "./images/88seriesrb/image1-88seriesrb.jpg"}
}

@views.route("/")
def home():
    return render_template("home.html", ids=ids, desks=desks)

@views.route("/product/<desk>")
def product(desk):
    desk = desks.get(desk)
    return render_template("desk.html", product=desk)
#

i'm trying to load a picture in flask, but i get an 404 error for the image

robust kettle
#

aiming to learn to automate some daily things I do and expand my vision on what it can be used for

ionic raft
# robust kettle thanks for this elaborate response, htmx is news to me! I've definitely been int...

htmx is a way of partially updating web-pages (like Ajax but without the Ajax). I started with Python last April. It came up as a powerful language for web development. By June I was into Flask, by July Django. Now, I'm on my third deployed Django project.

Python can be used for a LOT of things. And when it comes to web development, the end results are very, very fast websites. When I compare the speed of the projects I've built (with considerable application complexity) with many web applications out in the wild I'm always pleased by how snappy the web apps built on Python feel.

brisk mortar
#

Why is the square rotated but not enlarged?

robust kettle
robust kettle
ionic raft
brisk mortar
robust kettle
steep mural
#

.

ionic raft
# ionic raft I'm currently trying to resolve a use-case on a Django project. Here's the quest...

Someone provided an answer. When using pre-build functions, be sure to import them! face palm

Here is the answer. If you need to conditionally order a filtered query, here's a direction you can take:

from django.db.models import Case, F, Q, Value, When

        reading_progress = ReadingProgress.objects.filter(user__username=self.request.user)\
            .annotate(
            date_to_display=Case(
                When(reading_progress='1) On Reading List', then=F('date_added')),
                When(reading_progress='2) Reading In Progress', then=F('date_started')),
                When(reading_progress='3) Completed Reading', then=F('date_completed')),
            )
        ).order_by(
            'date_to_display',
            ''
        )```
native tide
#

Django question: Why do we put our apps in this format:

'users.apps.UsersConfig'

in the installed_apps area of the settings.py file instead of just typing

'users'
proper hinge
native tide
indigo ether
#

This is not for python, but html and css, how do u scale an image down, like I have a logo its current wxh is 2048x2048 how do I scale it down so it will fit and look good in the navbar (either reply, dm, or @ me)

frank shoal
#

With <img>?

#

You should just need to set the width and height

indigo ether
#

In css?

proper hinge
#

You can set the dimensions of the image in HTML. They are attributes of the img tag e.g. <img src="..." width="200" height="200/>

#

If you don't need to image to scale dynamically then that approach is fine.

#

If you do need it to scale dynamically, you could use object-fit in CSS or width and height in CSS.

wooden ruin
# ionic raft htmx is a way of partially updating web-pages (like Ajax but without the Ajax). ...

python-based server frameworks also really integrate well with asgi deployment which can provide reeaally fast asynchronous operations on servers. my only drawback about django in particular is that there's not much availibility for alternative libraries. for example it's really difficult to switch to a different ORM if you like a different one. i've recently switched to nestJS from django and haven't really looked back. i like it because it comes with all the batteries included as django does, but you also get to kind of pick-and-choose your functionality based on the wide options of different libraries ready do to a task

ionic raft
daring isle
#

Are you guys serving your react and django on individual deploys or combining them into one ?

I’m running on heroku for django and Netlify for React at the minute but wondering if that’s best when I push it to production

true falcon
#

Hi, I am trying to upload photo from gallery in phone to flask but i get
ImmutableMultiDict([('file[]', <FileStorage: '' ('application/octet-stream')>)])

when i print the file can anyone help me how to upload file from gallery ?

covert crystal
#

Guys, what is the best approach here? To have logic handling all 3 forms in the welcome endpoint or to redirect to 3 different endpoints which will handle it separately?

@app.route("/welcome", methods=["GET", "POST"])
def welcome():
    if current_user.is_authenticated:
        return redirect(url_for("index"))

    loginForm = LoginForm()
    if loginForm.validate_on_submit():
        print("LOGIN")
        flash(
            "Login requested for user {}, remember_me={}".format(
                loginForm.username.data, loginForm.rememberMe.data
            )
        )
        # logic authorizing the user
        return redirect(url_for("login"))

    signUpForm = SignUpForm()
    if signUpForm.validate_on_submit():
        print("SIGNUP")
        return redirect(url_for("signUp"))

    resetPasswordForm = ResetPasswordForm()
    if resetPasswordForm.validate_on_submit():
        print("RESET")
        return redirect(url_for("passwordReset"))

    return render_template(
        "welcome.html",
        loginForm=loginForm,
        signUpForm=signUpForm,
        resetPasswordForm=resetPasswordForm,
    )
#

Not sure which option is better, to have it in one bigger module, or to have it in separate endpoints and risk it being 'too' modular

dusk sonnet
#

Hey, i have just deployed my chat app on heroku however im having a few problems. One of which i cant actually login using the https url because i get a 403 forbidden error. I can only login using http in the url. Anyone know why this is the case?

dusk sonnet
#

someone helped me fixed it not long ago

#

although i still got an issue where the time is displayed in utc but when i was using it on local machine it was proper

#

ah ok

#

jesus

#

insane

sudden inlet
#

hello! a random question. is there a way to search YouTube videos without using YouTube data API?

vernal thistle
#

I have a kind of vague question. In Flask + Jinja2, without any frontend framework, what is a nice way to use view functions which needs to return a lot of data in its parameters, e.g.; return render_template('template.html', param1, param2,...,param10)? I think it's better to jsonify the response and handle the json in the templates somehow, but is there a standard acceptable way to do this?

#

Or is it better to simply bundle the parameters in a dictionary and access them with Jinja?

tidal ore
#

you can pack/unpack the parameters

#
params = {
    'param1': 1,
    'param2': 2
    }
return render_template('template.html', **params)
vernal thistle
#

Thanks, didn't think about this

sudden inlet
#

i know about selenium but need to check beautiful soup

lapis spear
#

i am learning django

#

this is django framework
if my user form is this raw and i intentionally tried to put 2 different passwords why i am not getting the {{form.errors}} when i am trying to render it on my template is it because all warnings are already shown?

#

this is the template

gusty sky
#

yo guys just a question. when using vue app in developer mode via npm run serve it always reload when content is changed. Is it possible to keep this feature when i wont run it in developer mod ?

sudden inlet
tidal ore
#

yeah, why wouldn't it

wooden ruin
jade spindle
#

what is the correct way to update user avatar field ?

#

can someone help please

thorny quartz
#

request.POST or None means none data will be saved in sql or something else ?

tidal ore
wet cliff
olive thistle
#

anyone have a minimal http server recommendation?

  • I am running this in prod
  • I do not need templating; I'm not serving HTML; just responding with JSON
#

CherryPy seems reasonable

proper hinge
#

I think Falcon has some dependencies, but very few.

#

Actually no, it has none.

#

I used it for a dead simple HTTP REST API that operates on JSON. Worked perfectly.

#

Also had support for jsonschema validation so I used that too.

olive thistle
#

tyvm

brittle trail
#

Hi, I wanna ask about customization Registration and Login forms.

I use from django.contrib.auth.forms import UserCreationForm. And I want to set only 4 field in User models, name, username, password, avatar. What should I do step by step?

gusty sky
#

@wet cliff I want to develop in production py_guido

native citrus
#

any pros want to help a brotha out lol

crystal quiver
sudden inlet
sudden inlet
tidal ore
#

the limits are imposed by youtube, not the library

burnt agate
#

Hi there, I am trying to generate pdf form a html template in Django. After unsuccessful attempts with xhtml2pdf or weasyprint I managed to get it work with headless chrome (django-hardcopy). However now I have deployed my app to Heroku, and need to somehow connect django-hardcopy with chrome buildpack installed on Heroku. In development, for django-hardcopy, I used a local path for chrome.exe. Now I need to somehow redirect my hardcopy to get chrome form heroku buildpack. Any hints on how to do this? I am using the official chrome buildpack https://elements.heroku.com/buildpacks/heroku/heroku-buildpack-google-chrome

thorny quartz
#

I am trying to share a file using blob using but file name is changing in only android can anyone help me ik this is python server but i am not getting answer from javascript server so post it on here

async function WhatsappShare()
{
var fileArray = [];
for (i = 0; i < document.getElementsByClassName('divclass').length; i++)
{
sid = document.getElementsByClassName('divclass')[i].id;
if (document.getElementById(sid).querySelector("#txtImgLink").value != "")
{
var _ImgLink = document.getElementById(sid).querySelector("#txtImgLink").value;



var blob = await (await fetch(_ImgLink)).blob();
var file = new File([blob], "Test.jpg", { type: blob.type });



if (blob.type == 'image/png' || blob.type == 'image/jpeg' || blob.type == 'image/webp')
{
fileArray.push(file);
}
}
}



if (fileArray != '')
{
navigator.share({ title: "Sharing from Vikas Portal", files: fileArray });
}
else
{
GetDocumentAlt();
}
}```
this is my code
kind beacon
wheat verge
#

I have a simple question .How does the template get access to the models objects when nothing is passed to the template

Like for example in function based view
s=Student.objects.filter(id=1) return render(request,' template.html',{'s':s})
we do something like this and then we can use the objects in s in the template....but how does this work in Class based view?

paper yacht
#

it's really simple,

novel stream
novel stream
wheat verge
paper yacht
wheat verge
novel stream
paper yacht
#

yeap

wheat verge
#

ok thank you....

#

is it same for form view?

#

like in fbv we made the object of form class then we pass it to the template so is it done automatically in case of formView

novel stream
zinc prawn
normal token
#

hey guys, how to have two django projects running on different ports communicate with each other?
Is there even a tutorial for this?

hexed stream
#

see it

<!doctype html>
<html>
<head>
<title> INDIA </title>
</head>
<body>
STATES OF INDIA <hr>
<ol style="list-style-type:lower-roman">
<li> ANDHRA PRADESH </li>
<li> ARUNACHAL PRADESH </li>
<li> ASSAM </li>
<li> BIHAR </li>
<li> CHHATTISGARH </li>
<li> GOA </li>
<li> GUJARAT </li>
<li> HARYANA </li>
<li> HIMACHAL PRADESH </li>
<li> JHARKHAND </li>
<li> KARNATAKA </li>
<li> KERALA </li>
<li> MADHYA PRADESH </li>
<li> MAHARASHTRA </li>
<li> MANIPUR </li>
<li> MEGHALAYA </li>
<li> MIZORAM </li>
<li> NAGALAND </li>
<li> ODISHA </li>
<li> PUNJAB </li>
<li> RAJASTHAN </li>
<li> SIKKIM </li>
<li> TAMIL NADU </li>
<li> TELANGANA </li>
<li> TRIPURA </li>
<li> UTTAR PRADESH </li>
<li> UTTRAKHAND </li>
<li> WEST BENGAL </li>
</ol>
</body>
</html>

plain seal
#

Im using Pub/Sub and Compute Engine. I create a Message from my Django Backend and then also create a Compute Engine instance. The Compute Engine then pulls the message.

Code in the Compute Engine

    def callback(message: pubsub_v1.subscriber.message.Message) -> None:
        cloud_logger.info("Received message: {}".format(message.data))
        # decode message data back form bytes to string
        data = json.loads(message.data.decode('utf-8'))

        try:  # try to create model
            create_model(data['target'],
                         data['uid'], data["model_id"], data["mode"], data["user_type"], bucket)
        except Exception as e:
            exception_type, exception_object, exception_traceback = sys.exc_info()
            filename = exception_traceback.tb_frame.f_code.co_filename
            line_number = exception_traceback.tb_lineno
            cloud_logger.error("Error: {}".format(
                exception_type, exception_object, exception_traceback, filename, line_number))
            update_model(0, data['uid'], data["model_id"], 0, "", "failed", data["user_type"], str(e))
        message.ack()

    streaming_pull_future = subscriber.subscribe(
        subscription_path, callback=callback)

    with subscriber:
        try:
            cloud_logger.info(
                "Listening for messages on {}..\n".format(subscription_path))
            streaming_pull_future.result(timeout=30.0)
        except TimeoutError:
            cloud_logger.error("TimeoutError")
            streaming_pull_future.cancel()
            self_kill_engine()

Its receiving the message but then instantly throws a TimeoutError. It worked before when my Compute Enginge started faster, but now it has a longer taking start-script. Does this effect the timeout in the .result() function ? Because the code is getting executed after everything else is installed from the start-script

merry lake
#

@normal tokenmaybe you need a system of passing messages from one to the other

merry lake
# normal token elaborate?

I dunno, it could be as simple as having a dir somewhere on each site, which the two sites where the dir is, would check it periodically

wooden ruin
#

django is a very "heavy" framework, so it might not be suitable for a microservice approach

normal token
nimble epoch
#

Hi can anyone help me with uploading file from react

#

when i choose the image, i get something like C:/fakepath/filename.jpg.

#

seems django doesnt support that path. how can i get rid of it

wooden ruin
#

i've heard it's pretty good. haven't gotten around to reading it myself, but it should give you a solid insight into microservices

rain tree
#

can someone here help me with flask

frank shoal
#

ask a question

#

(this is a threat)

rain tree
#

i dont know how to make a flask api public

#

currently uses 127.0.0.1

frank shoal
#

First, you need a hosting service.

rain tree
#

i dont need

#

i have a server at home

#

i run it on that

frank shoal
#

You have a public ip already?

rain tree
#

yes

#

i have a server which i host my website on

frank shoal
#

You should use gunicorn to host a production server, then link it to a proxy application like nginx

rain tree
#

what is a proxy aplication?

#

what will that do?

frank shoal
#

what do you currently use as a web server for plain files?

#

nginx or apache?

rain tree
#

apache

frank shoal
#

In that case, you can install mod_wsgi

rain tree
#

yes

#

wait

#

so

frank shoal
rain tree
#

can i use flask

#

or do i need a different framework

frank shoal
#

flask is a wsgi implementation

rain tree
#

ok

frank shoal
rain tree
#

ok

frank shoal
#

fyi your package manager probably has mod_wsgi already if you're using the system python instead of a virtualenv

rain tree
#

ok

#

if i run the api on a public ip what port should i use?

frank shoal
#

should be port 80.

rain tree
#

ok

frank shoal
#

Consider using a virtual host so traffic is routed based on the Host header.

rain tree
#

ok

#

ok

#

but

#

how can i make the api public

frank shoal
#

Are you port forwarding? Maybe using a no-ip service?

rain tree
#

i am port forward

#

i think

frank shoal
#

Then using your public ip should work.

rain tree
#

yes

#

but as i said

rain tree
#

127.0.0.1

#

idk how to change it

frank shoal
#

Don't run it using flask run

#

use apache to run it.

#

flask run is a development server anyway.

#

which means it's not as efficient and exposes certain things to users

rain tree
#

ok

#

sorry if im making u repeat urelf but how do i run it using apache?

rain tree
#

there is error

frank shoal
#

Requires a compiler and the Apache development headers to install.

#

What distro?

rain tree
#

ubuntu

frank shoal
#

just run sudo apt-get install mod_wsgi

rain tree
frank shoal
#

sudo apt-get install libapache2-mod-wsgi

rain tree
#

ok

#

its installing

#

done

frank shoal
#

now run sudo apachectl restart

rain tree
frank shoal
#

don't worry about that

rain tree
#

ok

frank shoal
rain tree
#

now how would i make an api?

frank shoal
#

that should be already written. This is guiding you on how to make it public.

rain tree
#

so how am i meant to run it

frank shoal
#

You're supposed to configure it in your httpd.conf

rain tree
#

i dont have that file

frank shoal
#

it's in /etc/

rain tree
#

no

frank shoal
#

I suggest switching to nginx

rain tree
#

thats what i have

frank shoal
#

That's it

#

Are you using a virtualenv?

rain tree
#

no

frank shoal
#

Then the link above is all you need.

rain tree
#

so the api script is /var/www/html/admin/planktum/api.py

#

how would i link it

frank shoal
#

The python file has to contain a application function. You can just assign application = api.app

WSGIScriptAlias /myapp /usr/local/www/wsgi-scripts/myapp.wsgi
#

See the "Mounting The WSGI Application" section

rain tree
#

also what is the virtualhost

#

im so confused

frank shoal
#

Did you read the vhost link I sent earlier?

rain tree
frank shoal
#

yes

rain tree
#

yes

#

thats for hosting 2 websites on the same server

frank shoal
#

Yes.

#

what you have pictured is the configuration for all addresses bound to port 80

rain tree
#

ok

frank shoal
#

You could have a localhost specific vhost

#

next to your api.py file, ```py

wsgi.py

import api
application = api.app

#

That's it. Plus you could add some apache specific configurations

rain tree
#

ok

rain tree
frank shoal
rain tree
#

ok

#

i see

frank shoal
#

just have the WSGIScriptAlias pointing to the wsgi.py file

frank shoal
#

yes

rain tree
#

should i make that now?

frank shoal
#

you can probably merge it with api.py and point to api.py if you want

rain tree
#

how

frank shoal
#

i.e. ```py

api.py

from flask import Flask

app = Flask(name)

@app.route("/")
def index():
return "Hello, world!"

application = app

rain tree
#

whats this for/

#

???

frank shoal
#

that's a mistake. You just need __name__

#

Though a name is required for blueprints if you ever get into them.

rain tree
#

ok

#

ok

#

ok

#

done

rain tree
frank shoal
#

you could also do application = app = Flask(...)

rain tree
#

no

#

the wsgi thing

rain tree
frank shoal
#
WSGIScriptAlias <url> <file>
#

it will generally be / /path/to/app.py

rain tree
#

ok

#

what does it mean if its /

frank shoal
#

/ is the root path on the web server.

rain tree
#

does that mean that the api will be ip/nameofapi

frank shoal
#

any path starting with / (all of them) will go to the wsgi app

#

yes

rain tree
#

WSGIScriptAlias /myapp /usr/local/www/wsgi-scripts/myapp.wsgi

#

do i ahve to put that in virtualhost

frank shoal
#

Yes.

rain tree
#

or can it be the normal one?

#

as im only using 1 website

frank shoal
#

put it in your virtualhost directive

#

the virtualhost is *:80

rain tree
#

ok

frank shoal
#

So that's basically the default.

rain tree
#

can i do

#
<VirtualHost *:80>
 WSGIScriptAlias /myapp /var/www/html/admin/planktum/api.py
</VirtualHost>
frank shoal
#

Should work. Do you have any static files?

rain tree
#

what are static files?

frank shoal
#

files served directly from the file system.

rain tree
#

sorry im a bit confused what u mean

frank shoal
#

Then don't worry about it.

rain tree
#

ok

#

ahh

#

this is so confusing

frank shoal
#

It might be a good idea to learn apache beforehand.

rain tree
#

ok

frank shoal
#

technically, I don't know apache. I prefer to use nginx.

rain tree
#

ok

#

i will try something else

#

AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using IP Set the 'ServerName' directive globally to suppress this message

#

how could i get rid of this?

frank shoal
#

Set the 'ServerName' directive globally to suppress this message

rain tree
#

what should i set it to?

frank shoal
#

Whatever

#

name your server

rain tree
#

ok

daring isle
#

hi all, in react im setting a modal body using state on click of a button.
In the state im trying to map an array which relates to the original item.

im populating that array using another state from an axios call to my django backend.

the modal pops up and my original item is listed.
But the fetched data at the bottom is an empty array unless i exit the modal and go back in.

Essentially its setting the second state succesfully but its not rendering in time for the modal.

Id expect it to update the values once they load, but i think since the modal body is specified by a state it becomes static and doesnt update.

does anybody know the correct way to go about this?

#

Even if i managed to get around this fact, i kinda need the modal data able to update as im going to be potentially adding data in there

#
function PopUp({subState, children, title, openPopup, setOpenPopup, props, EditopenChecklist}) {
   
  const handlePopUpClose = () => {
    setOpenPopup(false);
  };
    //const{title, children, openPopup, setOpenPopup} = {...props};


  return (
    
        <div>
            <div className="overlay"></div>
    <Dialog className='myModal' open={openPopup}  >
        <DialogTitle className='myModalTitle'>
            {title} <Chip onClick={handlePopUpClose} color="error" label="X"/>
            
            </DialogTitle>
            <DialogContent setOpenPopup={setOpenPopup} EditopenChecklist={EditopenChecklist}>
                {children}
                {subState}                
            </DialogContent>        
    </Dialog>
    </div>
    
    
  )
}

I managed to get it to load on first click by creating an additional variable called subState, and populating the axios call into an array within the api call function.

The only problem now is its still there if i open the modal for a different reason (that doesn try to set the subState since its retained)

#

I can put something in to the modal submit and close function to wipe the substate, but that will only be necessary for half the time. it feels wrong

native tide
#

I want to pass html code through flask in a varible. For example python return render_template('index.html', importable_html="<img src='image.jpg'/>") then within the html I want to have that image load as a normal image with <div> {{ importable_html }} </div> Is this possible?

daring isle
#

yeah i think so. you need to put it in brackets i think ,
but if you know youre always going to have an image there it might be cleaner only making the target a variable .

importable_html=('image.jpg')

then in your template...

<img src={importable_html}/>

i cant remember if you need double or single {{}}, its usually double but i rermber something weird about doing this for nits of divs

main kayak
#

I'm a bit stuck, trying to do something with Flask - and I am wondering if it's even possible. In my route method, I've defined an argument and set a default value. My goal is that when a user submits a form, I redirect to the same route, but want to pass a new string in that variable to have it execute some different logic, so that my jinja template renders a different block of code (namely, the second part of a form).

Is that even possible, or am I approaching this the wrong way? See my route method here:

@app.route("/session_management", methods=["GET", "POST"])
def session_management_builder(action='initial'):
    if action == "initial":
        title = "SM Builder - Event Info"
        form = sm_forms.EventInfo()
        if request.method == "POST" and form.validate_on_submit():
            print(request.form)
            global form_data
            form_data = {
            "event_name": request.form["event_name"],
            "pm_name": request.form["pm_name"],
            "ff_pid": request.form["ff_pid"],
            "account_name": request.form["account_name"],
            "account_number": request.form["account_number"],
            "event_code": request.form["event_code"],
            "ah_url": request.form["ah_url"],
            "start_date": request.form["start_date"],
            "end_date": request.form["end_date"],
            "event_timezone": request.form["event_timezone"],
            "expected_attendees": request.form["expected_attendees"],
            }
            session_management_builder(action="support_info")
        return render_template("session_management.html", title=title, form=form, action=action)
    elif action == "support_info":
        title = "SM Builder - Support Info"
        form = sm_forms.SupportInfo

    elif action == "upload_data":
        title = "SM Builder - Data Upload"
        form = sm_forms.DataUpload()```
#

The elif statements there aren't written yet, so can be ignored for now.

#

Then, within my jinja template, in my content block, I have an if statement

{% if action == "initial" %}

#

Or some other string - and no matter what I do its not working - making me think that perhaps my approach to this is flawed.

daring isle
#

and using it in your function, because it might just be reseting back to action=initial everytime you render

#
def session_management_builder(action='initial'):

because of this

#

again, im unsure, but you might have to create seperate methods to overcome this

#
def session_management_builder(action='support_info'):
Your stuff here

if its that you're trying to maintain a trail of the same form data then id focus on grabbing the form response and redirecting using a pk possibly.
just a suggestion, i might not be on the money tho

swift sorrel
#

Hi, I'm wondering what is the best way to host a flask app? Searching for something free or cheap... (I'm European)
Thanks (ping me if you have an answer please)

native citrus
swift sorrel
#

nice thanks!

tidal ore
#

o/

brisk mortar
#

How to adapt the text for a mobile device?

#

before:

#

after:

#

bootstrap 5

muted gull
#

i am new
can someone explain that why theres no black line or something for the div there

tidal ore
#

try to copy / paste the code, don't take a picture of it, so we can test it without rewiting it

#

see this in the top left corner

#

it looks like an end of a comment

#

and you have no comment on your html

#

so first try to view the Practice.html file firectly in the browser, to make sure the html is ok

#

then try to find why the program that listens to the port 5500 is not serving it

#

with right click => view source you can see what the browser receives from that program, it may help you finding out the bug

#

as a general advice, make the simplest thing to work then add small changes to it and verify them right away, so when something is not working you know it's from the last change

plain seal
#

Hello,
i have a Django Modell that has object_id as Primary Key and this is a CharField. I use graphene for API and when i create everything works until graphql has to return something, then it says cannot convert string to float. But i want the primary key to be a string not a float also when graphene returns it

novel stream
novel stream
swift sorrel
obtuse robin
plain seal
obtuse robin
#

i would recommend heroku more though

#

more control in it

swift sorrel
#

Is there any offers for students?

novel stream
novel stream
obtuse robin
#

i don’t think you need to pay for them rly

#

you can but it isn’t needed

plain seal
swift sorrel
obtuse robin
#

ohh yeah lol

#

for heroku it’s easier

swift sorrel
#

nice

obtuse robin
#

you can kinda name it for free

#

if you’re okay with that lol

#

name as in you can change it to anything

swift sorrel
#

no I have my own domain and I wanna use it

obtuse robin
#

oh i see

#

then you’d have to pay yes

swift sorrel
#

okay np!

novel stream
plain seal
#

Django Model

class EventSourcedModel(models.Model):
    object_id = models.CharField(max_length=255, null=True, blank=True)

Serializer

class UnternehmenCreate(Mutation):
    unternehmen = Field(UnternehmenType)

    class Arguments:
        unternehmen_data = UnternehmenInput(required=True)

    @login_required
    def mutate(self, info, **data):
        unternehmen_data = data.get('unternehmen_data')
        print(f"unternehmen_data: {unternehmen_data}")
        serializer = UnternehmenSerializer(data=unternehmen_data)
        serializer.is_valid(raise_exception=True)
        return UnternehmenCreate(unternehmen=serializer.save())

Types

## UNTERNEHMEN
class UnternehmenType(DjangoObjectType):
    class Meta:
        model = Unternehmen


class UnternehmenInput(convert_serializer_to_input_type(UnternehmenSerializer)):
    pass

And before i get the UnternehmenType back from the Graphene it wants to convert the primary key to a float

novel stream
#

Wait, I'm not sure if my eyes are playing with me, but where the EventSourcedModel enters in this code?

velvet vale
#

i am using Django drf and i have question, is not bad practice if i validate data in view? concrete in post method

plain seal
scarlet kite
#

Hello everyone, when using FastAPI OAuth2PasswordBearer, is there a way to create a custom OAuth2 that instead of receiving username in the body, it receives email

#

If I create a custom form like below it works, but it can't be used by the swagger, for example if using OAuth2PasswordBearer(tokenUrl="authenticate")

class OAuth2PasswordWithEmailRequestForm:
    def __init__(
        self,
        grant_type: str = Form(default=None, regex="password"),
        email: str = Form(),
        password: str = Form(),
        scope: str = Form(default=""),
        client_id: str | None = Form(default=None),
        client_secret: str | None = Form(default=None),
    ):
        self.grant_type = grant_type
        self.email = email
        self.password = password
        self.scopes = scope.split()
        self.client_id = client_id
        self.client_secret = client_secret
honest wadi
#

Can anyone please help me out? I'm trying to use pydantic to parse the response,but it isn't working.

class User(BaseModel):
    name: str

    
@app.route("/",methods=['GET'])
@webargs(query=User)
def index(**kwargs):
    response = kwargs
    return response["name"]

#

I keep getting keyError: 'name'....I'm new to Flask so I don't quite understand the error

wheat verge
#

I was going through a tutorial and the guy used
this is his filter ss given
`
data3=User.objects.filter(mypage__page_cat='Programming')

`
I know about django field lookups but what is this?Any idea what this is will help a lot

#

model and views given above

wheat verge
#

One edit the guy used related name in model fields and changed it to mypage,mypost but my question is how did Post object use User fields and vise-versa

indigo kettle
#

you can query related tables with the double underscores. Django will join the tables for you

wheat verge
#

Thank you so much

uneven bloom
#

Hi guys has anyone ever done a whatsapp Webhook using whatsapi api and flask with heroku

inland oak
#

Is anyone remembering a known video (trying to find a link)
where a small web company guy was telling how to communicate with client
and whole video his lawyer was present and he was telling how lawyer helped him through his work?
the video was something among the lines of how to say no and handle stuff correctly in negotiations / why important to have lawyer
it was kind of really funny video
and video was lasting 1 hour
it was kind of good for freelancers

#

if google would be able to handle this request, I would have been searching as youtube, funny, web company, freelancers, contract negotiation, lawyers, 1 hour

halcyon summit
minor jetty
#

Hello, I'm a fullstack django dev and from my beginning of my career I've I've been using django( almost 4.6 years). These days FastAPI is becoming so popular and in 4 years of its span, many people started using it and it also has more than 45K GitHub stars in a quick span..

from the beginning of my professional career till now I've never used any other backend framework, because django was serving all my needs and that's why I'm still using it and I still love it.

But going forward should I stick to django?
Why FastAPI is growing so rapidly fast (just look at the GitHub starts)
Is FastAPI is going to be future for python backend web development?
Does django has any future? From version 3 django team has given us the async views and from 4.1 onwards django will provide async capabilities for the ORM as well.

So how does future holds for Django when we compare with FastAPI?

inland oak
#

I would say with 4.6 years in django you are overexperienced already and should dive into FastAPI

#

it is just not healthy to be that overspecialized

#

FastAPI is cooler because..

#
  • In python there are only three frameworks to choose: Flask, Django and FASTAPI, as they are all the most popular and the most supported by community, and you will find more developers already used to those solutions.
  • Out of all three FASTAPI is preferable because: it is the most performant out of three, https://www.techempower.com/benchmarks/ , around 3-5 times faster than its competitors.
  • FASTAPI is oriented to serve as JSON formated REST API backend first, while Django and Flask require additional addons to have it
  • FASTAPI should be providing relatively minimal necessary stuff out of the box to serve as backend, without forcing its architecture too much on the application (like Django does)
  • FASTAPI does not have limitations in async support like Django does because of its still incompatible sync Django ORM
  • SQLAlchemy is the most popular and supported solution in Python community, supporting async stuff which makes it perfectly compatible with FASTAPI which is async compatible too.
#

I think performance reason is sort of one of main ones, though considering http delay stuff it is not that important

#

but considering that async flares the best in http delay stuff, it is actually important

#

probably scratch the architecture part though, in theory they should be more or less equal at that part 🤔 Framework is framework after all, and it does not matter that FastAPI is more microframework than batter included like Django is

minor jetty
#

Thanks you for the detailed explanations.. much appreciated 👏

inland oak
#

...not that you are overexperienced

#

but that it is usually expected more diversity in skills from senior ranked skills

#

at least in technologies so closely similar

#

for true seniors it is actually even does not matter tbh, as they are just expected to have generic best SWE skills

#

but you know the market... sort of expects you to learn the stuff that is in use? popular?

minor jetty
inland oak
#

with having frontend stuff of course you are already quite diversified but still backend stuff should not be neglected xD

#

anyway, learning FastAPI u will just increase the pool of jobs you can land on, easier to get hired, so direct advantage for you

minor jetty
wooden ruin
candid dust
#

how memory efficient is FastAPI in general? o.o

wild tendon
#

I have a problem, my flask app that is on heroku is not working I am getting this error on the logs.

2022-06-23T01:35:22.841832+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=random-xkcder.herokuapp.com request_id=2aed6ea7-442c-4390-ae00-d139e0a9bd87 fwd="175.157.36.32" dyno= connect= service= status=503 bytes= protocol=https
2022-06-23T01:35:23.695767+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=random-xkcder.herokuapp.com request_id=1486e9fc-a4ef-4319-bdd8-175ec5657fdf fwd="175.157.36.32" dyno= connect= service= status=503 bytes= protocol=https
wild tendon
#

new error

2022-06-23T04:00:48.603947+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=random-xkcder.herokuapp.com request_id=58c6652b-2b4b-45e1-8a53-92dfe9ef2fee fwd="175.157.36.32" dyno= connect= service= status=503 bytes= protocol=https
2022-06-23T04:00:48.920791+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=random-xkcder.herokuapp.com request_id=f88e4f6a-d2d7-41ac-90f1-110d52afe820 fwd="175.157.36.32" dyno= connect= service= status=503 bytes= protocol=https
astral pagoda
#

Hi I am using flask python I want to use a form but only during a get request will this work? There is no post request. if request.method == 'GET' and form.validate():

Thanks for the help

novel stream
dawn island
#

hello,
I am using django , when I use locahost instead of 127.0.0.1: another project is running

#

how to resolve this, can someone please help

novel stream
dawn island
#

no sir

novel stream
# dawn island no sir

This here might help you then https://stackoverflow.com/a/54769851/3716354 if you're getting this error you must have something running on the same port, need to figure out what. Depending on what the process is you can kill it. Another thing you can check is if your /etc/hosts file (if you're on Linux) have the 127.0.0.1 pointing to localhost

cat /etc/hosts
127.0.0.1       localhost
brittle trail
#

Hi, I'm using Django for build a quiz app with REST API. But I want to generate the question into JSON response and use it later. Endpoint of generateSoal() is http://127.0.0.1:8000/generate-soal and the endpoint of simpanJawaban() is http://127.0.0.1:8000/simpan-jawaban. How to access the JSON response from generateSoal() into simpanJawaban()?

novel stream
brittle trail
novel stream
# brittle trail Did you have an example or reference links?

Not at hand, but I think that what you wanna do is move the code from generateSoal line 6-19 to a separate function. Also, create a specific serializer for the Soul model. Then that separate function would return something like return SoulSerializer(query, many=True). With that you would be able to use this function in both generateSoal and simpanJawaban

wraith dagger
#

Am I able to .add(*items) to m2m in transaction.atomic() block?

novel stream
wraith dagger
novel stream
wraith dagger
prisma thistle
#

Hello, is anyone familiar with leafletJS ?

#

Or what channel should i ask for people familiar with it?

#

A JS library or an SDK

novel stream
# wraith dagger Partly you are right. But as I said ```add()``` execute additional query means i...

Ah I see. So it might create another transaction. Well I don't see it as a problem. Let's say you have something like:

with transaction.atomic():
  # some operations
  my_instance.m2m.add(*items)
  # more db operations

I mean, you have more DB operations than just the .add I think a block of code like that wouldn't be wrong. However if the atomic is just for the .add then I think you don't need it because like you said it already creates its own transaction

wraith dagger
wraith dagger
prisma thistle
novel stream
wraith dagger
faint mountain
#

Hey i recently create a site with django, gunicorn and apache, everything works fine except that ANYBODY on the internet can use my server as a proxy to access any site.
Who had thought that when you configure it as a proxy it will serve all proxy requests, not just the configured ones

#
    ProxyPass / http://127.0.0.1:8000/
    ProxyPassReverse /  http://127.0.0.1:8000/
faint mountain
#

ok if had

#

ProxyRequests on

#

lika foolish person

uneven bloom
#

Hi guys has anyone ever done a whatsapp Webhook using whatsapi api and flask with heroku

Maybe any tutorial you could share with me

I used heyoo to send WhatsApp messages but receiving I haven't figured how to do it

zealous island
#

I have this element but the problem is the id constantly changes when you refresh the page is there a way by getting the element by the title?

#

how do you get an element by the title tag

golden bone
zealous island
#

from signal import pause
import selenium
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver=webdriver.Chrome()
driver.get("link")
loginbtn=driver.find_element_by_id("loginbtn")
anmeldename=driver.find_element_by_id("username")
kennwort=driver.find_element_by_id("password")
anmeldename.send_keys("blank")
kennwort.send_keys("blank")
loginbtn.click()
fortsetzen=driver.find_element_by_class_name("btn-primary")
fortsetzen.click()

I figgured out I could just use the class name to get the button element

#

and by get I mean find the element

frank shoal
#

I currently have this scss loop defining a bunch of rules on a data- attr. Is there a better way to do this? I tried using calc(attr(data-u-height) * 1rem); but firefox said it was invalid.

@for $height from 1 through 52 {
  .elevation-device[data-u-height="#{$height}"] {
    // add twice the height -1 to compensate for the border
    height: calc($cell-height * $height + ($height - 1) * 2px);
  }
}
scarlet kite
#

Isn't a way to change, in FastAPI, the OAuth2 flow from Username at the form to Email variable?

frank shoal
#

it's just a variable name. You can display it to the users however you like.

#

just add a comment to the api notes that username is email

round shard
#

how can I run a python file in a website? I want like a terminal in a website so that the user cannot see the code, makes sense?

#

cause if not I have to share the code or use repl it to make users run the file and its a bit messy/uncomfortable

round shard
#

how exactly?

loud pike
#

yo

#

who can help me deploy my flask app via gunicorn

astral pagoda
ionic raft
#

How you implement is going to depend on the web dev framework you are using. What framework are you using?

inland oak
#

we first think about it at the abstract level of code blocks / pseudo code stuff

#

frameworks are all kind of same in the end, and they just introduce slightly different implementation details to such business logic stuff

#

this kind of logic could be not even tied to Programming Language details

#

it is nice to read Code Complete by McConnel book. he explains the difference about it too

#

Although it is book more concentrated only on Code Architecture I think so far 🤔 U would need several more books to get all aspects of Software development cycle, perhaps System Analysis and Design book by Alan Dennis should be enough to complete knowledge to a minimal sufficient picture

#

But all of it would be teaching you about how to develop from the most abstract to implementation details

#

to make the picture complete you would also need to learn a different stuff how to program best from implementation details / bottom refacrorized to higher level stuff

#

That would require Unit testing Khorikov -> Test Driven Development By Kent Beck -> and perhaps Refactoring by Martin Fowler?

#

Ergh. Time to add all extra appeared stuff to my diagram of learning which i drawing for all this stuff

wet hinge
#

hi,
I have a locally working app with a custom User model, which has a foreign key in it to UserTier model. When I try to run it in my CI/CD, when python manage.py makemigrations goes off, I get:
django.db.utils.OperationalError: no such table: users_usertier
I don't have any migrations in my repo.
It is a very important project for me and I can't seem to find anything helpful.
Anyone knows what could help? 🥺

inland oak
#

anyway, try to make sure you have added app with UserTier to django settings authorized applications

wet hinge
inland oak
#

The easiest way to detect what is wrong with your code, just git clone the repo from zero and try to achieve makemigrations in it
it should help you to identify steps needed to be added to CI CD

wet hinge
#

I have fully working entire project with AWS and stuff, but on the current local database. If I try to delete database and migrations and get it migrated from 0, i get that error

wet hinge
#

I didn't upload database or migrations folder to git, so it starts from 0

inland oak
#

you do know that Django also keeps in database performed migrations data?

#

a special table just about performed migrations?

#

drop database and create it again, it will ensure better database cleaning (don't forget to backup needed data)

wet hinge
#

yeye, that's exactly when the error appears

#

locally it works cause it was built gradually

#

but when I remove the database and migrations folder

#

and try to create a new, clean one

#

I try to run makemigrations and that's what I get:
django.db.utils.OperationalError: no such table: users_usertier

inland oak
#

shrugs, not enough info to identify what you do wrong

wet hinge
#

users.model.py:


class UserTier(models.Model):
    name = models.CharField(max_length=250)

class UserManager(BaseUserManager):
    # casual UserManager from Django Docs

class User(AbstractBaseUser, PermissionsMixin):
    username = models.CharField(max_length=30, unique=True)
    user_tier = models.ForeignKey(
        UserTier, on_delete=models.SET_NULL, null=True, related_name="users"
    )
    objects = UserManager()

    USERNAME_FIELD = "username"
#

and in settings:

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "rest_framework",
    "rest_framework.authtoken",
    "dj_rest_auth",
    "users",
    "images",
]

# Custom user model configuration
AUTH_USER_MODEL = "users.User"
wet hinge
wet hinge
native tide
#

If I'm creating a social network website with Django, would it be a good idea to use Django's built in User model(which makes users show up directly in the admin interface) or should users be added to some different database table?

wooden ruin
#

just be sure to point django to your new user model using AUTH_USER_MODEL in settings

#

also keep in mind you can specify any model to show up in the admin panel, not just users

native tide
wooden ruin
native tide
#

Let's say I have a Django model which has a bunch of countries in it(it has country names, abbreviations, and id's.)
Now let's say I'm creating a user registration form(using UserCreationForm) where I want the users to be able to pick one of the countries from my earlier model to sign up.
How would I go about implementing that?

#

it would probably have:

country = forms.ChoiceField

but what would the arguments here be?

#

my country model is this, fyi:

class Country(models.Model):
    name = models.TextField(max_length=50)
    abbr = models.TextField(max_length=3)
    id = models.IntegerField(primary_key=True)

    def __str__(self):
        return self.name
#

I found the answer myself. I used:

    country = forms.ModelChoiceField(queryset=Country.objects.all())

But if someone else has a better solution please feel free to share!

zenith hound
#

Got a bit of an issue with Flask, hope someone can clear this up for me.
Im trying to display a webcam feed through openCV on the screen, which worked fine while i was calling the function when it was on index.html .

Now that i've separated the pages with a help of a navbar, i cannot get the webcam to show up.

#

I have the route set as

@app.route('/webcam')
def get_webcam():
    return(render_template('webcam.html', camera=camera))
#
@app.route('/webcam_display')
def webcam_display():
    return Response(generate_frames_webcam(),mimetype='multipart/x-mixed-replace; boundary=frame')

and in the HTML

    <div>
        <img src="{{ url_for('webcam_display') }}" width="50%"/>
    </div>
#

The navbar is set up as

topbar = Navbar(
                View('ANPR', 'index'),
                View('Webcam', 'get_webcam'),
                View('Oak-D', 'get_oakcam'),
                )
nav = Nav()
nav.register_element('top', topbar)
nav.init_app(app)

and then rendered with

<body>
    {% extends "bootstrap/base.html" %}
    {% block navbar %}
    {{nav.top.render()}}
    {% endblock %}
    <h1>ANPR</h1>
    <form method="post" action="{{ url_for('tasks') }}">
        <input type="submit" value="Stop/Start Webcam" name="webcam" />
    </form>
    <div>
        <img src="{{ url_for('webcam_display') }}" width="50%"/>
    </div>
</body>

in the body.

#

Seems like navbar might be blocking everything else from showing for some reason, since on the index page i added some h1/h2 tags that do not show up.

eternal quiver
#

Have anyone tried to add file uploads with tus to fastapi? I'd appreciate some examples or at least tips

minor sedge
#

where would it be possible to fully learn javascript ?

sturdy drift
minor sedge
#

gg / java ??

sturdy drift
#

i cant send invite here

#

i will send in dms

minor sedge
#

ok...

eternal quiver
#

Not for tus, no. Anyway I figured that it won't make sense as fastapi will have to get the whole file anyway before passing it to tus

native tide
#

I want to get started with web development, what would be a good place to start?

#

I've heard HTML or CSS being recommended, any good resources to work with those?

frank shoal
#

mdn has some good (community written) turotials

novel stream
native tide
#

I see, thanks a ton

#

I've tried getting into some HTML before, I always stumble but I guess that is partly because of my lack of patience while approaching it

novel stream
native tide
#

Django seems like a fine choice, and of course I asked here because I'm interested in web development in relation to using Python, but I was thinking more about Flask

novel stream
#

I'm not a Flask guy but it's also a good choice and a very used one. You will be able to find plenty of resources online (blogposts, YouTube, etc)

eternal blade
#

Is it recommended to use drf with session authentication with a react frontend?
since the documentation says this
https://www.django-rest-framework.org/api-guide/authentication/#sessionauthentication

This authentication scheme uses Django's default session backend for authentication. Session authentication is appropriate for AJAX clients that are running in the same session context as your website.
What about applications not running on the "same session context"

indigo kettle
#

basically if your django and react are served on the same url

eternal blade
slim wraith
#

I have two permission class. IsAuthorGroup will check if the user belongs from the author group and IsOwnerOrReadOnly will restrict the user to performing post and delete if he is not the object's owner.

But the problem is anyone from IsAuthorGroup performing post and delete request event he isn't own of the object.

How to restrict anyone from IsAuthorGroup performing post and delete request if he isn't owner of the object?

here is my code:

    def has_permission(self, request, view):
        if request.user and request.user.groups.filter(name='AuthorGroup'):
            return True
        return False


class IsOwnerOrReadOnly(permissions.BasePermission):
    def has_object_permission(self, request, view, obj):
        if request.method in permissions.SAFE_METHODS:
            return True

        # Write permissions are only allowed to the owner of the blog.
        return obj.author == request.user or request.user.is_superuser 



class BlogViewSet(viewsets.ModelViewSet):

    queryset = Blog.objects.all()
    serializer_class = BlogSerializer
    pagination_class = BlogPagination
    lookup_field = 'blog_slug'
    permission_classes = [IsOwnerOrReadOnly & IsAuthorGroup]```
iron tusk
#

anyone familiar here with github pages / netlify or heroku

#

pretty much anything like that?

wooden ruin
iron tusk
#

well i just want somewhere to upload my portfolio stuff

#

if i ever have something that is good enough to show off

#

so since i cant really spend much money on website hosting service

#

i was just thinking about if github pages is good enough for stuf like that

wooden ruin
#

yeah github pages is a great place to host portfolios

wet hinge
#

hi,
when I do an authorization decorator, do I have to call the function inside of it? or it's just enough to return it?

def is_correct_user(func):
    """
    Check whether the requesting user is the one who the image belongs to.
    """

    @functools.wraps(func)
    def wrapper_is_correct_user(request, *args, **kwargs):
        img_name = kwargs['img_name']
        if request.user.id != int(img_name.split("_")[0]):
            return Response({"status": "Forbidden"}, status=status.HTTP_403_FORBIDDEN)
        func(request, img_name=img_name, *args, **kwargs)  # DO I HAVE TO HAVE THIS?
        return func(request, img_name=img_name, *args, **kwargs)

    return wrapper_is_correct_user
novel cosmos
#

Hey...
I am a beginner ...I just completed HTML ....
What should I do next ??...plz help

wet hinge
#

to-do app in django

onyx lava
#

jinja2.exceptions.UndefinedError: 'int' is undefined

{% if int(todo[2].replace("-", "")) <= int(date)%}

I can't use the int function? 🤔

frank shoal
#

use something as int I think.

#

it's (x | int) <= (y | int)

ember heron
#

hello i have a question

#

i am trying to do this

#

to make a model form

#

but the form ends up having a drop down of foreign keys

#

i just want it to log the currenlty logged in user

#

with modelform data which is being saved

pallid hill
#

Currently the sendBtn button and the username input box are not center aligned with the message text area, how would I do this? Thank you in advance.

native tide
#

Hi,
I know I can access user profiles by using their ids if I use int:user_id in my urls file. But how can I access user profiles using the profile names? I tried <user_username> but that didn't work

#

Question for Django ^

wooden ruin
native tide
wooden ruin
#

yeah slug works as well

native tide
#
class Country(models.Model):
    name = models.TextField(max_length=50)
    abbr = models.TextField(max_length=3)
    id = models.IntegerField(primary_key=True)

    def __str__(self):
        return self.name


class User(AbstractUser):
    country = models.ForeignKey(Country, on_delete=models.CASCADE, default='default')
    def __str__(self):
        return self.username

When I run migrations on this, I get the following error:

ValueError: Field 'id' expected a number but got 'default'.

any ideas on a fix?

dusk totem
thick oak
#

I know this is broad but is there any suggestions for fixes when I get key errors on production but not in development?

dusk totem
#

It really depends on how you want to handle errors. You could have it stop the script entirely or just return a default or just return some sort of error message somehow or log it

thick oak
#

hmm could try that

#

Yeah I've got it logging from website into a discord channel but again that just throws key errors. I'll have a further look this morning though and try some exception catching

thick oak
manic crane
#

can someone help me with this error please => AttributeError: 'Request' object has no attribute 'occupier' my code => ``` class OccupierLoginView(APIView):

def get(self,request,format=None):

    if request.occupier.is_authenticated == False or request.occupier.is_active == False:
        return Response('Invalid credentials', status=403)

    occupier = OccupierSerializer(request.occupier)
    return Response(occupier.data, status=200)

def post(self,request,format=None):
    print('Login Class')

    occupier_obj = Occupier.objects.filter(email=request.data['username']).first() or Occupier.objects.filter(username=request.data['username']).first()

    if occupier_obj is not None:
        credentials = {
            'username': occupier_obj.username,
            'password': request.data['password']
        }

        occupier = authenticate(**credentials)

        if occupier and occupier.is_active:
            occupier_serializer = OccupierSerializer(occupier)
            return Response(occupier_serializer.data, status=200)
    return Response("Invalid credentials", status=403) ```
sturdy siren
#

hello, I am pretty new to coding but am good at python skill wise. I want to make a program that automatically lists an item from Gumtree to Facebook Marketplace - would this be possible and will it be hard? I have no experience making large web projects liek these. Only puzzles.

zealous elk
#

I am stuck at something in my flask app. The details are in #help-ramen, please help me if you can

cobalt pine
#

is it possible to wirte if condition inside {{ }} in jinja ??

frank shoal
#

You can probably do it be chaining cond | reject | map | default

#

Does the python way not work, x if y else z

mystic wyvern
ember heron
cobalt pine
manic crane
#

can someone help me with this error please => AttributeError: 'Request' object has no attribute 'occupier' my code => ```from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from .serializers import OccupierSerializer
from .models import Occupier
from django.contrib.auth import authenticate

Create your views here.

class OccupierView(APIView):
def post(self, request,format=None):
print('creating occupier')

    occupier_data = request.data
    print(request.data)

    occupier_serializer = OccupierSerializer(data=occupier_data)
    if occupier_serializer.is_valid(raise_exception=False):
        occupier_serializer.save()

        return Response({'occupier':occupier_serializer.data}, status=200)
    return Response({"msg:ERR"}, status=400)

class OccupierLoginView(APIView):

def get(self,request,format=None):

    if request.occupier.is_authenticated == False or request.occupier.is_active == False:
        return Response('Invalid credentials', status=403)

    occupier = OccupierSerializer(request.occupier)
    return Response(occupier.data, status=200)

def post(self,request,format=None):
    print('Login Class')

    occupier_obj = Occupier.objects.filter(email=request.data['username']).first() or Occupier.objects.filter(username=request.data['username']).first()

    if occupier_obj is not None:
        credentials = {
            'username': occupier_obj.username,
            'password': request.data['password']
        }

        occupier = authenticate(**credentials)

        if occupier and occupier.is_active:
            occupier_serializer = OccupierSerializer(occupier)
            return Response(occupier_serializer.data, status=200)
    return Response("Invalid credentials", status=403)````
native tide
# dusk totem Try removing `default='default'`

Ok, I changed it to:

class User(AbstractUser):
    country = models.ForeignKey(Country, on_delete=models.CASCADE)

But I still get this error when I try to migrate:

ValueError: Field 'id' expected a number but got 'default'.
mystic wyvern
plush frigate
#

how to show this image on my web page? src is changes so i cant just copy it

golden bone
#

Or whatever server is hosting your html

plush frigate
golden bone
#

those images are their assets, not yours

pallid hill
bleak adder
#

Hi ! Can i have some assistance with flask?

bleak adder
#

So basicaly i have two buttons, when clicked, both call backend functions
So when i click the first button, a backend function is called and stores its data in a global variable
When the second button is pressed, it calls a function that uses the global variable, but this doesnt work because the two functions must be called at the same time.
How can i fix this ?

orchid hamlet
#

can you send code

#

@bleak adder can you send the code?