#web-development

2 messages Β· Page 181 of 1

dusk portal
#

if request.user ==User.post(this is model name)_set.all()

covert stratus
#

ok

deft shore
#

I have a model in Django that has a file field and I want to export all the files associated with a Foreign Key associated to that model. (It's a contract model that has an Event Foreign Key)
How should I go about doing that?

lime frigate
#

I 'm starting to learn django. But when i create a website and run python manage.py runserver

#

It gives refuse to connect

#

What's the problem?

#

Or should i setup anything?

jade lark
lime frigate
#

Curious*

#

Still refused to connect

jade lark
#

Did you try both variants of the command?

#

python manage.py runserver 0.0.0.0:8000 is the command. I just looked it up to confirm

lime frigate
#

Hold up my bad lmao

#

I typed sthg like 127.0.0.1/8000

#

So dumb of me

#

Sorry guys

jade lark
#

No worries man at least you got it figured

versed python
deft shore
versed python
marsh girder
#

how to intialize python in html

cobalt tartan
#

what's wrong with AttributeError: module 'django.db.models' has no attribute 'DataField' ? i did follow step-to-step from tutorial basic and it doesn't work for me

versed python
eternal blade
#

There is brython

marsh girder
#

well someone deleted some channe;?

#

tf

versed python
calm plume
#

it's just transpiled from python

eternal blade
#

Yeah

pliant shoal
#

Thanks to the ones here helped me, Now i have successfully deployed my Anime REST API

native tide
#

Can someone help me create some dependent drwopdowns in Flask?

#

I want to create dependent dropdown forms for Country, State, District, City

dusk portal
#
@api_view(['GET','DELETE'])
@permission_classes([permissions.IsAuthenticatedOrReadOnly])
def detailview(request,post_id):
    try:
        tasks=Post.objects.get(id=post_id)
        serializer= PostSerializer(tasks, many=False)
        task_del=Post.objects.get(id=post_id).delete()
    except Post.DoesNotExist:
        raise Http404('OBJ NOT FOUND')
    return Response(serializer.data)
```  i'm using this view for pagination but if i visit to this and then come back  to database it deletes the object from database  automatically at visit
#

can't i used function based views for work like pagination deleting updating

#

@eternal blade the g0d is on9 wow

eternal blade
dusk portal
#

umm

#

can't i do with browser

#

wait lemme try with postman

dusk portal
#

then too it's deleting in postman too @eternal blade

#

umm func based view for rest framework ig sucks

cobalt tartan
wary flint
#

Hey, any recommendations for a reporting app for django?

#

Pretty much would like to build queries and save reports that users can run again but with built in ability to export to csv, excel, pdf

manic frost
#

TIL that TypeScript allows you to express this:

violet briar
#

I don't really know if I should be using FastAPI or django for my graphene graphQL API, I come from a flask background so I am into more simple and open web frameworks, the thing is, I was not able to wire-up the database properly with FastAPI because I had to use SQLalchemy which is pretty painful and had to use graphql-sqlalchemy which tries to mimic the API of graphene-django, but, it's full of bugs and overall not so great to use

besides all that, the biggest problem I am facing is that I can't find any good learning resources to learn how to implement a graphQL API with fastAPI, all the quality tutorials were about graphene-django

edgy anvil
#

I have defined a variable in my html template with jinja syntax. Is it possible to use that variable to the corresponding routes.py in flask?

meager halo
#

hello i hacve a problem whit load my app in flask in heroku

#

i has my proyecty in git

#

but the struct i dont can upload

#

i has the proyect into a path src

eternal blade
vagrant ginkgo
#

Guys, best wombo combo django, django rest, fast APIhttps://django-ninja.rest-framework.com/

stray shard
lime valve
#

Anyone interested in django collaboration

vagrant ginkgo
vagrant ginkgo
lime valve
#

Employee Dashboard project

stray shard
#

brother i want to add the X to every box and when i hover on a li the X will have to diapear please suggest how can i achieve this

calm plume
lime valve
#

I actually completed major part but login was not working and password mismatch message errors are also not showing in html file

lime valve
vagrant ginkgo
lime valve
#

Actually I m Beginner Bro

lime valve
stray shard
#

@vagrant ginkgo are we still connected

vagrant ginkgo
pulsar meteor
#

hlo

pulsar meteor
#

i am beginner can you help me ?

vagrant ginkgo
vagrant ginkgo
#

install using cdn

#

then use navbar componennts

native tide
#

Can someone tell me why my code isnt working?

HTML
<a id="siteLogo" class="siteLogo_ani" href="./">
<img src="http://goo.gl/QafDup">
</a>

CSS
``.siteLogo_ani { -webkit-animation-name: asdf; -webkit-animation-duration: 1s; -webkit-animation-timing-function: ease-out; -webkit-animation-delay: 1; -webkit-animation-iteration-count: 1; -webkit-animation-direction: normal;`

animation-name: asdf;
animation-duration: 1s;
animation-timing-function: ease-out;
animation-delay:1;
animation-iteration-count: 1;
animation-direction: normal;
}
``
@-webkit-keyframes asdf{
from {float: left; width:355px; height:150px; display:block;}
to {float: left; width:160px; height:50px; display:block;}
}
@keyframes asdf{
from {float: left; width:355px; height:150px; display:block;}
to {float: left; width:160px; height:50px; display:block;}
}

#siteLogo img{width:100%; height:100%;}

#

also i forgot copy and paste existed

lime frigate
#

What is the difference between python manage.py migrate and make
migrations ?

ionic raft
ionic raft
lime frigate
ionic raft
inland oak
lime frigate
#

Isit something like git add then git push

ionic raft
#

makemigrations = prepare
migrate = implement

ionic raft
lime frigate
#

Ok now i got it, thanksssπŸ˜‹

ionic raft
#

I've had a couple of instances where I used the wrong default on a type of field and things have gone VERY badly

#

I learned the hard way...
Updating the model? USE VERSION CONTROL!!!!

πŸ˜„

ionic raft
# lime frigate What's rolling back?

Going to last working version...Like when you do something, and when you try and run things you get error messages that are really obscure that you KNOW related to something you did wrong in the change to the model

#

changing the DB is the riskiest change in my limited experience. git is the saviour...so long as you save right before the model change.

lime frigate
#

Adding data or adding column

ionic raft
#

If I change the application or presentation layer...easy to fix...but the DB...that's a whole different ball game.
If you change fields, their types, attributes, adding fields...

ionic raft
lime frigate
#

Ooo ok now i got it.. thanks for the heads-upπŸ˜‰

ionic raft
#

But then, the model entity diagram for my web app project is a bit of a beast...

lime frigate
ionic raft
#

19 tables...over 11k lines of python and 9k+ lines of html/css.
Yes...I too was a beginner...April 16, 2021. Four months later...and that's the result..

lime frigate
#

I like ur efffort keep it up

ionic raft
#

Apr 15 I did not know anything about Python.

lime frigate
#

Did u save it on github?

ionic raft
#

About 1-2 weeks from first deployment to production on Linode. Assuming all goes as planned

lime frigate
#

Oooo i c

#

R u working ?

#

Or r u just plainly practising

ionic raft
#

I had the blessing of a few months of pause after a really big business project successfully delivered in March to client. Been filling the time until new contracts start in Sep. I'm a business consultant

#

Had the idea for this web app....and decided to learn how to code Python

lime frigate
#

Ooooo

#

So what is exactly ur job?

#

Software engineer,

#

?

ionic raft
# lime frigate So what is exactly ur job?

Hmmm...I train and mentor organizations on how to improve how they work, how they collaborate. LanesFlow is the web app I'm building and is about automating what I do for a living, have been doing for 25 years.
Think, business consultant in an app...here's the dashboard of the web application...

lime frigate
#

Ooo so this is ur website?

ionic raft
#

Yep

lime frigate
#

And u use it for the purpose of business consulting?

ionic raft
lime frigate
#

Respect πŸ™Œ

ionic raft
#

The first subscription tier is free. You get access to most of the tools, just limited...

lime frigate
#

Hmmm my desired job is actually setting up website for companies

#

But urs is great too

ionic raft
#

I have limited bandwidth.

ionic raft
lime frigate
ionic raft
lime frigate
#

So i think it will be a smooth journey

ionic raft
#

I've been 6 weeks solid on Django. I'm really starting to pick up speed. I get most error messages and can find things quickly.
What editor/IDE do you use?

lime frigate
ionic raft
lime frigate
#

For javascript i use notepad++

#

I don't really care about ide tbh kinda lazy

ionic raft
#

I've not used it. I got started with PyCharm from day 1.
Yes, I get simple.

lime frigate
#

I even code on phone, termux

pliant shoal
#

wow

#

vs code and nano is good tho

lime frigate
#

Like when i'm outside or the computer is not available i just use termux

#

Works great also

ionic raft
#

PyCharm does teach me good PEP....and catches errors before I was time. But, the biggest gift of PyCharm is the things it suggests that help do things I coul;dnt before

ionic raft
lime frigate
#

I hope as soon as i finish my education i can get a job asap

ionic raft
lime frigate
#

But tbh i really hope the things i'm learning atm can gimme some sort of head start to conpete with others

#

Like getting a high salary job

ionic raft
lime frigate
#

But nowadays a lot of ppl know programming so the competition is quite tough

ionic raft
#

If you build a portfolio of projects that show you can solve problems and create valuable applications...it'll create the opening

thorny quartz
#

@ionic raft can you suggest me any site so that i can learn and understand Django

ionic raft
# thorny quartz <@!837562596231872512> can you suggest me any site so that i can learn and under...

Sure. My initial teacher was Corey Schafer on YouTube...AMAZING start.
https://www.youtube.com/watch?v=UmljXZIypDc&list=PL-osiE80TeTtoQCKZ03TU5fNfx2UY6U4p

In this Python Django Tutorial, we will be learning how to get started using the Django framework. We will install the necessary packages and get a basic application running in our browser. Let's get started...

The code for this series can be found at:
https://github.com/CoreyMSchafer/code_snippets/tree/master/Django_Blog

Flask Tutorials to cr...

β–Ά Play video
ionic raft
cerulean badge
#

anyone have an example of how do i edit connections.html of allauth?

hoary marlin
#

hello everyone I have a project to integrate react frontend with plus S and I am clueless about how to do the integration I have searched on the internet about the integration and this I got the result of using Axios API My target is to get input from react form standard data to the flask backend and redirect the user from that form to another form how can I achieved please tell me the steps and can you please guide me through the code.

dusk portal
#

how can i add a recurrsive (if) method so user can only delete his posts not anyone's else

#
class Post(models.Model):
    title=models.CharField(max_length=100)
    url=models.URLField()
    author=models.ForeignKey(User,on_delete=models.CASCADE)
    published_on=models.DateTimeField(auto_now_add=True)
#
@api_view(['GET','DELETE','UPDATE'])
@permission_classes([permissions.IsAuthenticatedOrReadOnly])
def detailview(request,post_id):
    if request.method=='GET':
        try:
            tasks=Post.objects.get(id=post_id)
            serializer= PostSerializer(tasks, many=False)
        except Post.DoesNotExist:
            raise Http404('OBJ NOT FOUND')
        
    if request.method=='DELETE' and User.objects.filter(username=request.user).exists():
        task_del=Post.objects.get(id=post_id).delete()
        return HttpResponseRedirect('/')
    return Response(serializer.data)```
#

rn any logged in user can del posts

dusk portal
#
@api_view(['GET','DELETE','UPDATE'])
@permission_classes([permissions.IsAuthenticatedOrReadOnly])
def detailview(request,post_id):
    if request.method=='GET':
        try:
            tasks=Post.objects.get(id=post_id)
            serializer= PostSerializer(tasks, many=False)
        except Post.DoesNotExist:
            raise Http404('OBJ NOT FOUND')
        
    if request.method=='DELETE' and Post.objects.filter(author=request.user):
        task_del=Post.objects.get(id=post_id).delete()
        return HttpResponseRedirect('/')
    return Response(serializer.data)``` now done this but getting error and when i  comment (last 4th line  from the end ) it works fine
#

else error

#
UnboundLocalError at /24/
local variable 'serializer' referenced before assignment```
eternal blade
dusk portal
#

Which the HttpResponse one or the last one @eternal blade

eternal blade
#

In the first if statement

long jackal
dusk portal
#

Btw is my approach /logic correct (see the last 4th if statement) to get to know which user is logged in and who is the author see the models too

eternal blade
dusk portal
#

Yes

eternal blade
#

Add another if statement inside the second one

dusk portal
#

Author = the one who made the object (author)
So author=request.user

#

I'm coding from 2.5 month in django

#

Most of the problems are in

#

If else and those

#

Indents

#

πŸ˜‚πŸ˜‚

native tide
#

Can someone help me with dependent dropdowns in flask?

#

I am trying to do that

dusk portal
#

i have a blog app and i want user can see all the posts there in home and psgination view too but he can only delete the posts by him as author is connected to ForeignKey so it;s sending to User db too and the db too

#
@api_view(['GET','DELETE'])
@permission_classes([permissions.IsAuthenticatedOrReadOnly])
def detailview(request,post_id):
    if request.method=='GET':
        try:
            tasks=Post.objects.get(id=post_id)
            serializer= PostSerializer(tasks, many=False)
            return Response(serializer.data)
        except Post.DoesNotExist:
            raise Http404('OBJ NOT FOUND')
        
    if request.method=='DELETE' and Post.objects.filter(author=request.user):
        task_del=Post.objects.get(id=post_id).delete()
        return Response(f"{task_del} have been deleted")```
eternal blade
#

add that logic in another if statement inside the second one

dusk portal
#

umm

#

ohk

eternal blade
dusk portal
#
    if request.method=='DELETE':
        if Post.objects.filter(author=request.user):
            task_del=Post.objects.get(id=post_id).delete()
        return Response(f"{task_del} have been deleted")```
dusk portal
#

umm

eternal blade
#
if request.method=='DELETE':
    post=Post.objects.get(id=post_id)
    if post.author == request.user:
        post.delete()
        return Response("Success!")
    else:
        # Return Status 403 Forbidden
dusk portal
#

wow

#

u r hero

eternal blade
#

πŸ˜„

dusk portal
#

umm

#

if post.user == request.user:
@eternal blade i have used this cez this make more sense

eternal blade
dusk portal
#

post.user i mean

#

lol

#

if request.method=='DELETE':
post=Post.objects.get(id=post_id)
if post.author == request.user:

#

@eternal blade

eternal blade
#

Yeah, that looks right

dusk portal
#

ohk

#

how u learned btw u r coding in django and drf from @eternal blade

#

it's my 2 n a half month ig im not that good

#

and i only focused on it

#

im good but not that

#

at making own logic i'm not that good rn at this point

#

im 16 my mind is not that much developed( nice excuse by me)

eternal blade
#

Still working on the drf project

#

Haven't made the frontend yet...

#

The frontend is the hard part

pliant shoal
#

Hi

dusk portal
#

u learning from how many months @eternal blade

eternal blade
#

I've been learning drf for about 2 months and django for about 9 months

snow sierra
#

HEY!

i have

updated = models.DateTimeField(auto_now=True)

template:

{{ post.update }}

it gives me [Aug. 15, 2021, 5:27 p.m.]

how can i filter?? Maybe only [Aug 15, 2021]

inland oak
#

Interesting.

#

Using something like this https://pypi.org/project/jsonpath-ng/

#

could be useful in order for API to be more versatile to incoming JSON input

#

which leads to less couping, which leads to less rippling effects.

past cipher
#

is it possible to embed a file directly into html

#

like a pdf document

inland oak
past cipher
#

@inland oak I tried iframe to embed an image and it worked, and then I tried with one of my files, and it didn't work. I soon realised that even when i visit the URL in my browser, it auto downloads - hence why I couldn't embed. Thanks for the link, because it made me realise my mistake

#

you just saved me a fair bit of time

rough jay
#

@api_view(['GET','DELETE'])
@permission_classes([permissions.IsAuthenticatedOrReadOnly])
def detailview(request,post_id):
if request.method=='GET':
try:
tasks=Post.objects.get(id=post_id)
serializer= PostSerializer(tasks, many=False)
return Response(serializer.data)
except Post.DoesNotExist:
raise Http404('OBJ NOT FOUND')

if request.method=='DELETE' and Post.objects.filter(author=request.user):
    task_del=Post.objects.get(id=post_id).delete()
    return Response(f"{task_del} have been deleted")

<object Rush2618 at 0x001B561E0> β€” Today at 14:19
in the second if statement remove and Post.objects.filter(author=request.user)
add that logic in another if statement inside the second one
ARYAN β€” Today at 14:20
umm
ohk
<object Rush2618 at 0x001B561E0> β€” Today at 14:21
What attribute is the posts author?
ARYAN β€” Today at 14:21
if request.method=='DELETE':
if Post.objects.filter(author=request.user):
task_del=Post.objects.get(id=post_id).delete()
return Response(f"{task_del} have been deleted")
ARYAN β€” Today at 14:21
class Post(models.Model):
title=models.CharField(max_length=100)
url=models.URLField()
author=models.ForeignKey(User,on_delete=models.CASCADE)
published_on=models.DateTimeField(auto_now_add=True)

hardy nebula
#

Someone knows how to get API of a website?

If yes please help

ionic raft
inland oak
#

quite full one in my opinion

#

anyway, if there is no information about existing API

#

you could always try emailing the tech support of the web site

snow sierra
ionic raft
snow sierra
#

OMG!!! am i drunk?? πŸ˜„
t Number of days in the given month. 28 to 31

#

Thank you Carewen!

dusk portal
#

Btw latest series is out
By Django Daddy
One n only CodingEntetpreneur I wish it would come before 2 month when I started
Latest django 3.2

ionic raft
dusk portal
#

How all r getting pycharm professional I don't have id which I have given to school

ionic raft
dusk portal
#

Wow

#

I only ask my parents to pay for Udemy couses

#

πŸ˜‚πŸ˜‚

#

And sometimes book

ionic raft
eternal blade
dusk portal
ionic raft
#

That's very cool of them.

ionic raft
dusk portal
#

Ppl say this

eternal blade
hardy nebula
ionic raft
hardy nebula
#

Ok I understand that πŸ‘
Is there any other wayπŸ₯Ί

native tide
ionic raft
#

Selenium comes with ChromeDriver, which will allow you to set up browser event automation. Which is useful.

native tide
fossil pond
#

Hello guys, I'm brand new to Django. I followed a really stupid tutorial on Yt and I'm stuck.
Basically, my model class looks like this:

from django.db import models
from django.contrib.auth.models import User

# Create your models here.

class ToDoList(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="todolist", null=True)
    name = models.CharField(max_length=200)

    def __str__(self):
        return self.name

class Item(models.Model):
    todolist = models.ForeignKey(ToDoList, on_delete=models.CASCADE)
    text = models.CharField(max_length=300)
    complete = models.BooleanField()

    def __str__(self):
        return self.text

Without the user variable everything works but I wanted every user to get a different page with different todolist items. When I do absolutely anything I get this error: table main_todolist has no column named user_id

ionic raft
fossil pond
ionic raft
#

Wait a minute...why do you have an Item as a child to ToDoList?

fossil pond
ionic raft
#

So, you can have multiple todolists?
That's going to get challenging quickly. To render both those forms together in a formset you'll need an Inline Formset. Those are AMAZING by the way...I've built two...but they're far from beginner Django

#

I must be missing something...a Parent-Child relationship for a todo list seems over-engineered to me. But then, I don't know the extent of the use-case.
And there are better teaching examples IMHO that could be picked to demonstrate a Parent-Child build.

fossil rivet
#

there is no discord group for Frontend something like React Angular or Vue

#

?

ionic raft
fossil rivet
#

ok thank you

ionic raft
fossil pond
#

I swear on youtube the dumbest programmers get the most views

ionic raft
ionic raft
#

And if skill is lacking...that's brutal

fossil pond
ionic raft
fossil pond
#

Logging in is compulsory

ionic raft
#

And logging in is compulsory for the approach I took.
But then, I'm new. My questions aren't challenging the approach. I'm trying to understand how two tables are better/more efficient in this use-case?

fossil pond
ionic raft
fossil pond
#

I just wanted a working tutorial/small project from where I can learn on my own

ionic raft
#

You'll need to learn about querying... πŸ™‚

fossil pond
#

That video i clicked was a nightmare

ionic raft
#

My recommendation...watch Corey for a bit...he'll set you straight πŸ˜„

fossil pond
#

His video of Django is 3 years old, would that be alright?

ionic raft
#

by the way, the query for ToDoList would look something like...

ToDoList.objects.filter(user=self.request.user)```
ionic raft
#

The above filter takes care of building a query of tasks. You can either assign that filter to a variable or context dictionary (Class based view). But that'll be explained when you get into views...

#

Trust me when I say, learning how to dance with the Django DB is some of the most fun you can do with a website. It took me a bit, but bruh...ORM in Django is da BOMB

#

This is the home/dashboard of the web application I'm building. And it all started with Corey and that series on Django...

rustic sky
#

I'm about to pay for DigitalOcean

#

and for some reason, their no refund thing is scaring me

glacial yoke
#

if I wanted to create a react project inside of django, what shall I write in the console?
this:

npx create-react-app app-name

or this:

npm init -y
native tide
#

How do I revert this to use in a class component```jsx
const BaseJoi = require('joi')
const ImageExtension = require('joi-image-extension')

const schema = Joi
.image()
.minDimensions(100, 50)

fossil pond
ionic raft
#

Excellent news πŸ™‚

native tide
#

How do I validate images with Joi browser?

#

export default class CreatePost extends Form {
  componentDidMount() {
    this.props.toggleShowSearchBar(false);
    axiosInstance.get().then((res) => {
      const slugs = res.data.map((post) => post.slug);
      this.setState({ slugs: slugs });
    });

    const BaseJoi = require("joi-browser");
    const ImageExtension = require("joi-image-extension");

    const Joi = BaseJoi.extend(ImageExtension);
  }

  state = {
    data: { title: "", image: "", content: "" },
    errors: {},
    slugs: [],
  };

  schema = {
    title: Joi.string().required().min(10).max(80).label("Title"),
    title: Joi.string().required().label("Image"),
    content: Joi.string().required().min(100).label("Content"),
  };
#

I have this at the moment

#

I want to access Joi from componentDidMount

#

or can I store it in the state?

thorn igloo
native tide
#

good Idea

native tide
#

In here jsx schema = { title: Joi.string().required().min(10).max(80).label("Title"), image: Joi.image().label("Image"), content: Joi.string().required().min(100).label("Content"), };

#

I get this error now

#

RangeError: Trying to access beyond buffer length

thorn igloo
#

i don't use joi so i don't know what that even means

native tide
#

joi-browser gives that error

#

ok

meager anchor
#

this is such a fun article

swift spindle
#

How do I pass a variable/library from Django init to my views?

#

or is there a better way something like that should be handled that I am not aware of?

#

I am trying to use the init to connect to a wss and I want to use that connection variable in the views later

mystic wyvern
#

login (request,user) what should i do ????

dense slate
rustic sky
#

reddit and otherwise @dense slate

swift spindle
#

@mystic wyvern Not sure what you're doing, but the error is pretty clear I think, login accepts 1 argument, but you have provided 2

mystic wyvern
timid nest
#

is there any way to restart my flask server within flask? trying to make an "update" command for my flask admin panel

ionic raft
ionic raft
timid nest
#

I'm aware an IDE is just running python app.py my question was more of is there a built in method to restarting the flask loop, guess not.

thorn igloo
lethal mesa
#

hi, can i get some help? i'll need to share screen

rustic sky
#

Final Decision Consideration before making my django webapp/site live:

Hit counter for each webpage or no?

#

More trouble than its worth?

native tide
#

is static local ip safe?

lime frigate
#

Guys my bootstrap works for button and other elements but somehow for others like navbar and fade in etc they don't work

#

Isit the problem of my browser lmao

versed python
lime frigate
#

My bootstrap version is 4.3.7

#

Helppppp

rustic sky
nova sonnet
#

is this the best way to create multiple objects when one object is being created in django?

lime frigate
#

`<html>

    <head>

            <meta name="viewport" content="width=device-width, initial-scale=1">                                                                                              <!--<link rel="stylesheet"  href="bootstrap.min.css">-->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">




    


    </head>

    <body>




            <navΒ class="navbar  bg-dark">
                    Β Β 
                    Β <ul class="navbar-nav">                                                                  <li class="nav-item">                                                                    <a class="nav-link" href="#">Link 1</a>
                             </li>
                             <li class="nav-item">
                                     <a class="nav-link" href="#">Link 2</a>
                             </li>
                             <li class="nav-item    ">
                                    <a class="nav-link" href="#">Link 3</a>
                             </li>

                                    </ul>
                                    Β Β Β Β 
            </nav>


            <h1>Quinton's Website</h1>

            <div id="content">
          
          
            </div>
    </body>

</html>`

#

Can anyone help to test if it's working cuz the navbar is wierdly not working at all

nova sonnet
lime frigate
nova sonnet
#

you can send one if youd like

#

i cant read that all

#

try re formatting the message

#

!code

lavish prismBOT
#

Here's how to format Python code on Discord:

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

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

lime frigate
#

        <head>

                <meta name="viewport" content="width=device-width, initial-scale=1">                                                                                              <!--<link rel="stylesheet"  href="bootstrap.min.css">-->
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">




        


        </head>

        <body>




                <navΒ class="navbar  bg-dark">
                        Β Β 
                        Β <ul class="navbar-nav">                                                                  <li class="nav-item">                                                                    <a class="nav-link" href="#">Link 1</a>
                                 </li>
                                 <li class="nav-item">
                                         <a class="nav-link" href="#">Link 2</a>
                                 </li>
                                 <li class="nav-item    ">
                                        <a class="nav-link" href="#">Link 3</a>
                                 </li>

                                        </ul>
                                        Β Β Β Β 
                </nav>


                <h1>Quinton's Website</h1>

                <div id="content">
              
              
                </div>
        </body>

</html>```
lavish prismBOT
#

Hey @lime frigate!

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

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

lime frigate
#

Man i should i reformat it it just comes up like that

nova sonnet
#

not gonna lie to you the code could be written more cleanly

#

whats the issue?

lime frigate
#
<html>
        <head>

                <meta name="viewport" content="width=device-width, initial-scale=1">                                                                                              <!--<link rel="stylesheet"  href="bootstrap.min.css">-->
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">




        


        </head>

        <body>




                <navΒ class="navbar  bg-dark">
                        Β Β 
                        Β <ul class="navbar-nav">                                                                  <li class="nav-item">                                                                    <a class="nav-link" href="#">Link 1</a>
                                 </li>
                                 <li class="nav-item">
                                         <a class="nav-link" href="#">Link 2</a>
                                 </li>
                                 <li class="nav-item    ">
                                        <a class="nav-link" href="#">Link 3</a>
                                 </li>

                                        </ul>
                                        Β Β Β Β 
                </nav>


                <h1>Quinton's Website</h1>

                <div id="content">
              
              
                </div>
        </body>

</html>```
#

It was initially wayyy better until i pasted it here

lime frigate
nova sonnet
#

so the classes arent being applied right?

#

my suggestion is try clearing the cache

#

see if that does anything

lime frigate
#

U mean the cache of browser?

lime frigate
#

This is really pissing me off

#

Bro can u help me try it in ur browser so i can see if it's my browser's problem

nova sonnet
#

aight

#

let me try it out

lime frigate
#

Thx man appreciate it

nova sonnet
lime frigate
#

I think so, cuz button works

#

Btn btn-warning works

nova sonnet
#

this is what i got

lime frigate
#

Hmmmmm

#

It's my browser's problem then

#

Even if i used Microsoft edge it wouldn't work

nova sonnet
#

try indenting your code so its not all over the place

lime frigate
#

I did tho

#

Maybe it isn't supported for mobile?

#

I don't know man this is wierd

nova sonnet
#

you coding on your phone?

lime frigate
#

Yes for now

#

Computer's running into problem

#

But even if it works on the computer i wanna know why it isn't working on mobile

nova sonnet
#

not too sure on why its not working on your phone

lime frigate
#

Can u try running the file on ur phone hehe

nova sonnet
#

unfortunately dont have the set up on my phone

inland oak
#

They have quick adaptive thing testing

#

In just two clicks

#

For all types of devices

thorny quartz
#

hey anyone can help me in this error

#

|as_crispy_field got passed an invalid or inexistent field

#

this is my html code

#

{% extends "base.html" %}
{% load crispy_forms_tags %}

{% block content %}
<form action="" method="post" autocomplete="off">
{% csrf_token %}
{{form.tittle|as_crispy_field}}
{{form.genre|as_crispy_field}}
<div class="row">
<div class="col-md-4">
{{form.year_released|as_crispy_field}}
</div>
</div>
<div class="row">
<div class="col-md-8">
<button type="submit" class="btn btn-success btn-block btn-lg"><i class="fas fa-database"></i>
Submit</button>
</div>
<div class="col-md-4">
<a href="{% url 'list' %}" class="btn btn-secondary btn-block btn-lg">
<i class="fas fa-stream"></i> Back to list
</a>
</div>
</div>

</form>
{% endblock content %}

lime frigate
thorny quartz
#

and this is my view file

#

from django.shortcuts import render, redirect
from .models import Movie
from . import forms

def movie_list(request):
movie = Movie.objects.all()
return render(request, 'movielist.html', {'movie': movie})

def movie_add(request):
form = forms.Movies()

if request.method == 'POST':
    form = forms.Movies(request.POST or None)

    if form.is_valid():
        form.save()

return render(request, 'moviesadd.html', {'form': form})

def edit(request, id):
movie = Movie.objects.get(id=id)
return render(request, 'edit.html', {'movie': movie})

def update(request, id):
movies = Movie.objects.get(id=id)
form = forms.Movies(request.POST, instance=movies)
if form.is_valid():
form.save()
return redirect("/list")
return render(request, 'edit.html', {'movie': movies})

def delete(request, id):
movie = Movie.objects.get(id=id)
movie.delete()
return redirect('/list')

def view(request, id):
movie = Movie.objects.get(id=id)
return render(request, 'view.html', {'movie': movie})

nova sonnet
thorny quartz
#

@ionic ore @vestal hound help

vestal hound
pliant shoal
#

for help

thorny quartz
thorny quartz
pliant shoal
#

as_crispy_field, this is guy is making the cause

#

so what are you doing is rendering a individual field in form?

thorny quartz
#

yeah bro if i remove this then page will look like shit

pliant shoal
#

I think this might help you @thorny quartz

thorny quartz
#

Ok Thanks bro

pliant shoal
#

show me your forms @thorny quartz

#

and show the html after rendering

thorny quartz
#

here

#

from django import forms

from .models import Movie

class Movies(forms.ModelForm):
title = forms.CharField(max_length=200)
genre = forms.CharField(max_length=50)
year_released = forms.IntegerField()

class Meta:
    model = Movie
    fields = ['title', 'genre', 'year_released']
manic frost
#

In Starlette, is StaticFiles supposed to incorrectly handle query params? It turns index.html?foo=bar into index.htmlfoo=bar

#

Wait... I think it's a firefox bug?..

#

No, it's not

#

hm wtf, curl is showing me the proper redirect

#

Nevermind, I'm stupid, I did some URL manipulations in JS

pliant shoal
#

You got moderation role and yet asking doubts here?

manic frost
#

and don't write bug-free code

deft shore
#

Hello, how can I make it so when I delete an object, the file associated with that object also deletes? Or when I clear a file from an object's FIleField it also deletes on the disk. (in DJANGO)

thorn igloo
#

i.e, os.remove(filepath)

gritty moth
#

getting errors

#

for react

thorn igloo
gritty moth
#

ty

vestal hound
#

β€œdoubt” is very commonly used to mean β€œquestion” in India

inland oak
#

they have somewhere mistake in their educational system, which affects all indians %

#

I wonder if it could be possible to email all educational indian organizations to fix it.

vestal hound
#

I wouldn’t really call it a mistake

#

just a regional thing

#

for example, in my country we say β€œstay” when we mean β€œlive”, and Americans spell β€œbrooch” β€œbroach”

inland oak
#

like dialect?

vestal hound
#

something like that! that’s more or less how they form

inland oak
#

xD witnessing the history

dawn shard
#
{% for key,value in form.items() %}
<h2> {{key}}</h2>
<p> {{value}}</p>
{% endfor %}
``` 'form' is undefined

how can i solve this.
quick cargo
#

have you passed form via context

fair escarp
#

So recently, I tried to use selenium to load a website in a browser, navigate to a button and click it, then closing the driver and starting over again (To clear cache)
I got it to click about once every 5 seconds per active script i had open, most of the time going into actually restarting the browser driver and loading the webpage

Later though, I found out somebody else was clicking the same button roughly 5 times per second, which I could simply not achieve.
Is there a way to load and click the buttons with Python, without rendering or reloading the website / driver?

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains
from selenium import webdriver
import selenium
from time import sleep

while 1:
    driver = webdriver.Chrome()
    driver.get("**********")
    xpath2 = "//*[@id=\"main\"]/div[1]/div/div/div/div/div/div[2]/div[1]/div[2]/div[2]/div/a/div/div/button"
    elem2 = driver.find_element_by_xpath(xpath2)
    sleep(0.2)
    try:
        elem2.click()
    except:
        pass
    sleep(0.2)
    try:
        xpath = "//*[@id=\"CybotCookiebotDialogBodyLevelButtonLevelOptinAllowAll\"]"
        elem = driver.find_element_by_xpath(xpath)
        elem.click()
    except:
        pass
    sleep(0.2)
    try:
        elem2.click()
    except:
        try:
            driver.close()
        except:
            pass
    sleep(0.2)
    driver.close()

That's my code by the way, the reason for the try and excepts is because of a cookie message loading at different times, and i need to call the button press on the actual button twice because it cant click on it the first time since its not clickable at that moment

deft shore
#

hey guys! I have a Volunteer model that has a OneToOne field with a User. How could I update some User fields when updating Volunteer fields? in DJANGO

thorny quartz
#

can someone tell me meaning of this line {'movie': movie}) in this code

#

def view(request, id):
movie = Movie.objects.get(id=id)
return render(request, 'view.html', {'movie': movie})

versed python
dense slate
#

the whole thing in the {}'s is the context that is being returned to your template

#

you can also do something like context = {"movie": movie, "2ndVar":2ndVar, "3rdVar":3rdVar, etc}

#

and just return context

native tide
#

I don't know if its a dumb question or not. but lets say I have an async function In javascript
Is there a way to have it start running in the background on a certain event, and then await the result on a button click?
sort of to make it have a head start and make the result appear faster

#

so lets say I have a form with a txt input and a button. I was thinking of when a change event happens on the txt input, it starts the async function (to have it run in background) and when the button is clicked we await the result of the async function

#

or is there another way to think of this / do it in a different way. I'm not very knowledgeable on asynchronous stuff

#

If I am not making sense, tell me to clarify πŸ˜„

strong palm
#

Hi, I have a similar question to this: https://stackoverflow.com/questions/57321712/django-refactoring-the-right-way
My views are also getting longer and are full of if / else and different responses.
I'm trying to find out what is a good design pattern to refactor it into smaller functions.
All ideas welcome!

pliant shoal
vestal hound
pliant shoal
#

yeah, you can .

inland oak
scenic marsh
#

Hi, can anyone help me change the primary bootstrap color on a flask webapp? I want the default primary link/button color to be custom.

ionic raft
# scenic marsh Hi, can anyone help me change the primary bootstrap color on a flask webapp? I w...

I'm still learning myself, so I there may be additional clarification from others. As @thorn igloo mentioned, you need to add a custom style sheet. When you load in Bootstrap you add the stylesheet links to the header if you're using Bootstrap through the CDN. When you add a main.css (or other name that works for you) in your project's static folder, you then can overwrite all the styles you want. What happens (if I recall correctly) is that Bootstrap's defaults are applied (because you called the Bootstrap style in the header) and then your custom stylesheet is applied.

This is accomplished by loading Bootstraps stylesheet link and then your stylesheet link into your template header. Here's a snippet of this in my Django project's base.html template. html <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <!-- Local CSS --> <link rel="stylesheet" type="text/css" href="{% static 'articles/main.css' %}">

I make extensive use of commenting across all files and languages. If you're using Flask the syntax will be a little different for the href to the location for the custom css file.

long jackal
#

I am making a game platform website, with a list of games. I have coded the games but want a dynamic way to list them. Similar to how youtube lists it's videos
This is how the games are stored

games = [
  ["name",
  "description",
  "author",
  "file location"
  ],
]

So what I am looking for is a way to create a element from JS, have it look nice (so either a way to create a template in html, then reuse in JS for each game. Or create the template in JS and reuse for each game). Any help on how I can do this will be appreciated

ionic raft
# strong palm Hi, I have a similar question to this: https://stackoverflow.com/questions/57321...

This is a great question. I'm working on a large web application and know refactoring is definitely to be done. At the same time, things are working great too.

One of the challenges with refactoring is that there are some very valid reasons for conditions. My web app has 5 subscription tiers, along with two other fields against a profile that determine what each user should see. In addition, there are some 19 tables in the DB, and a number of those tables require queries to determine counts of the records that belong to the user that they can then access/have count totals rendered in the template. The web app is a complex process improvement project management application with lots of tools per project available.

There is no cookie-cutter approach for refactoring here. Certainly, the extent of refactoring required will be determined by the design approach to coding I took in the first place. If I made good use of functions, then I should have no instance of repeat code in the file. I should be able to call functions when those queries are needed repeatedly.

However, and this is my newness speaking (only coding Python for 4 months) I am wondering if I could make use of calling functions from other files to save on making those functions within each file. The result I am envisioning is that I only have a function written in one file, and then make that function available through an import within every other file, and then invoke it.

I look forward to insights shared on this question.

ionic raft
# long jackal I am making a game platform website, with a list of games. I have coded the game...

TL;DR: I try to build web apps by using the back-end web server to create the structure, style and data for a web-page and use JS for managing web page behaviour that responds to how the user interacts with the web page.

A few questions. What web framework are you using? Flask/Django/Other?
How are you storing the game data? In a DB? Games appears to be a list of lists based in your snippet. Might there be an improved data structure for your games? I could see a list of a dictionary being something that can be queried.
Your question about creating an element from JS...I use the application layer in Django to query the DB, and then prepare the data for the template render, which is then built in html. This may be my newness speaking, but my general design philosophy is to have the web server build pages where possible, and leave JS to focus on front-end behaviour. If I start by offloading the build of the front-end in the front by relying primarily on JS I'm putting the processing demand on the client web browser. My understanding is that that is not as efficient.

inland oak
#

something is wrong with stack overflow I think

grave raft
#

Hi, so I am working push notification in django with firebase using fcm_django, so after doing basic setup I want to test but since frontend is not ready how can I test using postman or some other way.

#

All the stackoverflow I searched was using device registration token but I can't understand how to get it

unreal bolt
#

im not sure if should i ask this here, but, does someone know if there is a server like this one, but for javascript? thanks!

unreal bolt
#

i mean to join

#

for example, i have joined this server, to learn py

#

i ask: u know some servers, but to learn js?

hexed holly
#

team django unite

tough crane
#

Quick question, is it better to start working with APIViews and rest-framworks / serializers froom the start or first try and do it without? (Just learned django freshly)..

tough crane
honest dock
#

Quick django question:
My html:

<p>{{ dealer.License.url }}</p>

My code:

 dealer = UpdateDealerProfileForm(
            initial={
                "Vat_Company_Number": profile.Vat_Company_Number,
                "Company_Number": profile.Company_Number,
                "Address": profile.Address,
                "Phone_Number": profile.Phone_Number,
                "Name_Representative": profile.Name_Representative,
                "Website": profile.Website,
                "License": profile.License,
                "Logo": profile.Logo
            }
        )
context["dealer"] = dealer

This works:

{{ dealer.License }}
#

and gives this:

flat temple
#

Anyone know how to implement Jest testing framework with a Django app?

glass marsh
#

Anyone here has developed apps in flutter before I am facing a huge issue. I am wanting to make a Flask server to send multiple images into the flutter frontend but I am unable to do so. Anyone here who knows how to? Any help would be great!

native tide
true kernel
#
{% load static %}

<style type="text/css">
    .header{
        background-color: rgb(35, 172, 165);
        float: left;
        padding-left: 10px;
    }

    .h2{
        color: chocolate;
    }
</style>

<header>
    <h2>InvestApp</h2>  <h4>Your own investing App</h4>
</header>


{%block content%}
{%endblock%}


#

the formatting is not working. Any suspicions?

#

it shows just black plain texts with no color or paddings

native tide
true kernel
#

oh in that case you shouldnt ask help on other channels

#

regardless, please help me guys

outer apex
true kernel
#

lol im so sorry

dense slate
#

If I'm not mistaken, you can just remove the period before header and h2 in your style

#

the period will look for a class with that name

random finch
#

Hi folks, relatively new with using flask. I have made an API that uses the flask framework and gunicorn server. I serve POST requests via it. What I want to do now is, add authentication on flask level. Basically I would have 3 parameters that should be passed via headers i.e. Team, API Key, API Secret. I'm not finding a clear guide on this, can anyone help?

honest dock
#

nevermind

#

lol

true kernel
#

lol yea

#

my page is taking too much time to load as its pulling data from an api

#

is this the time to use redis?

#

I might be wrong, but I think redis is used for distributed cache, and this seems like a temporal cache problem to me

quick cargo
#

better to test rather than make assumptions

#

e.g. have you used the network tool on your browser to get more detailed info on whats taking the time load

#

have you timed the latency of the server code itself

true kernel
#

i tested it on jupyter, and its consistent

#

takes around 5-7 secs to load

quick cargo
#

well, is it your api? is it someone elses api? How do other browser behave? Where is the api server located? where are you located?

true kernel
#

how do these things matter though

quick cargo
#

How much data are you request etc...

#

yes

#

they all matter

true kernel
#

sure, when i make a fancy program

#

but not really when its just a mini project, right?

quick cargo
#
  • If its not your api you cant do anything about it
  • If its one browser loads really fast and another doesnt, is something broken on the client side
  • If the api server is on the otherside of the world to you there is naturally going to be more latency, normally from UK -> US is 100ms+ of additional latency for a simple message, now consider how much more latency that adds when it's a large payload chunking data.
true kernel
#

sure, but in the end its taking time

#

so i would want to load it beforehand

quick cargo
#

well this is how you debug that :P

#

you also want to consider what the data actually is

#

how big is data should be your first question

#

/ how much data is there

#

if you're trying to load GB of data its obviously going to take a while

true kernel
#

im not sure this matters

#

i mean, I get your point

quick cargo
#

All of this very much matter, redis isnt a silver bullet and isnt going to magically make it faster at all

true kernel
#

these are important things, but not for this specific thing

flat temple
#

Anyone know how to add Mocha.js or Jest.Js to a Django application?

quick cargo
true kernel
quick cargo
#

okay, and how long does that api take to respond on average

#

and how much data does it return

opaque vale
#

laying out html and css is infuriating and i think im gonna take a sledgehammer to this

true kernel
#

so for the most part its the same data on the home page, and i would not want it to pull it everytime im reloading the homepage

quick cargo
true kernel
opaque vale
#

I'm using django/bootstrap and I just want a container with a header in the middle and two divs left/right below it as a split view

#

and for some reason this shit is the most difficult

quick cargo
opaque vale
#

Trying another framework isnt gonna make my issues go away though its just going to make them worse shortterm so i'll pass thanks

true kernel
quick cargo
#

to do that it would be

<div class="flex flex-col items-center">
  <h1>Hey, Im centered</h1>
  <div class="flex justify-between">
    <div>Im a container</div>
    <div>Im also container</div>
  </div>
</div>``` in tailwind
true kernel
#

you can refer to traversymedia on youtube. Or w3 if text is your thing

quick cargo
#

but TLDR flex boxes are your friend

true kernel
opaque vale
#

I'll take a look thanks

winter adder
#

Hello everyone , I hope we are all doing fine. Would you recommend freecodecamp contents to a web developer beginner or software developer/engineer beginner?

quick cargo
#

mm not really

#

you tube wise look at Corey Schafer for Python related web dev and fireship.io for general web stuff

nova pewter
#
from django import forms
from django.contrib.auth.models import User
from .models import UserProfileInfo


class UserForm(forms.ModelForm):
    Password = forms.CharField(widget=forms.PasswordInput())

    class Meta():
        model = User
        fields = ('username', 'email', 'Password')


class UserProfileInfoForms(forms.ModelForm):
    class Meta():
        model = UserProfileInfo
        fields = ('portfolio_site', 'profile_pic')
<form method="POST" enctype="multipart/form-data">
    {% csrf_token %} {{ user_form.as_p }} {{ profile_form.as_p }}
    <input type="submit" value="Register" />
  </form>

so i am following this tutorial and the mentor uses
user_form.as_p
and
profile_form.as_p
and i didn't quite get what user and profile in form.as_p means?
there is no variable named profile in my code, only have profile_pic

ionic raft
ionic raft
# opaque vale Trying another framework isnt gonna make my issues go away though its just going...

I started a few months ago and was pointed in the direction of Bootstrap as a css styling framework. I cannot emphasize what an excellent starting point Bootstrap 5 is! Even though my web application has grown to huge proportions there's not been a moment where I've felt the need to ditch it. This is the end result of the logged-in dashboard for a process improvement project management web app...

ionic raft
# nova pewter ```diff from django import forms from django.contrib.auth.models import User fro...

I believe that form.as_p is a standard tag that will render the form fields with paragraph breaks. There are other ways of presenting a form. It's a quick way of separating all fields with paragraph breaks. If you don't use a formatting tag the form will be messy as each label and field will be displayed in order with no layout structure whatsoever.

If you really want to maintain simple (where you don't build your form manually, inputs/labels/text etc.) then you can look at crispy forms. Combined with Bootstrap, and Crispy Forms will instantly make very pretty forms with very little effort.

nova pewter
ionic raft
# nova pewter i get the form.as_p but why did he use "profile_" before it? to my little knowle...

Because there are two forms being presented in the template: form (for the user signin) and profile (for the additional profile info). Even though you're not showing your models.py file, I can see that you are showing forms.py. I observe two forms, UserForms and UserProfileInfoForms.

Also, without seeing views.py for the app I cannot verify if the template will render as expected as I am unable to see if the forms are passed into the template correctly.

Whew...I started Django 1.5 months ago from new. I'm starting to really get it πŸ™‚

nova pewter
#

so its just like commenting and has no effect on the form?

ionic raft
# nova pewter so its just like commenting and has no effect on the form?

Not really. If you need help troubleshooting a framework like Django you need to understand the sequence:

  • models.py for the app ishows what the DB stores, the data structure.
  • forms.py is where you (optionally) build a form explicitly
  • views.py is where you build the View. You can specify fields here and thus have no need for forms.py
  • your html file (the template) will need the tags to render the variables that views passes to it.
  • finally, urls.py for the app will need the url pattern to ensure you can refer to it through a static url link.

The challenge here is you showed only 2/4 snippets needed to verify/troubleshoot. You showed forms.py and the template. But without models.py and views.py for the app we can't really troubleshoot.

the tag .as_p is a quick and dirty way of taking the form fields passed from the view (potentially declared in forms.py, but not always) and rendering that form. Rather than seeing it as "commenting" look at as_p as formatting.

nova pewter
#

i see, thank for the help i'll look into it.

ionic raft
#

You're welcome. The Django documentation on forms is excellent and is well worth the read. It'll explain both the quick way {{form}} and building the form field by field. However, I've not needed to build a form manually as yet.

nova pewter
#

as you suggested i have bookmarked crispy forms i will look into it later on, any other libraries worth checking out?

ionic raft
nova pewter
#

cool

ionic raft
# nova pewter cool

Yes...not having to manually build up a form is very cool. It also guarantees a consistent input UX across your site. My sense is that crispy forms combined with Bootstrap will provide for most input capture needs. Anything more demanding, such as splitting fields across rows etc. would need to be manually built.

nova pewter
#

thanks for the help fam!

ionic raft
# nova pewter thanks for the help fam!

Paying it back, Bruh! I've been helped many times on this server. I make a point of logging in to help while I work. And since I'm getting deep on Django it would appear I can help there πŸ™‚

west peak
#

Hi brothers, i have a little question about implement websockets in my web

#

any idea to implement this? because i am using django and channels

#

but in the channels documentation said to use docker

#

but idk if it change the method the deploit my app

native tide
#

hi all, i have my code here https://codesandbox.io/s/reverent-sky-dcbdp?file=/src/App.js , and it can be run by entering thisurl https://dcbdp.csb.app/?datacenter=USMTT1 , the issue is i am using tr td from strach but want to clean my code and use exisiting component available online, any thoughts on what shall i clean up to make to look more visually appealing and which components i can use?

CodeSandbox

reverent-sky-dcbdp by akhil-quarantine using react, react-dom, react-router-dom, react-scripts

native tide
stray shard
#

hello

#

IS THERE ANYONE WHO CAN HELP ME.....

#

I want to create a sidebar like this ritual.com website

nova pewter
#

i get this "user object has no attribute ''set_password""

#
from django import forms
from django.contrib.auth.models import User
from .models import UserProfileInfo


class UserForm(forms.ModelForm):
    Password = forms.CharField(widget=forms.PasswordInput())

    class Meta():
        model = User
        fields = ('username', 'email', 'Password')


class UserProfileInfoForms(forms.ModelForm):
    class Meta():
        model = UserProfileInfo
        fields = ('portfolio_site', 'profile_pic')

#

models.py

from django.db import models
from django.contrib.auth.models import User
from django.db.models.deletion import CASCADE


# Create your models here.
class UserProfileInfo(models.Model):
    user = models.OneToOneField(User, on_delete=CASCADE)
    portfolio_site = models.URLField(blank=True)
    profile_pic = models.ImageField(upload_to='profile_pics', blank=True)

    def __str__(self):
        return self.user.username
#

do i need to inherit this method form some other class?

versed python
nova pewter
timid nest
#

How can I do a global variable in flask? Any alternatives to using a global? Like putting it in the app constructor?

inland oak
#

And access later as
from flask import current_app
current_app.config[variable name]

velvet yew
#

Is there a JS wizard among us who would be happy to help & answer a few questions with regards to my Django app? I want to start converting the Django template tags I used for prototyping to JS

violet lynx
#

anyone has idea a/b why django fast on one machine and slow on another machine, using docker same code simplest view func just return single constant

inland oak
#

by any chance you are using whitenoise?

#

if yes, that's the problem.

twilit needle
proper hinge
#

Sometimes I feel like in the only person who likes CSS

#

Don't get me wrong, the classes in these frameworks are convenient, but when I'm combing a bunch of tiny building blocks it just creates a mess of HTML

#

My understanding is that the goal of tailwind is to take that idea to the next level. I was already finding the HTML getting messy when using bootstrap.

ionic raft
# twilit needle bootstrap is very opinionated. Use tailwindCSS instead to build the same things ...

Offering an un-requested opinion about tearing bootstrap out my web app project (some 20k lines big already) to replace it with Tailwinds with zero context for my project, the roadmap, or the timing of release, is not actually helpful...at all. I appreciate the intention. As for relevance or practical advice, it leaves a lot to be desired. I suggest checking in for some validation before weighing in with such an un-invited opinion. IF my website looked like dog shit that'd be one thing. I happen to think it looks decent for a v1 prototype built in 6 weeks by a web dev who didn't know Python before Apr 15, 2021, and learned css only a couple of months ago...

versed python
#

css is a pain ngl

ionic raft
# proper hinge Sometimes I feel like in the only person who likes CSS

I like CSS. However, as someone new to CSS, what Bootstrap gave me was a decent looking foundation to build on for this v1 web app. Function AND form matter. I didn't want to spend months learning about form and style without function in play.
However, now that I've used bootstrap I've learned a LOT about css. I'd actually see going without a Framework as a great learning experience down the road.

versed python
ionic raft
#

I'm about to launch 3 months of open alpha testing. That'll show me the way πŸ˜‰

proper hinge
#

The idea of "never leaving html" is ironically a really bad advertisement for me. I think with larger projects it would be nicer to build custom css classes that use a preprocessor combine stuff from a css framework.

versed python
ionic raft
#

I actually just completed building the alpha testing application forms today. About an hour ago.

versed python
#

i personally dont like switching to some other file just to see what btn applies

ionic raft
versed python
proper hinge
#

I find html with a bunch of classes in each element to have poor readability. Furthermore, the purpose of using some class can sometimes feel unclear as it just appears like random classes combined together since the building blocks are so small.

ionic raft
#

My UX challenge is a balance of Form AND Function. When you're building a rich information active working site, space is at a premium

violet lynx
ionic raft
#

Oh my goodness...I'd have to check the template to answer that...
The thing is, I've actually layered custom css on top of Bootstrap. The last I checked there were 649 lines of css...
08-15:
320 files
11,118 Python
7,601 html
649 css
19,368 total

#

Which was my point. Bootstrap gave me a foundation I learned to navigate and make my own. It saved me a ton of time and got me to a decent style without holding me back.

versed python
inland oak
#

gunicorn?

ionic raft
proper hinge
#

Not very nice

versed python
#

that looks like bootstrap tho

#

but yes

proper hinge
#

Yes it is

versed python
ionic raft
#

LOL'ing here....
And yes, it does look like bootstrap. AND, when you learn bootstrap it actually becomes readable.

#

I'm not supporting it for readability, just saying that with time it can be read.

versed python
manic frost
#

@proper hinge I like how in the "Build whatever you want, seriously" section (https://tailwindcss.com/) they demonstrate how you have to modify the entire HTML of a thing to change how it looks, and you can't change it at runtime (e.g. with CSS variables), or by just changing a stylesheet definition

ionic raft
proper hinge
versed python
#

as i said

#

to each their own

manic frost
#

yeah I guess it's more of a preference

ionic raft
#

My intention/plan down the road is to hire someone who LOVES css and have them improve LanesFlow. I don't need to be the css-guru. It's not my bag, nor does it need to be. I'm just glad I could get v1 to a state where style > dog shit πŸ˜‰

twilit needle
proper hinge
#

I also never put to practice the idea of using a preproccessor to combine framework classes into my own class

ionic raft
violet lynx
twilit needle
#

I didn't literally tell you to tear it out..

#

anyways it doesn't matter

inland oak
#

what is your docker running command there?

ionic raft
# twilit needle I didn't literally tell you to tear it out..

When I read "Use tailwindCSS instead to build the same things easily, but with more flexibility" in reply to the screenshot that is how it came across. You started by saying that Bootstrap is opinionated, and then proceeded to offer your un-invited opinion about how I should be using something else. Had you simply offered that opinion without quoting me on the screenshot of my web app it would have been a non-issue

native tide
#

Is there a chance to create random planets and put details and its other features on web and use it for discord bots

violet lynx
#

it's working well on one machine

twilit needle
#

is anyone into python graphql here?

violet lynx
#

this's very strange to me

inland oak
versed python
inland oak
#

you should not use it when deploying to anywhere else, it is only for your localhost.

twilit needle
# versed python yeah

have you been successful with it? I feel that the ecosystem needs more features, like validation rules, input validation and a lot more

versed python
#

absolutely lol

#

i wrote a para a few days back mourning this

#

here

#

oh wait

#

that was a reply to you

#

lmao

twilit needle
#

also, python is a single threaded language. So, you don't get "real" multithreading, and will be writing blocking code. The only way to use dataloaders with frameworks like django and flask is through the "promise" library, because they shouldn't block. If you use asyncio supported libraries like quart, you can use quart instead. But promises aren't native in python and I dont like it.

#

This is what github did with ruby (another single threaded language). They promisifed blocking code

native tide
#

I want to create an planet rp bot

twilit needle
#

when you do it in javascript, everything fits nicely

manic frost
#

isn't Future the same as a promise? what's the difference?

violet lynx
proper hinge
versed python
twilit needle
#

no clue there lol

#

but I know they have a library named Juniper

inland oak
#

plus serving static files and attaching certificate with nginx as reverse proxy (which is made as second docker container running together with first one via docker compose)

versed python
twilit needle
# versed python have you tried Rust? How does it play with graphql?

but for python, asyncio should fix all the problems. The only problem is that the major players in this ecosystem, django and flask, weren't really built for asyncio. You'll have to use FastAPI or Quart or Sanic, but they are very new libraries and it feels like moving away from the gold standard

violet lynx
proper hinge
#

I think there are async decent substitutes for flask, but not for something as substantial as django

versed python
#

but the community there is very stagnant

twilit needle
#

django doesnt support asyncio yet because it's ORM is sync. But because they have a lot of batteries included, they can't do a lot of breaking changes easily.

#

so we cant expect it in the foreseeable future

elder rover
#

hi.. any idea build booking time slot like this, how to print date like this

twilit needle
proper hinge
inland oak
# versed python can you send me the config of the second container? I was not able to do it a fe...

nginx/Dockerfile

FROM nginx:1.19.0-alpine

RUN rm /etc/nginx/conf.d/default.conf
COPY nginx.conf /etc/nginx/conf.d

nginx/nginx.conf

upstream django {
  server web:8000;
}

server {
  listen 4000 ssl;

  # # location of SSL certificates
  ssl_certificate /app/web/ssl/ssl.crt;
  ssl_certificate_key /app/web/ssl/ssl.key;

  location / {
    proxy_pass http://django;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $host;
    proxy_redirect off;

  }

  location /static/ {
    alias /app/web/build/static/;

    if ($request_method = 'OPTIONS') {
        add_header 'Access-Control-Allow-Origin' '*';

        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';

        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';

        add_header 'Access-Control-Max-Age' 86400;
        add_header 'Content-Type' 'text/plain charset=UTF-8';
        add_header 'Content-Length' 0;
        return 204; break;
     }

     if ($request_method = 'POST') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
     }
     if ($request_method = 'GET') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
     }
  }

}
#

docker-compose.yml

version: '3.8'
services:
  web:
    build:
      context: .
      dockerfile: dockerfile
    volumes:
      - static_volume:/app/web/build/static
    expose:
      - 8000
    env_file:
      - ./.env.${mode}
    
  nginx:
    build: ./nginx
    volumes:
      - static_volume:/app/web/build/static
      - ./ssl:/app/web/ssl
    ports:
      - 5555:4000
    depends_on:
      - web

volumes:
  static_volume:
#

i was launching it as mode=test docker-compose up --build for example

#

it used my .env.test file of env then

#

folder ssl in my project had certificates obviously

#

I have a script for self generated(not useful for production though) ones if needed

#

openssl req -x509 -nodes -days 3650 -newkey rsa:4096 -keyout ssl.key -out ssl.crt -config ssl.cfg -extensions v3_req

#

for that matter my main dockerfile I guess too

FROM python:3.8-slim

ENV PYTHONUNBUFFERED 1
ENV PYTHONDONTWRITEBYTECODE 1

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

COPY ./requirements.txt ./
RUN pip install -r requirements.txt

# Create directories app_home and static directories
ENV HOME=/app
ENV APP_HOME=/app/web
RUN mkdir $HOME
RUN mkdir $APP_HOME
WORKDIR $APP_HOME

COPY . .
# RUN python manage.py migrate

EXPOSE 8000
RUN python3 manage.py collectstatic -c --noinput

RUN chmod 777 $APP_HOME

CMD gunicorn core.wsgi -b 0.0.0.0:8000

it is with postgres libraries coming installed

elder rover
proper hinge
#

You could use JavaScript to register a click event handler on the dates.

deft shore
#

Is there a better or cheaper alternative to S3 Buckets? Specifically for a Django project.

versed python
inland oak
#

in your case you could exposing to 443 port

#

plus, you would need a bit editing nginx config

#

so it would redirect from 80 port to 443 port, and exposing nginx 80 port then

versed python
#

alright thanks

#

have you used dokku?

#

heard a lot about it

inland oak
#

nope

#

first time hearing

versed python
#

it manages docker and nginx configuration

#

pretty slick

#

plan on using it soon

inland oak
versed python
#

no it works completely through containers

#

its basically heroku but for your own server

balmy sparrow
#

Does anyone know of a good library for implementing Django session logging?

true kernel
#

value error incorrect timezone setting 'Asia/Kolkata' ?????

#

Can i get a list of all timezones?

thorn igloo
true kernel
#

my dumbass misspelled asia

thorn igloo
#

ahh, it happens

gentle ingot
#

How hard would it be to set up an e-commerce with just PayPal checkout for 2-4 products using flask?

thorn igloo
#

how hard something is is kinda relative to how much you know

gentle ingot
#

My google-foo is decent.

#

Django is just overwhelming.

thorn igloo
#

eh

#

paypal has some documentation on implementing the payment option onto your website. although it looks terrible from what i've seen

gentle ingot
#

I thought about the buy me button. But then if someone wants everything on the site then it would be a headache to group that and not charge separate shipping it seems.

thorn igloo
#

yea buy me button not really that customizable tbh

#

but that's just me

worn fjord
#

guys can anyone help me with flask?

#

I'm appending a list to add 2 images in it and then i had made a detec_face function which takes two images as a parameter and returns if they are same or not. But as soon as i run the program on the localhost and send two images it crashes and gives me an error on the detect_face function :/

thorn igloo
worn fjord
#

`@app.route('/', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
file = request.files['file']
if file and allowed_file(file.filename):
list.append(file)
if len(list) == 2:
if detect_face(list[0], list[1]):
return html + '<br><h2>These faces match</h2>'
else:
return html + '<br><h2>These faces dont match</h2>'

        filename = secure_filename(file.filename)
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        file_url = url_for('uploaded_file', filename=filename)
        return html + '<br><img src=' + file_url + '>'
return html`
#

`def detect_face(img1_path,img2_path):
# If required, create a face detection pipeline using MTCNN:
mtcnn = MTCNN(image_size=160, margin=0)

# Create an inception resnet (in eval mode):
resnet = InceptionResnetV1(pretrained='vggface2').eval()

confidence = []

img1 = img1_path
img2 = img2_path

j = 1
img_cropped = mtcnn(img1, save_path=f'D:/python_Api_try/frame_{j}_face.jpg')
embd1 = resnet(img_cropped.unsqueeze(0))

j = 2
img_cropped = mtcnn(img2, save_path=f'D:/python_Api_try/frame_{j}_face.jpg')
embd2 = resnet(img_cropped.unsqueeze(0))

embd1 = embd1.detach().numpy()
embd2 = embd2.detach().numpy()


matches = face_recognition.compare_faces(embd1, embd2, 0.6)
print(matches)

if True in matches:
    return 1
else:
    return 0`
thorn igloo
#

what is the error saying? let's start there

worn fjord
#

ok wait ill run and copy paste directly

elder rover
worn fjord
#

@thorn igloo

#

as soon as i push in the second image

elder rover
thorn igloo
worn fjord
#

oh its a framework for face detection

#

comes along with pytorch and opencv. this function was given by another internee to me, i had to integrate flask with this

gritty coyote
#

Hello everyone, Is there a job board in this server?

worn fjord
thorn igloo
worn fjord
thorn igloo
#

the function accepts the image paths, you're passing the file object

worn fjord
#

yes but... i changed the detect_face, for example previously it was accepting paths but then in the function you can see i wrote img1= img1path .. previously it was taking the image from the path. now since im just passing the images it should work fine

worn fjord
#

also, i ran the detect face on cmd it's working fine.

thorn igloo
#

you probably need to save first if you don't want to rewrite the function, unless you can get the path without saving somehow

thorn igloo
worn fjord
worn fjord
thorn igloo
#

you can use the os module to delete files

worn fjord
dawn shard
#
@app.route('/form')
def form():
    return '''<form action="/data" method = "POST">
    <p>Name <input type = "text" name = "Name" /></p>
    <p>City <input type = "text" name = "City" /></p>
    <p>Country <input type = "text" name = "Country" /></p>
    <p><input type = "submit" value = "Submit" /></p>
</form> '''
 
@app.route('/data/', methods = ['POST', 'GET'])
def data():
    if request.method == 'GET':
        return f"The URL /data is accessed directly. Try going to '/form' to submit form"
    if request.method == 'POST':
        form_data = request.form
        return flask.render_template('data.html',form_data = form_data)
 ``` This is in main.py 

```python
{% for key,value in form.items() %}
<h2> {{key}}</h2>
<p> {{value}}</p>
{% endfor %}
``` this is in data.html

I am getting error that form is not defined. How can I tackle this.
thorn igloo
#

you did not pass it in render_template

dawn shard
#

So what should I do next????????

thorn igloo
#

flask.render_template('data.html',form_data = form_data) pass your form as a parameter here

native tide
#

Can anyone help me in this creation

vestal hound
#

you need to code it yourself

#

of course, there exist implementations

#

you can look into, for example, Material Design components

thorn igloo
stone pebble
#

hey guys, I just have a quick LATEX issue

thorn igloo
stone pebble
thorn igloo
#

yea i don

#

i don't know what's causing that

#

my latex knowledge is not that deep

stone pebble
#

I feel you man but it's at least good enough

#

I need to send out a resume today

final lake
#

How does Grammerly work?
How do they teach computer to automatically correct the text?
And how can we learn to do that and make something ?

native tide
#

for a start

#

and then I believe they have a known phrases algorithm that studies other texts based upon well known articles etc and relates it to your texts

final lake
native tide
#

well

#

yes

#

thats how it exists today

#

you just need to learn a bunch of algorithms

final lake
native tide
#

whatever language

brave stag
#

for django what are the feasible web server for apis in production?

glacial yoke
#

why does it give me this error when I try to runserver?:

ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? 
#

It used to work perfectly fine, but now for some reason it just stopped working

#

i tried reinstalling django, but it didn't help

lavish ferry
#

You aren't in some virtual environment?

glacial yoke
#

nope

#

I never even used virtual environments

#

I literally have no idea why it would give me this error

lavish ferry
#

Did you try just closing your ide completely and reopening it?

lavish ferry
#

You are definitely importing it correctly? Right capitals/lower-case?

glacial yoke
#

It is auto compiled when you start your project

#

I literally haven't looked at it since I started project

lavish ferry
#

Well inadvertently it seems you have changed something

#

I wish I could help more, though it is probably something dumb/simple

glacial yoke
#

I definitely haven't changed everything

#

oh well, I guess I'll just have to restart my project

#

and copy in all the files

#

it doesn't even highlight as a problem

lavish ferry
#

No idea, any chance you are good at HTML though?

glacial yoke
#

wdym, you need some help?

lavish ferry
#

I need some help

glacial yoke
#

right

#

yeah, I'm fine with html

#

what do you need help with

vestal hound
#

@glacial yoke how are you executing it?

glacial yoke
vestal hound
#

from IDE? in IDE terminal? in external terminal?

#

@lavish ferry just ask

glacial yoke
#

in IDE terminal

#

I even tried in external terminal

vestal hound
glacial yoke
#

doesn't work

glacial yoke
vestal hound
#

that’s the problem

#

it depends on which environment manager you used when you set up the project

glacial yoke
vestal hound
#

the method will vary based on that

glacial yoke
#

I just ran it from my ide, without creating any virtual environments

#

so Idk why am I getting the problem now

vestal hound
glacial yoke
#

how do I fix it then?

vestal hound
#

in your IDE terminal

#

if you run pip install django what happens

glacial yoke
vestal hound
#

paste as text

glacial yoke
#
Requirement already satisfied: django in c:\users\Π΅Π³ΠΎΡ€\appdata\local\programs\python\python39\lib\site-packages (3.2.6)
Requirement already satisfied: asgiref<4,>=3.3.2 in c:\users\Π΅Π³ΠΎΡ€\appdata\local\programs\python\python39\lib\site-packages (from django) (3.4.1)
Requirement already satisfied: sqlparse>=0.2.2 in c:\users\Π΅Π³ΠΎΡ€\appdata\local\programs\python\python39\lib\site-packages (from django) (0.4.1)
Requirement already satisfied: pytz in c:\users\Π΅Π³ΠΎΡ€\appdata\local\programs\python\python39\lib\site-packages (from django) (2021.1)
vestal hound
#

run echo $PATH?

lavish ferry
#

Cheers, I keep failing with what should be simple HTML. I just want to have an image container 400px in height and 100% in width, with a 26rem in width card horizontally and vertically centred over the image which contains some H1 text. I can't for the life of me figure it out unfortunately.

glacial yoke
#

that's all that it says

vestal hound
#

what OS

#

Windows?

glacial yoke
#

windows

#

yeah

vestal hound
#

ugh

#

I can’t remember how to do this on Windows

#

but if Django is showing as installed

#

then there’s an issue with your PATH

#

alternatively, PYTHONPATH

#

these control where Python looks for installed packages

vestal hound
#

that’s why they can’t be found

#

you should be able to Google that

vestal hound
#

okay so

#

you want a wrapper

#

around the image

glacial yoke
#

I tried googling, I can't find the right answer

#

literally nowhere

vestal hound
#

of the relevant size

glacial yoke
#

Everyone talks about virtual environments, but I have never used one

vestal hound
glacial yoke
#

idk how to even start one lmao

vestal hound
#

and another element

#

that is absolutely positioned

#

then use top and left to fix it to the centre

#

just look into position: absolute

#

that’s a start

glacial yoke
vestal hound
#

hm

#

I’m not familiar with VSCode so I don’t know how it manages environments

#

but anyway something is wrong with your path variables

lavish ferry
#

Would the wrapper just be a container?

#

Also presuming they aren't using a virtual environment they essentially just have everything they have ever pip installed installed and ready in VSCode

#

Though I don't know how to check the path unfortunately

vestal hound
#

then it's still an environment issue

vestal hound
lavish ferry
#

So I would put the image and the card in a container and then reposition the card?

vestal hound
#

something like this

#
<div class="container">
    <img src="...">
    <div class="card">
        <h1>text</h1>
    </div>
</div>
.container {
    position: relative;
    display: flex;
}

.card {
    position: absolute;
    top: calc(50% - 20px);
    left: (50% - 20px);
    width: 40px;
    height: 40px;
}
#

off the top of my head

#

I haven't written frontend stuff for a few months

#

but this should be it

#

@lavish ferry

lavish ferry
#

after all my suffering, it should be that easy lol

#

I will give it a spin as soon as I make it home (got frustrated and left to get food)

#

Why the -20px in the CSS though?

glacial yoke
#

@vestal hound I even tried to create a new project in the same env, as where the django is installed, and it still didn't work

#

When I tried to run it

#

it just gave me the same mistake

vestal hound
#

you have a problem in the PATH

vestal hound
#

you want it to be centred

#

right

#

if it's just 50%

#

the left edge

#

will be at the horizontal midpoint

lavish ferry
#

Oh

#

Yep

vestal hound
#

which means the right edge will be @ the horizontal midpoint + its width

lavish ferry
#

I see, that makes sense

grave raft
#

In django if we have one to one relation can we overwrite the fields we are creating one to one relationshi with ??

grave raft
#

class User(AbstractUser): name = models.CharField(max_length=100) phone = PhoneNumberField(unique=True) email = models.EmailField(_('email address'), unique=True) phone_verified = models.BooleanField(default=False) email_verified = models.BooleanField(default=False)

#

`class TemporaryUnverifiedUserUpdate(models.Model):

user = models.OneToOneField(
    User, on_delete=models.CASCADE) 
phone = PhoneNumberField(unique=True, null=True, blank=True)
email = models.EmailField(
    ('email address'), unique=True, null=True, blank=True)
phone_verified = models.BooleanField(default=False)
email_verified = models.BooleanField(default=False)`
#

now if i create instance of TemporaryUnverifiedUserUpdate and updates it phone value and save

#

will it change the value of phone in user instance

grave raft
lavish ferry
#

Do

```Python
Code
vestal hound
lavish ferry
#

I know what it is, turns out my phone doesn't do the box I expected from the first one

#

Oh wrong symbol I see, phone again xd

#

Does Discord have some kind of escape character?

native tide
#

yeah

#

\

#

basically escapes a lot of things

bright spindle
#

is there someone able to understand django-rest authorization issues

#

i have full access to the admin and other non-django rest stuff outside of my network

#

and inside

#

however the second i start using the django-rest api trough react, i get Unauthorized (applies to all endpoints), unless i'm on my local ip address (192.168.x.x, localhost and 127.0.0.1 won't work)

bright spindle
#

from what i see i think the CORS seems to be setup properly

CORS_ORIGIN_ALLOW_ALL = True

CORS_ALLOW_METHODS = [
    'DELETE',
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT',
]
CORS_ALLOW_HEADERS = [
    'accept',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
]
thorn igloo
bright spindle
#
Unauthorized: /api/any_endpoint
HTTP POST /api/any_endpoint 401 [0.03, 127.0.0.x:12345]
thorn igloo
#

you have authentication for your endpoint?

bright spindle
#

not that i'm aware of

#

it only works when accessing from 192.168.x.x

thorn igloo
#

did you configure your headers in react?

bright spindle
#

that isnt something i'm able to check right now

#

cause i'm only managing the backend

#

if i try to request to the api endpoint trough postman, and it gives the same error

#

i think that will isolate it to django

#

there's this thing tho

DEVELOPMENT_ENVIRONMENT = env('DEVELOPMENT_ENVIRONMENT', default='local')
#

i have no idea what this is, someone added this before i got the code

thorn igloo
#

i think the issue might be the request header in your frontend

#

but that's just my thoughts

bright spindle
#

i'll look up with the frontend gyu, and see if there's any issues with the frontend headers

#

the weird thing is that this worked out of the box the first time i ran it

lavish ferry
#

@vestal hound it works but I can't get it to horribly destroy the size of the image:

<div class="image-container">
    <img class="d-block w-100"
        src="{{url_for('static', filename='images/other/home_encryption.png')}}">
    <div class="card image-card justify-content-center">
        <h1 class="text-center">Data Manipulation</h1>
    </div>
</div>
#
.image-container {
  width: 100%;
  height: 400px;
  position: relative
}

.image-card {
  position: absolute;
  top: calc(50% - 20px);
  left: calc(50% - 200px);
  width: 24rem
}

img{
  max-width: 100%;
  max-height: 100%;
  display: block
}
true kernel
#
TypeError at /admin/
'str' object is not a mapping
Request Method:    GET
Request URL:    http://127.0.0.1:8000/admin/
Django Version:    3.2.5
Exception Type:    TypeError
Exception Value:    
'str' object is not a mapping
Exception Location:    /home/feynman/anaconda3/lib/python3.7/site-packages/django/urls/resolvers.py, line 490, in _populate
Python Executable:    /home/feynman/anaconda3/bin/python
Python Version:    3.7.11
Python Path:    
['/home/feynman/StockInvestor/investpro',
 '/home/feynman/anaconda3/lib/python37.zip',
 '/home/feynman/anaconda3/lib/python3.7',
 '/home/feynman/anaconda3/lib/python3.7/lib-dynload',
 '/home/feynman/anaconda3/lib/python3.7/site-packages',
 '/home/feynman/anaconda3/lib/python3.7/site-packages/yahoo_finance_api-0.0.1-py3.7.egg',
 '/home/feynman/anaconda3/lib/python3.7/site-packages/locket-0.2.1-py3.7.egg']
Server time:    Tue, 17 Aug 2021 20:04:36 +0530
#

Not able to debug this. Please help!

lavish ferry
#

I have been buried by someone who hasn't even shared enough information to actually be helped. 😦

vestal hound
#

I mean

#

you're stretching the image

lavish ferry
#

Yes. I don't know how to move from this to the desired stretch whilst maintaining the aspect ratio

#

Which isn't actually a stretch because the image is huge, but the point should still be clear.

vestal hound
#

I don't get it

#

what do you expect to happen

lavish ferry
vestal hound
vestal hound
true kernel
lavish prismBOT
#

Hey @true kernel!

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

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

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

https://paste.pythondiscord.com

true kernel
#

Environment:

Request Method: GET
Request URL: http://127.0.0.1:8000/admin/

Django Version: 3.2.5
Python Version: 3.7.11
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'investApp']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']

vestal hound
#

that's not the traceback

true kernel
#

Traceback (most recent call last):
File "/home/feynman/anaconda3/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/home/feynman/anaconda3/lib/python3.7/site-packages/django/core/handlers/base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/feynman/anaconda3/lib/python3.7/site-packages/django/contrib/admin/sites.py", line 250, in wrapper
return self.admin_view(view, cacheable)(*args, **kwargs)
File "/home/feynman/anaconda3/lib/python3.7/site-packages/django/utils/decorators.py", line 130, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/home/feynman/anaconda3/lib/python3.7/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "/home/feynman/anaconda3/lib/python3.7/site-packages/django/contrib/admin/sites.py", line 222, in inner
if request.path == reverse('admin:logout', current_app=self.name):
File "/home/feynman/anaconda3/lib/python3.7/site-packages/django/urls/base.py", line 54, in reverse
app_list = resolver.app_dict[ns]
File "/home/feynman/anaconda3/lib/python3.7/site-packages/django/urls/resolvers.py", line 526, in app_dict
self._populate()
File "/home/feynman/anaconda3/lib/python3.7/site-packages/django/urls/resolvers.py", line 490, in _populate
{**defaults, **url_pattern.default_kwargs},

Exception Type: TypeError at /admin/
Exception Value: 'str' object is not a mapping
'

#

@vestal hound

vestal hound
true kernel
#

which part?

#

theres a lot of code, a whole project with many files πŸ™‚