#web-development

2 messages ยท Page 167 of 1

inland oak
#

there probably some more cloud-ready solutions to do the same

#

which perhaps have less steps to do

edgy sable
#

so i bought the domain and it will be a website that runs on apache2 and am developing an api but don't know how to connect it to my site

inland oak
#

did you deploy your app

#

is it having ip address?

edgy sable
#

so i just started with flask a few weeks ago i don't know much about it so right now i'm developing the api and it's running on pycharm and the website is running on my dedicated server

inland oak
edgy sable
#

Ubuntu

inland oak
#

and you can access your app with certain IP?

#

all right

#

then you just need

inland oak
#

re deploy your app with enabled https

stark tartan
#

class TestCreateFrom(forms.ModelForm):
    class Meta:
        model=Test
        fields ='__all__'
        exclude=('teacher','subject')

        widgets = {
               'exam_start_time': forms.DateTimeInput(attrs={"type":"datetime-local" },
                format='%Y-%m-%d %H:%M:%S'),

               'exam_end_time': forms.DateTimeInput(attrs={"type":"datetime-local" },
                format='%Y-%m-%d %H:%M:%S')



        }

inland oak
#
  1. turn on where your domain controlling pannel
#

and make necessary DNS records, A records and somthing? to point to your IP

edgy sable
#

i bought my domain from namecheap and the ssl certificate runs through cloudflare

inland oak
#
  1. ???
  2. Proffit!
inland oak
stark tartan
#

class TestCreateFrom(forms.ModelForm):
    class Meta:
        model=Test
        fields ='__all__'
        exclude=('teacher','subject')

        widgets = {
               'exam_start_time': forms.DateTimeInput(attrs={"type":"datetime-local" },
                format='%Y-%m-%d %H:%M:%S'),

               'exam_end_time': forms.DateTimeInput(attrs={"type":"datetime-local" },
                format='%Y-%m-%d %H:%M:%S')



        }

#

||how to add initial date time from django ||

edgy sable
#

so domain and certificate is ready with me the site also runs perfectly I just need to somehow connect the flask app with the website

inland oak
#

it is done with Nginx reverse proxy or with Gunicorn directly

#
  1. enable namecheap domain controlling pannel and make DNS records to point to your IP
#
  1. you are finished
edgy sable
#

so my website is running on apache2 on my server?

inland oak
#

as far as I know, apache2 can serve only html/css/js CSR sites
or perhaps in theory it could be used as reverse proxy

#

you will probably able to find instruction how to use Apache2 in the same way as Nginx as reverse proxy

#

to attach ssl certificates to your site

#

yeah, googled, you can

edgy sable
#

because i know someone where his sites run on apache2 and there run his apis and that confuses me a bit xD

inland oak
#

you can't run it with Apache2

#

Apache2 can be used only as secondary web server, which serves as reverse proxy pointing to your first web server

#

Apache2 can be used to server fully only for frontend CSR web sites, which have no backend coding (python or something), and only having html/css/js

edgy sable
#

that means my normal pages can run over apache2 but my api page must run over nignx ?

stark tartan
inland oak
#

you can use Apache2 in the same way as Nginx!

#

as reverse proxy!

#

they can be used interchangeably for the same purposes

#

am I explaining in a not right way perhaps? I'll leave it to others to explain then

edgy sable
#

no all good you explain well but I've only been working with apache2 for a few weeks and I've never heard of nginx so I'm confused

inland oak
# edgy sable because i know someone where his sites run on apache2 and there run his apis and...

https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-xvii-deployment-on-linux
how to run flask app in Gunicorn
with usage of Nginx as reverse proxy(with attaching ssl certificates) is explained here

This is the seventeenth installment of the Flask Mega-Tutorial series, in which I'm going to deploy Microblog to a Linux server.For your reference, below is a list of the articles in thisโ€ฆ

#

replace Nginx with Apache2 instructions, if you want to use Apache2

#

they are interchangable

edgy sable
#

ok thanks for the help i will have a look at it

pine torrent
#

I want resources for django

native tide
#

Is it possible to use async views with django?

balmy sparrow
#

I'm trying to use django-pandas on a django project, in which I convert models into dataframes to build tables, etc. Whenever I make a dataframe, im able to send it to a template without issue with .to_html(). It's whenever I try to take that dataframe and use the groupby, i get an error: '<' not supported between instances of 'Model' and 'Model'.

#works
 
class_five_df = pd.DataFrame(index=('unit',), columns('unit','equipment','ammo','base','assault','sustain'))
#
# some code that appends rows to the dataframe
#
class_five_df = class_five_df.dropna()
class_five_df = class_five_df.to_html()


# doesn't work
 
class_five_df = pd.DataFrame(index=('unit',), columns('unit','equipment','ammo','base','assault','sustain'))
#
# some code that appends rows to the dataframe
#
class_five_df = class_five_df.dropna()
class_five_df = class_five_df.groupby(['unit'])['base'].sum()
class_five_df = class_five_df.to_html()

Does anyone know what this error is trying to tell me that I'm not understanding? I'm not certain how its different than any of the other examples around the web.

inland oak
#

Django certainly supports async

#

At least 3.2 version

native tide
#

Are there any docs for it?

inland oak
#

Yeah, official docs have it

native tide
#

Ohh Okay

#

Thanks :)

slow gazelle
#

any idea with the error?

#

The included URLconf '<module 'pages.urls' from 'C:\Users\Aaron Joshua\Desktop\py\django-brad\pages\urls.py'>' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import.

obtuse trout
#

the given path '/' is not right

#

can you show me your btre/urls.py ?

slow gazelle
obtuse trout
#

ya

#

leave a blank instead of /

obtuse trout
slow gazelle
#

still the same

#

python manage.py runserver is the command for running right?

obtuse trout
#
path('', views.index, name='index'),
slow gazelle
obtuse trout
#

urlpatterns*

slow gazelle
#

Thanks a lot dude.

obtuse trout
#

no problem ๐Ÿ‘

runic sparrow
#

Does anyone have any experience with Flask / Gunicorn / Nginx, and load balancing? My web page is getting 60k requests/minute at times, and CPU and RAM never exceed 40% usage, but performance gets seriously degraded (3000ms response time)

dusk portal
#

TypeError: expected string or bytes-like object

#
def AddTodo(request):
    current_time=timezone.now().year
    data=request.POST.get('text')
    getch=Todo.objects.create(added_date=current_time,text=data)
    getch.save()
    return HttpResponseRedirect("/")```
#
path('addtodo',views.AddTodo,name='AddTodo'),```
#
class Todo(models.Model):
    text =  models.CharField(max_length=100)
    added_date= models.DateField(datetime.utcnow)

    def __str__(self):
        return self.text

    class Meta():
        verbose_name_plural='Todoes'```
#
{% extends "app1/base.html" %}

{% load static %}
{%block title%}TODO INDEX {% endblock %}
{% block body %}

<form action="{% url 'app1:AddTodo' %}" method="POST">
    {% csrf_token %}
    <input type="text" id="text" name="text">ADD TODO
    <button type="submit">Submit</button>
</form>
{% endblock %}```
edgy sable
#

i need help

#
application.secret_key = 'Add your secret key'```
#

do i have to enter a random at secret token

dusk portal
#

from FlaskApp import app as application what is this

#

application.secret_key = 'Add your secret key'
yeah any ur choice

#

but dont share it

#

@edgy sable

edgy sable
#

ok thanks for the info

dusk portal
#

^^ plz help

edgy sable
#

when i tried to start my flask website

pliant pewter
#
DigitalOcean

Output of systemctl status apache2.service Job for apache2.service failed because the control process exited with error code. See 'systemctl status apache2.service' and 'journalctl -xe' for details. root@essayszone:~# systemctl status apache2.service

slow gazelle
#

do you always use rest_framework with django?

edgy sable
#

systemctl status apache2.service

#

have entered the but does not come the error

dusk portal
#

I want guidance
Any django exp dev

#

I want a full roadmap and have some questions

#

If anybody arises plz ping me

#

If u have a good in django then only

edgy sable
#

this is the error

#

Invalid command 'WSGIScriptAlias', perhaps misspelled or defined by a module not included in the server configuration

ivory bolt
ivory bolt
dusk portal
ivory bolt
#

im serious

waxen lion
#

Anyone with experience in using python ap scheduler ?

slow gazelle
#

correct me if i'm wrong but based on my observation, its better to use django rest_framework with you use frontend frameworks like react, and plain django if you're using django view template

surreal portal
#

Although every single Django+React tut I've seen so far implemented React within Django. But that's mostly to avoid CORS issues.

#

By that, they build their frontend with React, then package it in Django's templates so it can be served by Django on the same host + same port

#

But imo if you do microservices, it's best to keep the front and the back as separate as possible

west peak
#

Hi guys i want to deploy my django project but a don't have idea of what if the best service for to that

#

can you help me please?

surreal portal
#

Heroku allows free hosting for POCs

west peak
#

Yes, is the most mentioned when i search for deploying

slow gazelle
#

just connect your github to heroku so when you push something in your repo, it will automatically update and deploy your website

west peak
#

It's my first time deploying a django project that's why the question

surreal portal
west peak
#

I'll try with it in heroku

#

Thanks guys

surreal portal
#

The other services are Linux VMs that you have to pay monthly

#

Anyway I have a question with Django models

#

When you have a field

#

Can you use the content of that field to fill another one by default?

west peak
surreal portal
#

Let's say you have an email field. I wanna extract the name of the email to put it in an username field

west peak
#

what is the model name of email?

surreal portal
#

email = models.EmailField(_("email address"), unique=True)

west peak
#

because you can use your id of that model and reference into username

surreal portal
#

Let's say I have johndoe@example.com. I want to set username to johndoe

glass sedge
#

email.split('@')[0]

surreal portal
glass sedge
#

looks like it yes, i havent used that django models enough to know if the outside part is correct

#

you might run into issues if its possible to have an empty or invalid email though

surreal portal
#
    username = models.CharField(max_length=30, default=generate_username(email, 30))
  File "/app/users/models.py", line 11, in generate_username
    username = "_".join(re.search(r"^(.+)@", email).group(1).split("."))
  File "/usr/local/lib/python3.9/re.py", line 201, in search
    return _compile(pattern, flags).search(string)
TypeError: expected string or bytes-like object

Trying to run a migration and it looks like it doesn't work

glass sedge
#

whats your generate_username code?

surreal portal
#
def generate_username(email, max_length):
    username = "_".join(re.search(r"^(.+)@", email).group(1).split("."))
    return username[:max_length]
glass sedge
#

this will do the same job

def generate_username(email, max_length):
    if not email:
        return None
    return email.split('@')[0].split('.')[0][:max_length]
#

but mainly you need to check if email is a string, if str is a shortcut check

surreal portal
#

I think ats are forbidden when you write emails, outside of the name@domain part

#

AttributeError: 'EmailField' object has no attribute 'split' you probably need a .data somewhere

glass sedge
#

ah i see, probably the first line of the function to get the string value of email

primal thorn
#

i cannot get the django-filters package to work, this is my filters.py ```python
from .models import PastExam
import django_filters

class PastExamFilter(django_filters.FilterSet):
class Meta:
model = PastExam
fields = ['category', 'subject', 'year', 'season', 'zone', ]

this is my view
```python
def yearly(request):
    form = PastPaperSelectForm()
    pastExams = PastExam.objects.all()
    myFilter = PastExamFilter(request.GET, queryset =pastExams )
    pastExams = myFilter.qs
    
    

    context = {
        'title': 'Yearly Past Papers', 
        'form': form,
        'myFilter': myFilter,
        'pastExams': pastExams,
        
    }
    return render(request, 'Yearly/home.html', context)

and this is my template

                        <form method="post">
                            {% csrf_token %}
                            {{myFilter.form}}

                            <input type="submit" value="Submit" />
                        </form>      

    {% for result in pastExams  %}
      {% comment %} <th scope="row">{{result.code}}</th> {% endcomment %}
      <td>{{result.subject}}</td>
      <td>{{result.year}}</td>
      <td>{{result.season}}</td>
      <td>{{result.paper_no}}</td>
      <td>{{result.zone}}</td>
      <td><a href="{{result.question_file.url}}" target="_blank" class="ml-2">Question Paper</a></td>
      <td><a href="{{result.answer_file.url}}" target="_blank" class="ml-2">Answer Paper</a></td>

        </tr>

    {% endfor %}
dark gull
rain delta
#

hello , this is my vscode file structure

#

in the src attribute i want to specify the path of the last file that is lordkrishna.jpg , how can i do that

#

plesae help

#

i learned that for folder in root we have to use a '.' and for root folder ".." , please help

coarse haven
#

.. is go up one folder in this case root main folder

#

then u go back into the folder you were in, the lecture 1 folder

#

but theres no lord krisha in there

#

u have two of those jpgs so idk which you want, but either do ../lordkrishna or do ./newimages/lordkrishna

rain delta
#

i want the outside one

opaque rivet
surreal portal
opaque rivet
dusk portal
opaque rivet
dusk portal
#

pretty sure the error is not in my code it's a db problem

#

tried many things too

#

@opaque rivet

#
class Contact(models.Model):
    name=models.CharField(max_length=50)
    email=models.EmailField(default='ahsuhg@gmail.com')
    phone=models.CharField(max_length=50)
    message=models.TextField()```
#

like changing email to Emailfield

#

and by adding default

opaque rivet
dusk portal
#

entry.save()

#

in my views

#

ig the error is done by me in the views or models

#

im not sure

opaque rivet
#

Sure... But read the error. It tells you exactly what's wrong. Do you understand what this line is telling you: NOT NULL constraint failed: app1_contact.message?

dusk portal
#

yeah

opaque rivet
#

so what is it telling you?

dusk portal
#

this tells app1_contact.message cannot be null ig

#

entry.save()

#

i should pass

#

anything inside this

#

๐Ÿคฏ

opaque rivet
# dusk portal this tells app1_contact.message cannot be null ig

Nice. Exactly, the model is expecting that message is not null. So implicitly there's a null=False there.
You said you added a default to email, etc. That's not related to the error so you wouldn't see any improvements there.

entry.save() is just saving the object. But that object still has an empty message field.

So instead you have to ensure the message field isn't empty:
entry = Contact(name="foo", email="bar", phone="foobar", message="foo-bar")

prisma canopy
#

I have a doubt about web development. like we have a site at which we work, so i want to code a thing like that if my input on name box is X then it should fill adress box number box itself. How can I make it do? What I have to learn to do this?

prisma canopy
#

should I explain you in more detail?

#

yeah, so i got a image from google

opaque rivet
#

You can, but for the user to see the address box fill the page will have to reload.

prisma canopy
#

like if i put the vehicle no, it should autofill the name and the driver name

dusk portal
prisma canopy
#

@dusk portal ๐Ÿ˜’

dusk portal
#

instead of py entry=Contact(name=name,email=email,phone=phone,message=message)

prisma canopy
#

karle block

#

karle maje

opaque rivet
prisma canopy
prisma canopy
#

could you help with thiws?

opaque rivet
#

I would use JS personally

opaque rivet
#

apart from that it's just simple form processing

prisma canopy
prisma canopy
dusk portal
#

can i?

opaque rivet
#

try it

dusk portal
#

so it should work aswell

prisma canopy
#

@opaque rivet my simple meaning is just to automate

opaque rivet
#

that requires JS... unless you want to make it janky and want the user to submit the form after inputting their name, reloading their page, then rendering a new page... giving them a worse experience

dusk portal
#

ok it;s not working

#

@opaque rivet

#
class Contact(models.Model):
    name=models.CharField(max_length=50)
    email=models.CharField(max_length=50,null=True)
    phone=models.CharField(max_length=50)
    message=models.TextField()

    def __str__(self):
        return self.email

#
def contact(request):
    if request.method=='POST':
        name=request.POST.get('name')
        email=request.POST.get('email')
        phone=request.POST.get('phone')
        message=request.POST.get('message')
        entry=Contact(name=name,email=email,phone=phone,message=message)
        print(message)
        entry.save()
    return render(request,'app1/contact.html')```
opaque rivet
#

why did you set null=True on the email field?

#

you literally told me what the error was 5mins ago

dusk portal
#

why it cant be null my question is @opaque rivet

#

cez it's in str method

#

that's why?

prisma canopy
#

dumb

#

yeah?

opaque rivet
#

why do you think it's the email field? Read the error again. What field do you think is causing the error?

#

It's the message field

dusk portal
#

so why the message cant be null

#

why

#

it's not making sense

#

cez it also not show str

opaque rivet
dusk portal
#

why msg cant be null

#

message**

opaque rivet
#

why? I'm not sure. Maybe there's an implicit null=False or it covers it in the docs.
But you know what the error is if you inspect the error. So make sure that you pass a valid message to your table

dusk portal
#

omg saw something like this

#

1st time

prisma canopy
#

๐Ÿ˜‚

dusk portal
prisma canopy
dusk portal
#

ok '

#

hey r u free i want some suggestion's @opaque rivet

ivory bolt
frosty halo
#

Hey All,
i have a form and i want to make a field that add multiple value at once (keywords) any clue to ho we do this ?

nimble radish
#

Anyone get unsolved references like this when using ForeignKeys on Django? PyCharm Professional.

surreal portal
#

I wanted to ask about authentication and security. Is a JWT token from a DRF app really the way to go when you have Django and the frontend running on different origins?

#

Because all the tuts I've seen so far stored the JWT in the local storage

#

Which, afaik, isn't the right thing to do?

#

But then idk how you can store it in a session cookie

modest bough
#

Hello all, I'm creating a web application with Django. I'm allowing users to create a test schedule (a model object) then add individual tests to it (another model object). I'm trying to decide the best way to do this in terms of HTML. Ideally, on the Test Schedule create page, the user would select an individual test type from a drop-down, and have the needed fields appear on the page.
Would like to use Django Forms for the individual Test creation form (and have made several forms for this purpose), but can't think how to display the required fields to the user because the web page/View doesn't know the type of form before-hand.

Ideal 'flow' would look something like:
User -> Create Test Schedule page -> Add Test -> choose type from drop down -> fill in form fields -> press submit -> add test to the test schedule -> Add Test [ * n ]

quick cargo
#

but yeah session cookies on multiple origins is basically the most awful experience ever and changes between browser so some token based auth is the way to go

surreal portal
quick cargo
#

but it doesnt need to be JWT if you dont need the storage on the client side just a method of showing who's who

opaque rivet
surreal portal
opaque rivet
#

Either way it's stored on the clientside, you could get a JS script to do the store the token as a cookie, or you could store the cookie from the server-side with Set-Cookie headers in the response.

surreal portal
#

I'd like to see a good example of fullstack project where the frontend is entirely separated from Django's REST application, with authentication and all

opaque rivet
#

They usually are

#

Django serves .html page with bundled JS which hydrates the page

#

On each request there's an identifiable token in the Authorization header, with Django just acting as an API returning data

quick cargo
#

can you do it with multiple origins? yes, is it worth the constant hassle? fuck no

opaque rivet
#

won't JWTs have the same problem though?

quick cargo
#

that depends on how you transfer the JWT

#

the JWT is just a base64 string

#

you can send that however

#

and that can be sent however from the client side rather than via the browser's cookie storage setup.

opaque rivet
#

whether you send it client-side (fetch api) or retrieve it from cookies, where is the hassle coming from? I don't really see the difference, both will still be enforced by CORS if they're from different origins

quick cargo
#

because Cookies have their own origin policy

#

so the server cant (reliably) set a cookie for the client

#

that would come purely down to the client to set itself

#

which yes, the client save that itself and load it again when it needs it

#

but for the actually client <-> server handling cookies dont work well with multiple origins

#

/ at all if they're diffrent domains

#

or on localhost

opaque rivet
# quick cargo or on localhost

oh yeah... because servers can only see the cookies if they're on the same origin... I forgot that cookies can have a different domain

#

so how would you transfer JWTs? As query params?

quick cargo
#

Generally we just stick it via headers

#

not for any major reason other than it keeps the urls from being obnoxiously long, but generally we dont use JWT much

opaque rivet
#

and storing them?

quick cargo
#

mostly Oauth2

#

tokens are just handled by the client

opaque rivet
#

oh, so never stored?

quick cargo
#

e.g. JS just sets and loads them

#

if it's needed to be stored

#

but generally long term storage JWT goes against what i think alot of people consider the 'Norm' for the setup because you cant revoke single tokens short of changing the secret

#

hence we normally roll with Oauth2* and any info is loaded server side

naive rock
#

Would it be bad to put time.sleep inside an async function?

naive rock
#

What does it mean aiohttp.client_exceptions.ClientOSError: [WinError 121] The semaphore timeout period has expired I'm using aiohttp and asyncio to make async requests.
Upon failure, it retries, I dont get this error when I have time.sleep set to 15 seconds, but it happens when time.sleep is set to less than 5 seconds.

naive rock
# naive rock What does it mean `aiohttp.client_exceptions.ClientOSError: [WinError 121] The s...
velvet yew
#

I'm making a simple bidding/auction system in Django as a practice project, anyone (preferably someone with JS skills) wanna join?

dusk portal
#

i want to debug this error can anyone explain me this error

inland oak
# surreal portal So it's entirely up to the frontend to host the accesskey you can request from t...

@quick cargo
Would not be it with good backend, entirely unnoticeable for frontend?
I mean... if backend would set cookie in httpOnly mode. Front end would be entirely clueless about how authorization goes between different microservices, because its javascript can't access the token. Frontend would only know to use login request once.
And at the same time clientside would be authorized automatically with this sticky cookie containing JWT inside

inland oak
#

at least that's possible if you create JWT on your own with PyJWT

#

I store like 6 different parameters about the user in my token at the moment

#

no need to change secret key in order to revoke then, make your own conditions.

dark gull
wooden ruin
inland oak
# wooden ruin wdym by more information? also where's a good place to store tokens client-side?...

JWT token is made from three parts
{
Some system info, when it is expiring and e.t.c.
},
{
Your own stuff you can put in.
Dictionary of jsonified information can be put here
You can put literally any data that you don't mine to be read by user though

the basic minimum, to have User ID in your database here
other user fields can be added too though
}
{
Signature against data tampering, verifying it is made with your secret code.
}

First two sections can be read by anyone, as it is encoded by just transport protocol base64 (no security)
When you decode JWT token, you verify that signature matches the hash of data basically, that this JWT was made with your secret key

inland oak
#

plus you remove responsibility from frotnend person to deal with it, it will be entirely unseen to him

#

I consider my security should be made in the first place against frontend people ๐Ÿ˜‰

#

So whatever mis usage would be done, it would not hurt my services

#

Hackers can do anything frontend framework does basically, so protection should be according.

#

In the worst case of them getting full access to the client browser, they should be able to hurt one user only

dark gull
primal thorn
#

how do i add a link from my user's account to their profile, for eg i want at the botton of every 'user' table to be a link to their profile in the admin panel

icy spade
#

not sure if this is the right place, but has anyone seen a flask/gunicorn workload suddenly start crash-looping from memory limitations as a result of a K8s/nginx upgrade?

#

same pipeline is fine on DEV, but severe memory leaks on app startup in TEST. been wracking my brain a bit over it all day. if anyone has any ideas beyond the obvious stuff that you can safely assume i've tried, please tag me!

ivory bolt
primal thorn
surreal portal
inland oak
#

or more like... it is a flaw of fully CSR frontend usage

#

trying to find some ideas how to protect my API end points from unauthorized usage now%

#

what if they are meant to be used without prior authorization by frontend?

#

The only idea I have for now is using at least initially SSRed frontned

#

since in this option I will be able to restrict API usage to specific allowed server ip

cerulean badge
#

why can't we just use async functions but need something like celery?

primal thorn
cerulean badge
primal thorn
cerulean badge
#

pass required=False

primal thorn
cerulean badge
#

i never used that package so donno

#

try passing null=True and blank=True if you have model form

primal thorn
cerulean badge
#

ok

#

why can't we just use async functions but need something like celery?

primal thorn
surreal portal
#

I have a question with Django, in production, is the main server enough or do I have to use an alternative like Gunicorn

inland oak
#

of course it is not enough

#

Gunicorn as minimum!

surreal portal
#

I completely neglected that aspect when I was deploying a fullstack app

#

So, suppose you have a frontend and a backend running on different servers

#

That means I have to use Gunicorn + NGINX for the back

#

And NGINX for the front?

inland oak
#

will give you full set of problems for production

inland oak
#

you serve Python things with Gunicorn, you serve django static files with Nginx, while having Nginx in Reverse-proxy mode to redirect it to Gunicorn. Ssl certificates are attached to Nginx too.

surreal portal
#

Oh yeah I still need the admin panel available online

inland oak
surreal portal
inland oak
#

Uvicorn is for Async features

#

if you aren't using them, you don't need it

#

Async features require special async-friendly libraries

#

just adding async and await is not enough

surreal portal
#

Idt any part of my DRF app needs any asynchronous programming

inland oak
#

don't bother with it then

surreal portal
#

So i'll stick with WSGI for now

inland oak
#

it is just additional compliication for you then

#

yup

surreal portal
#

So if I moiunt both in NGINX, do I still need CORS specified?

#

I'm working with containers

#

Probably gonna need CORS for inner exchanges thonk

surreal portal
#
while !</dev/tcp/db/5432
  do sleep 1
done 

gunicorn --bind 0.0.0.0:8000 config.wsgi
#

Iirc, this command waits for postgres, then starts on gunicorn right?

#

Oh no wait lemme edit this

#

Looks like it can't find the config.wsgi lol

#

Despite being exposed

#
ERROR: for django-backend  Cannot start service backend: OCI runtime create failed: container_linux.go:380: starting container process caused: exec: "bash -c 'while !</dev/tcp/db/5432; do sleep 1; done; gunicorn --bind 0.0.0.0:8000 config.wsgi'": stat bash -c 'while !</dev/tcp/db/5432; do sleep 1; done; gunicorn --bind 0.0.0.0:8000 config.wsgi': no such file or directory: unknown
#

Oh nvm

#

actually no even after renaming it i can('t detect it

surreal portal
#

Ok no I have a problem with Docker

#

Img can't detect the files

#

WTF

#

When they are in the same directory

tall plaza
#

hi everyone

#

i have one problem related to django async view

#
@sync_to_async 
def  get_movies_async (): 
    print ( 'prepare to get the movies...' ) 
    time.sleep( 5 ) 
    qs  =  Movie.objects.all() 
    print ( qs ) 
    print ( 'got all the movies!' ) 

@sync_to_async 
def  get_stories_async (): 
    print ( 'prepare to get the stories...' ) 
    time.sleep( 5 ) 
    qs  =  Story.objects.all() 
    print ( qs ) 
    print ( 'got all the stories!' ) 


async  def  main_home_async ( request ): 
    start_time  =  time . time () 
    # task1 = asyncio.ensure_future(get_movies_async()) 
    # task2 = asyncio.ensure_future(get_stories_async()) 
    # await asyncio.wait([task1, task2]) 
    await  asyncio . gather ( get_movies_async (),  get_stories_async ()) 
    total  =  ( time . time () - start_time ) 
    print ( 'total: ' ,  total ) 
    return  HttpResponse ( 'async' )
#

this is the code where main_home_async will execute the two functions
get_movies_async

get_stories_async
asynchronously
as you can see there is in each function 5 seconds of halt
but it is taking around 10 seconds which is kind of synchronous task

#

this is the output which is taking aroud 10 seconds as synchronous functions are taking

prepare to get the movies...
<QuerySet [<Movie: Spiderman>]>
got all the movies!
prepare to get the stories...
<QuerySet [<Story: my first story>]>
got all the stories!
total:  10.02943205833435```
#

it should be completed before the 10 seconds i guess

surreal portal
#

Maybe I should change the main image

#

Idk why for some reason the scripts are unusuable

#

I have no idea why it worked using a shell script

#

But not the command itself

opaque rivet
#

say you had a postgres container separate to your django backend container, and your db settings were:

DATABASES = {
}
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'postgres',
        'USER': 'postgres',
        'PASSWORD': 'postgres',
        'HOST': 'db',
        'PORT': 5432,
    }

How is the django backend able to communicate with the postgres container? Because the service is not running within its container. I don't understand how that happens?
https://docs.docker.com/samples/django/

Docker Documentation

Getting started with Docker Compose and Django

surreal portal
#

Meaning that instead of running a string of commands I defined that:

#!/bin/bash

# Wait for db
echo "Waiting for db.."
if [ "$DATABASE" = "postgis" ]
then
    echo "Waiting for postgis..."

    while ! nc -z $SQL_HOST $SQL_PORT; do
      sleep 1
    done

    echo "Postgis started"
fi

# Runs the server
echo "Running Django server with gunicorn"
gunicorn --bind 0.0.0.0:8000 control.wsgi
opaque rivet
#

ouch idk, I'm brand new to docker

surreal portal
#

gunicorn --bind 0.0.0.0:8000 control.wsgi doesn't work as a command since it can't detect control/ for some reason

#

manage.py is in the working directory btw

opaque rivet
#

are docker volumes relative or absolute paths?

surreal portal
#

Relative paths

carmine saffron
#

Hi,
im working on a project that work in microservice architecture and currently I have 2 services:

  1. auth service
  2. book service
    both services are develop in django and drf.
    and im trying to figure how do i call the auth service from my book service to check if the user is authenticated,
    what are the best practices to solve interconnection between 2 services?
remote cloud
opaque rivet
#

my docker-compose file has the volume:

volumes:
    - ./frontend:.

Does that mean that if any files change in the frontend directory my container will pickup on the changes? (I'm using this for hot-reloading of the frontend)

#

oh, turns out docker volumes have to be absolute

surreal portal
#

Also you don't need volumes in production

opaque rivet
#

@surreal portal what if the container somehow shuts down, from some sort of machine failure?

#

I'm just using it for development... I need hot reloading for my next.js frontend otherwise it's such a hassle

surreal portal
surreal portal
surreal portal
#

The only technique I know with JWTs are storing them in your browser (localStorage variable) then checking if it's the valid one

inland oak
# carmine saffron Hi, im working on a project that work in microservice architecture and currently...

You auth servers creates JWT token, which contains information about user and his level permission. You stick it to his cookie in httpOnly mode (it prevents it being accessed by javascript)
When the user requests other APIs, extract from his cookies this JWT token, decode/verify it with the same secret key, and get all his necessary permissions from it.
Beware. JWT token is encoded in just base64 + it has special signature that verifies the data was not tampered and was created with your secret key. Do not store any sensitive information in it.

regal fossil
#

I really feel difficult to design layout of website
Suggest me something which improve ky front-end skills.

surreal portal
#

@inland oak btw I wanted to ask if it was possible to run a Django container with NGINX and a frontend container like React on NGINX too

#

And both can communicate

inland oak
#

You do know, that react is client side

wicked mason
#

Hi all, I have a question on Django REST nested relationships, should I ask such a question here or in the help channels?

surreal portal
#

I have a backend running on Django + NGINX that communicates with a CRA build, hosted on another NGINX container

inland oak
#

Reacts loads and exists fully in user browser

surreal portal
#

The frontend sends credentials

inland oak
#

Can't answer in any short manner it

#

You need to provide more details what you wish to achieve

#

So I could say a more precise and shorter answer

surreal portal
calm plume
#

Using DRF

#

Like, https://forms.pydis.com is powered by React with the backend using FastAPI, and you could accomplish the same thing with DRF

#

Dunno about load balancer though, haven't messed with NGINX enough

calm plume
#

You can make it render server side

surreal portal
calm plume
surreal portal
#

@inland oak I'm trying to make the following structure

#

Here's a better structure

wicked mason
#

Anyone here that can help me with Django REST?

inland oak
#

I have a clue how to do that in the best way for django, I remember seeing a tutorial about it, going to try soon

inland oak
surreal portal
calm plume
#

That's the technique I'm referring to, although I prefer Next.js for server side

surreal portal
#
// src/api/client.ts
import axios from "axios";


export default axios.create({
    baseURL: process.env.BACKEND_URL,
    withCredentials: true
});

// src/api/forms.ts
import ApiClient from "./client";

export enum FormFeatures {
    Discoverable = "DISCOVERABLE",
    RequiresLogin = "REQUIRES_LOGIN",
    Open = "OPEN",
    CollectEmail = "COLLECT_EMAIL",
    DisableAntispam = "DISABLE_ANTISPAM",
    WebhookEnabled = "WEBHOOK_ENABLED"
}
#

So I suppose ApiClient = axios instance here

calm plume
#

I think so, but I haven't worked with Axios much

#

Actually, it might be this:

lavish prismBOT
#

src/api/client.ts lines 4 to 7

export default axios.create({
    baseURL: process.env.BACKEND_URL,
    withCredentials: true
});```
calm plume
#

Since it's exported as default

#

It's possible that ApiClient was simply used for clarity

carmine saffron
inland oak
#

it should verify jwt token that it was produced with the same secret key as auth has. There is some encrypting/decrypting thing that will verify your jwt token by its signature

#

and extract all necessary information from it

inland oak
#

rendering my react with django ๐Ÿ˜‰

#

I will be able to achieve my goals

#

btw why do you wish fitting everything into one contaner?

#

it is usually done with multicontainerized structure with docker-compose

opaque rivet
#

@inland oak SSR for each page or SPA?

inland oak
#

it will make possible in one command building and running multiple containers connected with each other

inland oak
inland oak
#

in all other situations CSR, or CSR with pre render can work faster and better

calm plume
#

I prefer Next.js for anything SSR/SSG tbh

carmine saffron
# inland oak and extract all necessary information from it

ok.
you just shed some light on what im suppose to do ๐Ÿ˜„
so 2 more questions:

  1. if i have for instance 100 services, should each of them implement the encrypting/decrypting of jwt?
  2. this secret key, where do I store it so I could use in each service that I need to do an authentication ?
surreal portal
inland oak
#

you get more than one container

#

check with docker ps command

inland oak
dusk portal
#
{% extends "app1/base.html" %}

{% load static %}
{%block title%}TODO INDEX {% endblock title %}
{% block body %}

<div class="row mt-4">
    <div class="col">
        <h2>Add Item</h2>
    <form action="{% url 'app1:addtodo' %}" method="post" class="form-inline">
        {% csrf_token %}
          <input type="text" id="text" name="text" class="form-control mb-2 mr-sm-2" placeholder="type here...">
      <button type="submit" class="btn btn-primary mb-2">Submit</button>
    </form>
  </div>
</div>

<ul>
{%if data2 %}
{% for p1 in data2 %}
<li>{{p1.text}} </li>
<li>{{p1.added_date}}</li>
<a href="/deletetodo/{{p1.sno}}"><button>Delete</button></a>

{% endfor %}
</ul>

{% else %}
<p>No Todo Enjoy!!!</p>

{% endif %}
{% endblock body %}```
#

i can't load my {{p1.sno}}

primal thorn
#

how do i remove the firstname and lastname fields from the default user model(django)

dusk portal
#

idk why

#

it is not loading

dusk portal
primal thorn
dusk portal
#

ig admin panel ask for username and password

#

;-;

#

not this

primal thorn
dusk portal
radiant storm
#

How would you implement expiring link functionality. Let's say we have an image stored on our server. We want to generate a link to that resource that expires after some period.

#

If you know Django, how would you that in Django?

inland oak
#

it looks liks this is a real way to do that

surreal portal
#

What's done is a frontend Django app being installed

#

Then you define the entrypoints for React

#

Webpack builds and stores in a frontend folder

surreal portal
#

Each box = 1 container

#

@inland oak dotted lines = 1 container

inland oak
surreal portal
#

Adding a NGINX container between the two then?

#

One NGINX container will hold static files for both Django and react?

inland oak
#

first choice almost

surreal portal
#

so, englobing React in Django?

inland oak
#

React with its own Nginx

#

Django with Gunicorn would have its own Nginx

surreal portal
#

Oh I see

inland oak
#
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:
#

make container Nginx for django sharing static file with it

#

while Nginx will work as reverse proxy to Django

#

so, in this scheme 5555 port is entrance point to receive Django API and its static file with Nginx

#

static files served immideatly with Nginx, while API requests travel further from Nginx to Django

surreal portal
#

Oh I see

inland oak
#

nginx dockerfile

FROM nginx:1.19.0-alpine

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

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';
     }
  }

}
#

btw, I am probably having not the best CORS settings, feel free to correct them on your own

surreal portal
#

Somethign like that? (hexagons = docker volumes)

surreal portal
inland oak
#

trying to photoshop it

surreal portal
#

Really useful tool

#

If you're more on keyboard there's mermaid.JS

inland oak
#

can you copy yours scheme?

surreal portal
inland oak
#

button at the top right with airplane sign

#

it has exporting feature

surreal portal
#

Decided to take it on my personal account

primal thorn
#

how can i disaplay the amount of times my loop has looped through a table, for eg if my for loop is showing 9 records in my templates tables, i want to show a 9

surreal portal
#

From the diagram, NGINX exposes the backend to the frontend. The Python code is governed by gunicorn

inland oak
#

yup.

#

this scheme will ensure for API to serve the right static files if necessary

#

technically if you aren't needing static files

#

you need them only for Django admin? you can access your admin from 4000 port

surreal portal
inland oak
#

nah... you need nginx for API too

#

because your React API will be with ssl certificates

#

and it needs making requests to https API with certificates too

#

it is just easier to attach certificates with Nginx to Backend

#

technically you can attach certificates directly to Gunicorn

#

it will work too

#

but...

#

having back behind Nginx will give other advantages

#

like... there are some even simple Nginx based caching servers

#

I dunno) advantages will be)

surreal portal
#

So both nginx implementations will need ssl certificates?

inland oak
#

emm. your React Nginx will need ssl certififcates for sure

#

for backend you have a choice to apply them to Nginx backend or to Gunicorn backend

#

it would be more comfortable to apply them to nginx backend too

#

less problem to access your admin web site

surreal portal
#

For sure.

#

What I understand is that both services will need a certificate

inland oak
#

uh. yeah. that's because...

#

urgh, trying to solve how to use this interface

#

here we go

#

you either expose your API with different port
or host it in different domain
not sure, may be there are other options?

#

i mean, your React needs somehow accessing your API ๐Ÿ˜‰

#

and since react will be in user browser

#

API should be having some port to get access to it

surreal portal
#

Oh dw I see the trick

inland oak
#

may be there is some nice solution though

#

perhaps it is possible to expose API somehow with the same port as front

#

not sure how)

surreal portal
#

I didn't wanna make the frontend entirely dependent from the back.

inland oak
#

you know...

#

perhaps nginx can host

#

for / address one site

#

and for /api another site?

#

then they would be available nicely both from the same port

#

it needs to be checked

#

if that's possible

#

then probably frontend and back would be behind same nginx
or perhaps we can just add third nging to redirect between their two nginx ;b

#

a little bit too many nginxes

#

one nginx should be enough

#

if you will not find how to do that, or going to be lazy. Exposing back from different port will work too

inland oak
#

deleted

quick cargo
#

nginx can manage several domains

#

and several certs

#

just make add another server {} to the config

lavish hedge
#

Can someone explain to me why its not updating... this was working fine earlier today....

inland oak
quick cargo
#

yeah

inland oak
#

I found that it is possible for sure with
/first_path
/second_path

quick cargo
#

just add a new path route

inland oak
#

what if there will be route conflict

quick cargo
#

just make sure you put the /api first then the / so it matches the api first

#

by default routes are matched in the order they're set in the config

dusk portal
inland oak
#

all right

#

we need to change our scheme then

surreal portal
#

So both routes can coexist

quick cargo
#

yeah

surreal portal
#

As long as the origins are different?

inland oak
#

as long as different paths at least

#

domain can be the same

#

and user can be the same

dusk portal
#

hey friend , i have done till a intermediate lvl in django i can do many stuff but before i go to login authentication i have some problems , idk how to flash msg like if any1 fill contact form it should flash msg and in my todo app if anyone add's todo blank it show flash ,add some task ik it's in docs but idk that logic cant get it

#

for example let's take

#
def Home(request):
    data2=Todo.objects.all()
    return render(request,'app1/index.html',{'data2':data2})

def addtodo(request):
    current_year=datetime.now()
    data=request.POST.get('text')
    getch=Todo.objects.create(added_date=current_year,text=data)
    getch.save()
    return HttpResponseRedirect("/")

def deletetodo(request,question_id):
    delete=Todo.objects.get(id=question_id).delete()
    return HttpResponseRedirect("/")
inland oak
dusk portal
#

how can i add that ik that try , get_object_or_404

#

but idk to apply it here

#

;-;

quick cargo
#

this section doesnt make any sense

#

but other than that it looks alright

inland oak
#

what is not making sense, Django static files?

#

oh yeah

#

why would they be served to Gunicorn

#

ummm

#

because they are build in container with Gunicorn)

#

and just shared to container with Nginx)

#

inversed arrow

calm plume
#

So looking at that, the NGINX serves to React?

inland oak
#

yeah

calm plume
#

Makes sense

inland oak
#

@surreal portal woohoo. the scheme makes sense now

dusk portal
#

me at this moment: what's NGINX

calm plume
#

It's a load balancer and reverse proxy

inland oak
#

it can serve as regular web server too

calm plume
#

And also Ingress Controller iirc

surreal portal
#

Nvm I forgot to refresh

surreal portal
dusk portal
#

ohh

inland oak
#

load balancer is a thing to redirect between several web servers
for horizontal scaling of performance.

for example we can randomly reidrect to two instances of something. the average load of users would be twice less then

dusk portal
#

plz see up ^^ my msg 10-12 msg up i have doubt plz

inland oak
#

eh. here goes my evening.

#

I thought to watch some cartoon and at last getting myself distracted from programming every day all day allong

surreal portal
#

I can barely sleep with those advanced webdev techniques

inland oak
#

my books to get started in front end arrive

#

so, even more load then before%

surreal portal
#

Last time I used Flask-login for authenticated users

dusk portal
surreal portal
inland oak
#

i like for now being one army web dev too. Nice to grow skills

light cloak
#

Hello! Sorry if I'm interrupting. I have a quick question. I've been learning python for a month or two and recently started working through
Corey Schafer's Django tutorials on YouTube. I'm wondering if you guys would have any insight in to if this is a good avenue to go about
learning web-dev with Python? I've just finished his third video on templates and much of the code on show is taken from bootstrap or html code snippets that I don't really
understand. Is a better way of learning for me to just try and make my own thing and see where it gets me and looking up various html/css etc ideas as I go along, or is it
more beneficial to be walked through a complete project? ๐Ÿ™‚

inland oak
#

never understood watching videos

#

I learn with books and text tutorials

#

some people learn from videos though

#

I don't for sure which are you type of guy, I guess video learner?

inland oak
#

you can learn the rest of bits during the process)

light cloak
#

@inland oak I don't think necessarily video learner, just that this particular series was recommended all over reddit and I thought it might be a good idea to try it out. It seems like there is quite a lot of stuff to learn before I can make a site operational so I wasn't sure if it would be a good idea to get an overview with a guided project before doing my own thing or not

inland oak
#

in my opinion videos are a huge waste of time)

#

or read beginner book for Djangoers, it would be more beneficial to you, if you aren't video guy

light cloak
#

I have been following along but I think perhaps the official tutorial may be a better way to start since hopefully it will cover the absolute basics

inland oak
#

surely. and you can follow it with speed you like at 100%

light cloak
#

Do you think official tutorial -> Experimentation is the way to go?

inland oak
#

yup!

#

absolutely

#

it is in my opinion the best possible way ever

light cloak
#

I'll give it a shot then! I wonder also if you can check my understanding in that python/django is mostly used for setting up the framework of a website/ how it functions, and javascript is the main language used for making things look pretty/ design elements?

inland oak
light cloak
#

If you're making a website in django, can you include javascript code to make things look the way you like when it's done?

inland oak
#

python/django is mostly used for doing server side part of work

#

html/css is used to make things pretty

#

javascript is used to make stuff dynamic/smoothy at the client side part of the web site, so it could show dynamic stuff without re rendering whole web site from zero

inland oak
light cloak
inland oak
#

hmm, what does backend? ๐Ÿค” said backend developer.

#

mmm... it organizes any data you need before showing end results to user

calm plume
#

Backend (at the simplest level) basically consists of the database (the place to store data) and the API (the way to interact with that data)

light cloak
#

Okay interesting, so in the case of twitter for example, the backend would consist of lists of tweets written by users and ways for users to like/reply/ retweet etc

#

Do developers usually do either back end or front end and not usually both?

inland oak
#

they usually start with one part and trying to learn doing both parts

light cloak
#

Thank you for the explanations. Can I ask what you think a good starting web project would be/ what your initial ones were? ๐Ÿ™‚

inland oak
inland oak
calm plume
light cloak
#

Hardest part about starting different aspects of python for me is figuring out what interesting thing I could build with it ๐Ÿ˜„ It's hard!

inland oak
#

well, my first my own project with django which I tried to make is
making online database of game items for players)
too bad I did not finish it. One I will, one day I will. Not really a lot of free time I am having at the moment to continue it.

light cloak
calm plume
#

Yeah, I provided people with an iframe component that they could embed on their websites

light cloak
#

Thank you guys for your insight, it's helped a lot I think

#

Web dev is pretty daunting since it seems you have to know a lot of background info about a few different things

light cloak
#

It's not like just making a calculator or something

inland oak
#

so many languages and technologies to know
wondrous profession.

light cloak
#

Agreed - actually what inspired me to pick up python in the first place, I feel like it could never get boring, there's so much stuff to learn and problems to solve ๐Ÿ™‚ Thanks for your help!

dusk portal
#

ok stuck idk what to do now and from where

#

done this docs

#

made 1-2 apps

#

what next

calm plume
dusk portal
# calm plume What type of apps?

simple ,Todo app containing db models , contact page , django templating , as i have good exp in flask so i have done if loops and stuff and yes i practiced alot , now i wanted to move to sign up,sign in and co,mplex so docs are too lenghty after that ig i should not read now

#

and practiced so many times

#

i can do that stuff now within 30 mins

#

bet

#

1-2 issue's only nothng else ,

calm plume
#

With syntax highlighting and you can save your code

dusk portal
calm plume
#

Yeah, pretty much

#

You can make your own

dusk portal
#

lmao @calm plume

#

how can i make own code editor

#

im idiot

#

idk that much

calm plume
#

It wouldn't be too hard. Make an <input> field and make the font monospace with CSS

#

Or you could use codemirror

dusk portal
#

hey can u tell me how can i learn next cez bro docs after are too boring

#

@calm plume

calm plume
#

In Django?

#

Don't just try to read docs

dusk portal
#

there are so many

calm plume
#

Build real world applications that people can actually use

dusk portal
#

my kids will read ig

dusk portal
calm plume
#

Then try your best and you'll figure it out along the way

#

Google is your friend

dusk portal
#

annd bro @calm plume

#

im 16

#

how can i read that much

#

๐Ÿ˜ข

calm plume
#

You only need to read what you need

#

Building an application is the best way to learn imo

dusk portal
calm plume
dusk portal
#

too fast

#

and apply side by side in my project

#

thanks alot

#

love u

native tide
#

im not sure if this is in the theme of this chanel (if not i will post in the chanel it is the theme), i am working on a programm that gives you chanel stats that all fine but i need a bit help with the api, i am using googles youtube data api v3 and i cant get the stats of some chanels and i have no clue why or how i can fix it maybe someone can help me, in a help chanel i opened no one awnsered :sad: i rly hope someone can help me

native tide
#

like this should be the response if i enter a valid youtube user name: html { "kind": "youtube#channelListResponse", "etag": "R_zl83uUDFpjvbcf27L54MfmRr8", "pageInfo": { "totalResults": 1, "resultsPerPage": 5 }, "items": [ { "kind": "youtube#channel", "etag": "SZX06KQUwMK0TTjAKww39NaJoj0", "id": "UC-lHJZR3Gqxm24_Vd_AJ5Yw", "statistics": { "viewCount": "27467796238", "subscriberCount": "110000000", "hiddenSubscriberCount": false, "videoCount": "4358" } } ] }

#

but for most channels (my channel including) im geting this response: html { "kind": "youtube#channelListResponse", "etag": "RuuXzTIr0OoDqI4S0RU6n4FqKEM", "pageInfo": { "totalResults": 0, "resultsPerPage": 5 } }

#

to check if it works i used this api request (i used like i said the youtube data api v3): www.googleapis.com/youtube/v3/channels?part=statistics&key=<api key here>&forUsername=<username here>

grizzled verge
#

Hello! I need help in url_for Flask. I want to put a variable in my url_for. For example.
<a href="{{ url_for('index',name=(variable_name,location=variable_location)}}"></a>

I want to do is take the input name and location from the user as a variable and put it here. How can I do it?

solar epoch
native tide
#

How do you get the Accept-Encoding (br, gzip, deflate) from the browser via JavaScript without going through a server that can return that ?

modest osprey
#

Someone can help me with Web Scraping with Selenium?

stable coral
#

can someone help explain a bit of code in a Flask project I'm working on?

#

(i'm following tutorials to create the project)

#

i don't understand how render_template() comes after the if block

#

doesn't the webpage have to be rendered first in order for the code to check the login info?

noble spoke
#

When you go to /login thats what you get

#

Then when the user submits the form the if statement is truthy and so the user is redirected elsewhere if successful or a message is flashed at them

stable coral
#

I'm sorry, I don't understand @noble spoke

#

Could you go over what validate_on_submit() and render_template() do? maybe I don't understand them properly

noble spoke
#

Ok, so you have a route that accepts both get and post requests

#

Get so the user can fetch and see the form

#

Post to submit

#

form.validate_on_submit checks to see if the form was submitted with a post request

#

If is was, it validates it and moves on

#

When the user goes to /login, thats a GET request

#

The form is created but form.validate_on_submit fails because the form wasnt posted yet

#

So the code skips straight to render template

#

So the user can see the actual html

#

Ok?

stable coral
#

Oh

#

I think I get it

#

Wait so is login() constantly being run?

noble spoke
#

Not constantly, just twice if the user submits a valid form

#

When the user submits the form, form.validate_on_submit checks if its valid and if it is the body of the if statement is run

#

And the user is either redirected or flashed a message and the template is rerendered

stable coral
#

is it recursive?

#

when render_template() is run does it go through the whole function again until it gets to redirect() ?

noble spoke
#

Not recursive no, there is no call to itself and nothing redirects to it from within

#

The html is just rerendered

#

(with the kwargs passed through)

stable coral
#

I don't understand what causes login() to run, and how many times it runs

noble spoke
#

Best case scenario (the user doesnt fuck up the credentials) it runs twice

#
GET /login # renders the form in the first place
POST /login # with actual form data this time to be validated and verified
#

If this was recursive or had redirects to itself you would get errors

#

(probably)

#

You can see these in the console btw

stable coral
#

where is the second GET?

#

in my code

noble spoke
#

Sorry, my b, i dont think there is one actually

#

The form is just rerendered

#

You can double check in your console

#

Try to login with bad credentials

stable coral
#

ok

noble spoke
#

Yea ok there is no second get, the form is just rendered again

stable coral
#

it's in debug mode btw, idk if that changes anything

noble spoke
#

No i dont think it matters

stable coral
#

ok

#

thank you for the help @noble spoke

scenic vapor
#

I need to build a scheduler to automate payout to merchants every week. Should i have it in the same code-base as my backend or an entirely separate server?

#

Im concerned about the performance

ruby kelp
#

So I've been a python user for quite a while, but one thing that I have never built is like a web frontend, what libraries/frameworks would one recommend for building such a thing? I can hack myway through html and css to do the visual stuff, but when I want things to do_something(), what is a solid framework for this?

scenic vapor
#

flask, django

pliant nymph
#

nice timezone

wooden ruin
ocean notch
ruby kelp
#

thanks

rain delta
#

this is my code in html for accessing two image files

#

and above code is working perfectly fine

#

but this is not working

#

the first line of img tag

#

i am getting confused in using . and .. to acess the files ,

#

please help

primal thorn
#

whats the best way to remove the first and last name column in the default django user model

graceful flax
#

Hi, I'm looking to frame assignments for Backend developers in Django [Channels included] & postgres and needed some suggestions, is this the right channel to ask?

graceful flax
#

Umm?

inland oak
#

and what means [Channels included]

graceful flax
# inland oak what are frame assignments?

Oh okay, I'm looking to hire Backend developers for Junior Intern position and Associate position, for the junior position I know what task to frame as I'm expecting only basic CRUD operations and knows the REST Framework well

For the associate role need some suggestions, Channels included meant, I require the person to have knowledge of how websockets work, django channels here

paper briar
#

hey guys, im making a website of mine using django and was wondering if i could implement pysimpleguiweb in this site

#

im very new btw

lavish prismBOT
#

5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.

#

6. Do not post unapproved advertising.

#

4. Use English to the best of your ability. Be polite if someone speaks English imperfectly.

#

9. Do not offer or ask for paid work of any kind.

sturdy sapphire
#

it looks like you all was very clear

#

you can use local hiring or freelance sites @graceful flax

indigo vessel
#

is still books relevance in this fast pace world?

inland oak
#

the fastest

#

and most precise you can get in a short time

#

checking reviews should be still done though, not every book is the best

indigo vessel
indigo vessel
# inland oak not getting the question

what i mean is that many websites provides online tutorials (e.g w3school and etc) since we lived in a fast pace world, is books still an option to learn fast and understand it precisely?

indigo vessel
#

because in my defense.....

graceful flax
graceful flax
#

Alright cool thanks anyway

graceful flax
inland oak
#

tutorials are often... only touching the top of the thing

#

and all other interfactive things

indigo vessel
#

I am learning 3 subjects at the same time (Data struct and algo, web dev, and java (i know not python but i'll get in touch with it though)) and also i have life responsibility to deal with which steals my time studying and doing productivity

inland oak
#

some good ones, but it is difficult to find completely covering interactive online good thing

#

books are more often with excellent coverage on a subject

#

combining two methods is usually a good way too

#

small quick peek to online things, or getting started is often better in online things
main learning from books

#

also I believe that online courses became a subject of scamming tbh

indigo vessel
inland oak
#

believe or not... but I often see people who take online courses

#

they pay a lot of money

indigo vessel
inland oak
#

online courses make very... slimy addvertisements to themselves

#

and in the end people learn only small set of skills, without thinking out of the box

#

or just learning reaaaalllly slow

#

online courses look to me like a way to take money from beginning developers

#

they usually have money to waste for it

#

but the return from them is quite mediocre

#

may be there are good online courses, but that's my general opinion about them

indigo vessel
inland oak
#

may be that's more a thing to my country

#

perhaps you have it differently

indigo vessel
indigo vessel
inland oak
#

books are usually a faster way to go

indigo vessel
#

maybe i'll be double hustle for this one though

inland oak
#

I mean, I can read one book in just one-two days during weekends

#

or during evenings

#

online courses consume much greater time with lower return in my opinion

indigo vessel
#

i mean do you just read read?

#

or read then understand and read again until you get the point... like connecting the idea form one concept to another?

#

i read books but i get it slower because I am fomulating the connection of the topic and trying to connect its main connection to another concept

round swift
#

psycopg2.OperationalError: could not connect to server: Connection refused
Is the server running on host "localhost" (127.0.0.1) and accepting
TCP/IP connections on port 5432?

#

django.db.utils.OperationalError: could not connect to server: Connection refused
Is the server running on host "localhost" (127.0.0.1) and accepting
TCP/IP connections on port 5432?

#

I am getting this error after running heroku run python manage.py migrate

inland oak
# indigo vessel woah.... what strategies you implement on reading?

eh? I just read. I am a fast reader I guess, too many books read before.

I usually though... choose the right book to read in a right order
starting from covering basics in the topic, then going to a more advanced ones
and always choosing the most fun to read and with best reviews

#

usually I get the book about some topic when I feel the need to feel gaps in yet another field, which I encounter at my job

balmy sparrow
#

Iโ€™m looking for a good reference (intermediate level) Django project to study and learns some new concepts. Iโ€™ve found Oscar, but think thatโ€™s just a bit complex for me to follow and understand as of right now. Does anyone have some good recommendations?

opaque rivet
#

@inland oak if you don't mind me asking, whats your job title? Devops?

inland oak
#

wishing highly to learn Frontend, today I will start doing it. Going to get my Head First O'Reilly books for that.

opaque rivet
#

At what point did you think "ill apply to a job", after your first project?

#

@inland oak go for React :)

inland oak
inland oak
opaque rivet
#

Oh cool, thanks for letting me know! That's really valuable for me.

inland oak
#

I was told I could skip chapters 8,9,10,20,21,22 though

#

this was quite funny for me. it was like my first experience with web frameworks ever

#

I was accepted into company with the lowest possible standards though

#

all standards of quality were have to be quickly learned on my own and enforced by me later

#

giggles
I remember, when I started working there, I could not believe that my.... first ever experience in web dev... the entrance assignment...
...was made actually the main project to start backend with

#

thankfully I was able to refactorize later my past mistakes (and throwed away Flask too, Django is 20% cooler)

cunning crane
#

Hi! I have a question about django. I have created two projects with django, and one of the project include the folder (.idea) and the other one does not. I dont know the reason but would it be a problem in any kind?

inland oak
#

that's not really important, some nice settings could be saved there though

#

my vscode projects often get .vscode folder because of it

cunning crane
#

then it wont be a problem not to have that...

#

Thanks

dusk portal
#

can anyone explain me that django.contrib.auth import User see the ss and why did he added it to a ForeignKey (video is of Corey Schafer)

rain delta
#

well actually i also followed that tutorial

dusk portal
#

i followed docs

#

docs done now doing this

#

as idk django_auth

#

so im asking

rain delta
#

he added it to a foreign key because he is linking the post to users

#

and for that he is using the user as foreign key to link the post with the authors

rain delta
dusk portal
#

this module do what

rain delta
dusk portal
#

ohh

fallen birch
#

I'd like to put an base64 string into to source using jinja. the code looks like that: url('data:application/x-font-woff;charset=utf-8;base64,{{ read(src)|b64enc }}') format('woff') - within a macro. Jinja does replace some charackters in the resulting string (b&#39;) right after: base64, I guess that is = or something. How can I prevent jinja from doing that??

opaque rivet
# dusk portal ohh

Django provides default models. One of them is User which is a model with premade fields to store user information. It saves you from making your own...

dusk portal
#

๐Ÿคฏ

opaque rivet
#

?

#

who said User is a field

dusk portal
#

bro i saw that tutorial i dont found this User and from django.contrib.auth.models import user useful it's kinda same bro it is necessary while writing backend of the sign up or sign in page @opaque rivet

opaque rivet
#

no clue what that means

dusk portal
#

i mean to say that , is it necessary to use User module

#

for writing backend of sign up and sign in page?

#

@opaque rivet

opaque rivet
#

it's not necessary, but it helps, and it saves you from making your own model for users.

dusk portal
#
from django.shortcuts import render

posts=[
    {"title":"First Post",
    "Author" :"ARYAN"
    },
    {"title":"Second Post",
    "Author" :"CYPHER"
    }
]

# Create your views here.
def index(request):
    context = {'posts':posts}
    return render(request,'app1/index.html',context)

def about(request):
    return render(request,'app1/about.html')

``` this my code
#

and when im doing User.objects.all()

#

it's showing only admin

#

that's only issue

#

nothing else

#

got all other stuff

#

@opaque rivet

opaque rivet
#

How is User.objects.all() related to that code?

#

@dusk portal

native tide
dusk portal
#

do we have to do anything here

inland oak
#

My precious books have arrived about frontend
At last I am going to get started in it

dusk portal
#

best of luck @inland oak

opaque rivet
#

you showed a random, unrelated code snippet and asked something about User.objects.all() without relating why

dusk portal
#

User.objects.all() related at all to that code? there is nothing in my view called this

#

but as tutorial

#

i have it on my

#

models

opaque rivet
#

exactly, so what even is your question

dusk portal
#

``py

#
class Posts(models.Model):
    title=models.CharField(max_length=50)
    content=models.CharField(max_length=250)
    date_posted=models.DateTimeField(default=timezone.now)
    author=models.ForeignKey(User,on_delete=models.CASCADE)
    
    class Meta():
        verbose_name_plural='Posts'```
#

he's doing User.objects.all() and his

#

posts=[
{"title":"First Post",
"Author" :"ARYAN"
},
{"title":"Second Post",
"Author" :"CYPHER"
}
]

#

this is showing

#

author

opaque rivet
#

Ok, what is your question

dusk portal
#

but when im doing

#

wait i send a screen shot

#

i'll **

opaque rivet
#

still, that's not a question facepalm

#

I just ask because it makes 0 sense what you asked, so there's no point quoting it again

dusk portal
opaque rivet
#

Like, what are you trying to do??

#

User is a model

#

posts is just a list.

#

They are unrelated

dusk portal
#

hmm ik i have readed the docs

#

but in video

#

he have accessed through

#

this User

#

idk how

opaque rivet
#

User.objects.get(kwargs_here)

#

he's most likely saved entries in the database

dusk portal
#

ohh

inland oak
#

I just realized how much horrible fate I escaped 2 years ago.

During my bachelor's diploma I tried to work with teacher, who worked with php CMS bitrix.

What a horrible fate I skipped, when I chose that I don't like this CMS at all.

opaque rivet
# dusk portal ohh

but next time, please articulate your question... it might help you find the solution to your problem, and it will reduce headaches to others trying to understand what the hell the issue is