#web-development
2 messages ยท Page 167 of 1
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
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
your dedicated server is some Linux server
Ubuntu
- getting ssl certificates
a) for free with certbot
b) for not free from https://www.namecheap.com/ (5 dollars per year, or something like that)
Register domain names at Namecheap. Buy cheap domain names and enjoy 24/7 support. With over 13 million domains under management, you know youโre in good hands.
re deploy your app with enabled https
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')
}
- turn on where your domain controlling pannel
and make necessary DNS records, A records and somthing? to point to your IP
i bought my domain from namecheap and the ssl certificate runs through cloudflare
- ???
- Proffit!
oh I regulated my domain through namecheap too)
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 ||
anyway, read instructions like that
https://www.namecheap.com/support/knowledgebase/article.aspx/9837/46/how-to-connect-a-domain-to-a-server-or-hosting/
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
- run your flask app with attached ssl certificate
it is done with Nginx reverse proxy or with Gunicorn directly
- enable namecheap domain controlling pannel and make DNS records to point to your IP
- you are finished
so my website is running on apache2 on my server?
I am 80% sure your web site can't be running with apache2
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
because i know someone where his sites run on apache2 and there run his apis and that confuses me a bit xD
you have flask. it is backend, it should be run with python web servers, like Gunicorn, Hypercorn and e.t.c.
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
that means my normal pages can run over apache2 but my api page must run over nignx ?
please answer my question at #help-cookie message
groans
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
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
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
replace Nginx with Apache2 instructions, if you want to use Apache2
they are interchangable
ok thanks for the help i will have a look at it
I want resources for django
Is it possible to use async views with django?
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.
It should be.
Django certainly supports async
At least 3.2 version
Are there any docs for it?
Yeah, official docs have it
any idea with the error?
here is the views.py file
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.
https://github.com/bradtraversy/btre_project here is the tutorial I'm following
here
path('', views.index, name='index'),
urlpatterns*
ye it works now, i though you can name it any
Thanks a lot dude.
no problem ๐
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)
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 %}```
i need help
application.secret_key = 'Add your secret key'```
do i have to enter a random at secret token
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
ok thanks for the info
^^ plz help
@edgy sable this could possibly help https://www.digitalocean.com/community/questions/job-for-apache2-service-failed-because-the-control-process-exited-with-error-code
do you always use rest_framework with django?
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
this is the error
Invalid command 'WSGIScriptAlias', perhaps misspelled or defined by a module not included in the server configuration
add '/' after addtodo
who r u talking about?
Lmao xD
im serious
Anyone with experience in using python ap scheduler ?
anyone
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
REST APIs are used when you do microservices so yeah.
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
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?
Have you tried Heroku?
Heroku allows free hosting for POCs
heroku is easy
Yes, is the most mentioned when i search for deploying
just connect your github to heroku so when you push something in your repo, it will automatically update and deploy your website
It's my first time deploying a django project that's why the question
look for a tutorial where you can deploy Django with Heroku on google
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?
But if i whant for my own domain i need to pay in heroku so it isn't a problem
Let's say you have an email field. I wanna extract the name of the email to put it in an username field
what is the model name of email?
email = models.EmailField(_("email address"), unique=True)
because you can use your id of that model and reference into username
Let's say I have johndoe@example.com. I want to set username to johndoe
email.split('@')[0]
username = models.CharField(max_length=30, default=email.split('@')[0])
Like so?
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
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
whats your generate_username code?
def generate_username(email, max_length):
username = "_".join(re.search(r"^(.+)@", email).group(1).split("."))
return username[:max_length]
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
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
ah i see, probably the first line of the function to get the string value of email
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 %}
I would like some suggestions on: https://codinginventor.github.io/Endangered-Elephants/
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
.. 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
i want the outside one
When you specify the default kwarg, that is the value that the field will take if nothing is passed, i.e. it's null.
Instead, override your model's save method to parse the email, so that when your object is saved the email@provider.com will be parsed and assigned to the username.
Is there a save method we can override in models?
Yeah, models have a save method:
class myModel(db.Model):
# fields...
def save(self):
self.username = self.email.split("@")[0]
super().save()
Thank you!
do you understand why you have a bug here?
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
Read the error, what do you think it means? Explain to me your thinking.
Also most errors are due to errors in our code, open source software is highly tested and usually the errors don't arise there...
The above exception (NOT NULL constraint failed: app1_contact.message) was the direct cause of the following exception:
entry.save()
in my views
ig the error is done by me in the views or models
im not sure
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?
yeah
so what is it telling you?
this tells app1_contact.message cannot be null ig
entry.save()
i should pass
anything inside this
๐คฏ
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")
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?
sounds like a job for JS
can't a i do with python?
should I explain you in more detail?
yeah, so i got a image from google
You can, but for the user to see the address box fill the page will have to reload.
ohh so should i write py entry = Contact(name="foo", email="bar", phone="foobar", message="foo-bar")
@dusk portal ๐
instead of py entry=Contact(name=name,email=email,phone=phone,message=message)
no, that's just an example.
If you understand what the error is telling you then you can fix it...
The issue is that message is null. Do print(message) to see what data you're passing
i have had suffered from that error, but when i replaced msg to message in lhs, it was fixed
@opaque rivet
could you help with thiws?
I would use JS personally
dude it's not flask
apart from that it's just simple form processing
i didn't asked to you okay
ah i just want a module that would help, like tkinter or anything
so in this logic , if i want the message to be passed null also i can do null =True
can i?
try it
so it should work aswell
@opaque rivet my simple meaning is just to automate
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
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')```
why did you set null=True on the email field?
you literally told me what the error was 5mins ago
why it cant be null my question is @opaque rivet
cez it's in str method
that's why?
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
so why the message cant be null

why
it's not making sense
cez it also not show str
the __str__ dunder method has nothing to do with it
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
error's aren't common some error's are only common and they are basic, aren't they?
nice english but you can tell that in 7-8 words
You need any help setting that up
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 ?
Anyone get unsolved references like this when using ForeignKeys on Django? PyCharm Professional.
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
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 ]
We use JWT or Oauth2 for that, depending on the setup if you dont want to have short TTL tokens then oauth2 might be the way to go
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
I'm gone with the DRF SimpleJWT extension.
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
You can store it as a cookie in the Set-Cookie header of your server's response
So it's entirely up to the frontend to host the accesskey you can request from the back after a login attempt?
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.
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
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
cant do that with multiple origins easily or reliably across browsers is the issue
can you do it with multiple origins? yes, is it worth the constant hassle? fuck no
won't JWTs have the same problem though?
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.
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
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
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?
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
and storing them?
oh, so never stored?
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
Would it be bad to put time.sleep inside an async function?
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.
I'm making a simple bidding/auction system in Django as a practice project, anyone (preferably someone with JS skills) wanna join?
i want to debug this error can anyone explain me this error
@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
You can just store more information in JWT
and revoke by additional your own rules
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.
I just build two webpages yesterday and would like to share with all of you:
- https://codinginventor.github.io/Tourist/
- https://codinginventor.github.io/Endangered-Elephants/
I also have a doubt regarding both the pages. I have got tables in both of them but their border is some-what different. Will it be possible to have borders fully good-ly?
wdym by more information? also where's a good place to store tokens client-side? i've heard localstorage/sessionstorage can be insecure at times
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
The best place is cookie, with httpOnly flag
it can't be accessed with javascript. So basically token will be accessed with backend only.
Hackers could still use it, but they will have much harder time since it would be harder to find and to know with automated javascript scripts
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
I just build two webpages yesterday and would like to share with all of you:
- https://codinginventor.github.io/Tourist/
- https://codinginventor.github.io/Endangered-Elephants/
I also have a doubt regarding both the pages. I have got tables in both of them but their border is some-what different. Will it be possible to have borders fully good-ly?
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
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!
if you're talking about django, it's simple. In your URLs, there should be a name for the user profile detail view, so use the {% url "user_profile" %} or whatever the name of the url is, and insert that tag in your <a href="url tag goes here"></a>
i need this but for my admin panel
Interesting. Also isn't that a microservices flaw?
mm yeah. it is microservice flaw.
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
why can't we just use async functions but need something like celery?
in django?
yes
pass required=False
im using the smart_select package and when i try to make it a char fields my dropdown becomes a text field
i never used that package so donno
try passing null=True and blank=True if you have model form
ill try and see if theres anything in the docs, thanks you for the help
ill try that
yup that fixed it! thank you for the help
I have a question with Django, in production, is the main server enough or do I have to use an alternative like Gunicorn
default server is development only
of course it is not enough
Gunicorn as minimum!
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?
python manage.py check --deploy
will give you full set of problems for production
Nginx should be used for back too
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.
Oh yeah I still need the admin panel available online
not a problem
Yeah bc I was wondering what was the difference between gunicorn and uvicorn
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
Idt any part of my DRF app needs any asynchronous programming
don't bother with it then
So i'll stick with WSGI for now
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 
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
Ok no I have a problem with Docker
Img can't detect the files
WTF
When they are in the same directory
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
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
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/
Yeah, but for some reason I can't execute any Django commands using just a simple command in the docker-compose. I needed to use shell scripts to get them running
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
ouch idk, I'm brand new to docker
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
are docker volumes relative or absolute paths?
Relative paths
Hi,
im working on a project that work in microservice architecture and currently I have 2 services:
- auth service
- 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?
I'm following https://realpython.com/introduction-to-flask-part-1-setting-up-a-static-site/ to make a website using Flask, and I've got to the test stage but when i input python app.py to my terminal and visit http://localhost:5000/ it doesn't connect
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
Personally they never did for my Django directory but idk if that was because the restart option was disabled.
Also you don't need volumes in production
@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
I think the saves are taken into account. When I used a local folder as a volume for my db, everything was saved.
You can use an option in the docker-compose file called restart : https://docs.docker.com/compose/compose-file/compose-file-v3/#restart
You need to implement a mechanism that allows the user to check whether they're identified or not. Usually we use tokens like the JWT one.
The only technique I know with JWTs are storing them in your browser (localStorage variable) then checking if it's the valid one
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.
I really feel difficult to design layout of website
Suggest me something which improve ky front-end skills.
React with Material-UI
@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
Clarify in which way communicate
You do know, that react is client side
Hi all, I have a question on Django REST nested relationships, should I ask such a question here or in the help channels?
I have a backend running on Django + NGINX that communicates with a CRA build, hosted on another NGINX container
Reacts loads and exists fully in user browser
The frontend sends credentials
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
I just want my services to be on the same load balancer. Both the backend and the frontend are on separate origins and need to be crossed.
You can make an internal REST API
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
Not always
You can make it render server side
Yeah that's exactly what I'm trying to make with DRF instead.
If you're curious, the backend url for that is at https://forms-api.pythondiscord.com/
And the sources are at https://git.pydis.com/forms-frontend and https://git.pydis.com/forms-backend
Anyone here that can help me with Django REST?
You know... I actually try to achieve almost the same for totally different purposes though
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
Node.js or prerender with react-snap and rehydration?
It's well-structured. I should take notes on the architecture.
I have one React-related question though: APIClient being imported is an axios instance, right?
Here's a good tutorial: https://www.digitalocean.com/community/tutorials/react-server-side-rendering
That's the technique I'm referring to, although I prefer Next.js for server side
// 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
src/api/client.ts lines 4 to 7
export default axios.create({
baseURL: process.env.BACKEND_URL,
withCredentials: true
});```
Since it's exported as default
It's possible that ApiClient was simply used for clarity
ok.
and after i stored the jwt token. Now I want to access my book service and i want some of my api calls to be accessible only to authenticated users.
should the book service check if the jwt token is valid by creating an api call to the auth service?
and if so, how should i do that? I mean is there a best practice for creating an external api call to other services?
the book service should not contact auth service
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
https://www.valentinog.com/blog/drf/
I want to try this
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
@inland oak SSR for each page or SPA?
it will make possible in one command building and running multiple containers connected with each other
depends on the web site content
SSR if you have multiple content like tutorials/blogs, that you wish them being indexed by search engines. Which are stored in your database, and need to be pre rendered on server side
in all other situations CSR, or CSR with pre render can work faster and better
I prefer Next.js for anything SSR/SSG tbh
ok.
you just shed some light on what im suppose to do ๐
so 2 more questions:
- if i have for instance 100 services, should each of them implement the encrypting/decrypting of jwt?
- this secret key, where do I store it so I could use in each service that I need to do an authentication ?
isn't that the purpose of docker-compose?
docker-compose fits them into an array of containers launched and running together)
you get more than one container
check with docker ps command
- yes, each 100 services should be able to verify JWT (something like SHA-256 by default is used there I think for signature?), and decrypt its base64 to get the data
- The secret key should be the same for auth service and all your 100 services in order to do that. Auth service create with his secret key JWT token, 100 services use the same secret key to verify the received JWT token
Thanks ๐
{% 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}}
how do i remove the firstname and lastname fields from the default user model(django)
from where can u explain correctly
from the admin panel
what?
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?
bump
it looks liks this is a real way to do that
these are the tuts I've been seeing lol. Ppl do that with vanilla npm + webpack
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
Yeah, the schema illustrates what docker-compose renders
Each box = 1 container
@inland oak dotted lines = 1 container
I would suggest additionaly splitting Gunicorn and Nginx box for backend
Adding a NGINX container between the two then?
One NGINX container will hold static files for both Django and react?
no no no
first choice almost
so, englobing React in Django?
Oh I see
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
Oh I see
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
Somethign like that? (hexagons = docker volumes)
oh yeah, the port is probably going to get modified
trying to photoshop it
You can use https://whimsical.com/ if you need flowcharts
Really useful tool
If you're more on keyboard there's mermaid.JS
can you copy yours scheme?
I did that on my work account whoops 
export it then
button at the top right with airplane sign
it has exporting feature
Decided to take it on my personal account
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
I guess something like that)
Oh I see
From the diagram, NGINX exposes the backend to the frontend. The Python code is governed by gunicorn
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
only for django admin yes
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)
So both nginx implementations will need ssl certificates?
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
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
Oh dw I see the trick
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)
I didn't wanna make the frontend entirely dependent from the back.
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
oh yeah, I forgot to delete impossible connection
deleted
nginx can manage several domains
and several certs
just make add another server {} to the config
Can someone explain to me why its not updating... this was working fine earlier today....
could it make with one domain
/ to one server
/api to another server?
yeah
I found that it is possible for sure with
/first_path
/second_path
just add a new path route
what if there will be route conflict
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
So both routes can coexist
yeah
As long as the origins are different?
as long as different paths at least
domain can be the same
and user can be the same
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("/")
our new improved scheme then
is it legit?
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
So looking at that, the NGINX serves to React?
yeah
Makes sense
@surreal portal woohoo. the scheme makes sense now
me at this moment: what's NGINX
It's a load balancer and reverse proxy
it can serve as regular web server too
And also Ingress Controller iirc
How does Frontend React interacts with Backend API?
Nvm I forgot to refresh
WHat they said. Youโll often see NGINX when it comes to serve static files, but it also serves as a load balancer when you have multiple users using your website
ohh
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
plz see up ^^ my msg 10-12 msg up i have doubt plz
eh. here goes my evening.
I thought to watch some cartoon and at last getting myself distracted from programming every day all day allong
I can barely sleep with those advanced webdev techniques
@surreal portal
the fun for me starts tomorrow
my books to get started in front end arrive
so, even more load then before%
Isnโt there an extension like Django login that can help you with that?
Last time I used Flask-login for authenticated users
nope django have in built
django is beast xD
They donโt have any webdev in the team and Iโm the only one who got some skills on webdev, despite me only making Flask apps and never touching React before
you are lucky. So much relevant experience goes all to you)
i like for now being one army web dev too. Nice to grow skills
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? ๐
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?
making your own thing will be more beneficial for sure)
you can learn the rest of bits during the process)
@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
then I will say my discriminatory words to you
in my opinion videos are a huge waste of time)
https://docs.djangoproject.com/en/3.2/ better walk through official turorial
or read beginner book for Djangoers, it would be more beneficial to you, if you aren't video guy
Thanks for your advice. I agree that it does seem like videos are a bit of a disconnected way to learn - watching someone else do it instead of doing it yourself, even if you're following along
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
surely. and you can follow it with speed you like at 100%
Do you think official tutorial -> Experimentation is the way to go?
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?
well, I would correct few things
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?
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
you can use django with javascript at the same time
And this is handling people connecting to the website, following links, logging in etc correct?
Aha, that makes more sense
Links can be done through HTML
backend is making manipulations with database, doing some calculations..
hmm, what does backend? ๐ค said backend developer.
mmm... it organizes any data you need before showing end results to user
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)
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?
they usually start with one part and trying to learn doing both parts
Thank you for the explanations. Can I ask what you think a good starting web project would be/ what your initial ones were? ๐
backend would keep lists of tweets, and will expose ability to like/reply/retweet and e.t.c.
but those actions would be triggered by frontend. Frontend would fetch and show this data from backend, frontend would activate for user backend ability to retweet
the first thing I started doing was this simple blog thing with user profile.
https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world
later decided I don't like Flask and switched to Django
I was asked actually to make web scrapper btw in reality, so refactorized a bit to fit the new case.
I first made an application for comment sections of websites
Hardest part about starting different aspects of python for me is figuring out what interesting thing I could build with it ๐ It's hard!
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.
Like an application to handle comments being submitted and stuff like that? Sounds like a good place to start
Yeah, I provided people with an iframe component that they could embed on their websites
Sounds ideal for an MMO
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
hell yeah)
It's not like just making a calculator or something
so many languages and technologies to know
wondrous profession.
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!
ok stuck idk what to do now and from where
done this docs
made 1-2 apps
what next
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 ,
What about an online Python editor?
With syntax highlighting and you can save your code
u r talking about repl xD
It wouldn't be too hard. Make an <input> field and make the font monospace with CSS
Or you could use codemirror
hey can u tell me how can i learn next cez bro docs after are too boring
@calm plume
Next what?
In Django?
Don't just try to read docs
there are so many
Build real world applications that people can actually use
my kids will read ig
idk that much rn
That's what I said, you don't need to
You only need to read what you need
Building an application is the best way to learn imo
any yt tutorial so i can get sign in sign up (django auth ) topic then i can go to learn myself
Corey Schafer's Django series is good
ok then gonna kill it too fast
too fast
and apply side by side in my project
thanks alot
love u
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
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>
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?
If it's only for some channels it's probably not a problem with your code, you probably need help from someone who knows the API better and why you sometimes get no results
How do you get the Accept-Encoding (br, gzip, deflate) from the browser via JavaScript without going through a server that can return that ?
Someone can help me with Web Scraping with Selenium?
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?
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
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
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?
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
is it recursive?
when render_template() is run does it go through the whole function again until it gets to redirect() ?
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)
I don't understand what causes login() to run, and how many times it runs
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
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
Yea ok there is no second get, the form is just rendered again
it's in debug mode btw, idk if that changes anything
No i dont think it matters
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
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?
flask, django
nice timezone
i think you mean javascript, a client-side programming language that can work right in the browser
learn javascript then to make things faster learn react
thanks
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
whats the best way to remove the first and last name column in the default django user model
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?
good question!
Umm?
what are frame assignments?
and what means [Channels included]
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
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
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.
found โ๏ธ
<@&831776746206265384> boop
it looks like you all was very clear
you can use local hiring or freelance sites @graceful flax
is still books relevance in this fast pace world?
I love books as main source to learn from
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
i mean various companies implement online courses, vids, etc..... is book still being taken attention?
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?
yes
because in my defense.....
Oh I'm not looking for someone here, I'm a frontend guy, I've no clue how to judge the person. So wanted to know what type of questions do people ask at that level
i see.. #career-advice is the place for that
Oh okay thanks will ask there!
book still remain in my opinion a way to get in a quick way a deeper understanding of subject
tutorials are often... only touching the top of the thing
and all other interfactive things
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
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
well you did a really good job explaining your opinions though and perhaps i'll implement it perhaps in my tight sched...
believe or not... but I often see people who take online courses
they pay a lot of money
not a good gramatical structure ha ha
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
i never thought of it though...... tbh i rely learning DS & A on youtube vids and planning to take online course for my collge requisite
well good online courses cost tons of money from consumers though. I only acquire courses in udemy for $11 (depends to which i'll be learning)
its not that we are different.. my friends too recommend me reading books but we have different life responsibilities to take on to...
books are usually a faster way to go
maybe i'll be double hustle for this one though
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
woah.... what strategies you implement on reading?
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
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
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
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?
@inland oak if you don't mind me asking, whats your job title? Devops?
technically I am Backend Software Developer.
but fulfilling a bit of Devops duties part of my time.
wishing highly to learn Frontend, today I will start doing it. Going to get my Head First O'Reilly books for that.
At what point did you think "ill apply to a job", after your first project?
@inland oak go for React :)
that's my goal. already chose it
I applied immediately after graduating from university.
got lucky at third random interview to be accepted into web dev.
my resume was actually suggesting to accept any software dev role, starting from C#.
I got really lucky to get my first job in web dev, because I wished to work with it since my teenhood
Oh cool, thanks for letting me know! That's really valuable for me.
I was accepted after I made my entring assignment
https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world
I was able in five days to pass this tutorial and to make this simple web site with user profile and blog
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)
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?
somebody used JetBrains IDE in your project with .idea I think
that's not really important, some nice settings could be saved there though
my vscode projects often get .vscode folder because of it
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)
well actually i also followed that tutorial
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
is it alright
ok but what django.contrib.auth.models import User
this module do what
well , it is storing the information about users , which could be as many authors as you want
ohh
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') right after: base64, I guess that is = or something. How can I prevent jinja from doing that??
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...
i was not knowing about that field WOw op , but why r we using foriegn key there , cez is no any other model , so what's the use of using foreign key and to add User in it
๐คฏ
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
no clue what that means
i mean to say that , is it necessary to use User module
for writing backend of sign up and sign in page?
@opaque rivet
it's not necessary, but it helps, and it saves you from making your own model for users.
umm got it , facing issues to understand
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
How do i get values from discord.com bot login page?
yes ig its cez
do we have to do anything here
My precious books have arrived about frontend
At last I am going to get started in it
best of luck @inland oak
no, I asked you how is User.objects.all() related at all to that code?
you showed a random, unrelated code snippet and asked something about User.objects.all() without relating why
umm u want code of views.py
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
exactly, so what even is your question
``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
Ok, what is your question
..
but when im doing
wait i send a screen shot
i'll **
still, that's not a question 
I just ask because it makes 0 sense what you asked, so there's no point quoting it again
oh
im dumb sorry

Like, what are you trying to do??
User is a model
posts is just a list.
They are unrelated
hmm ik i have readed the docs
but in video
he have accessed through
this User
idk how
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.
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



