#web-development

2 messages · Page 184 of 1

past cipher
#

does anyone know how to use Redis with Heroku? I have an app which I developered locally, and I setup a redis server, and it worked perfectly. My broker url was:
redis://localhost:6379/0

So on Heroku, I signed up to a Redis addon, and it gave me a link like:
redis://redistogo:3e46b******0@dory.redistogo.com:9556/

However, the tasks aren't being called.

dense cloak
#
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
  <div class="container-fluid">
    <a class="navbar-brand" href="#">Navbar</a>
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavDarkDropdown" aria-controls="navbarNavDarkDropdown" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarNavDarkDropdown">
      <ul class="navbar-nav">
        <li class="nav-item dropdown">
          <a class="nav-link dropdown-toggle" href="#" id="navbarDarkDropdownMenuLink" role="button" data-bs-toggle="dropdown" aria-expanded="false">
            Dropdown
          </a>
          <ul class="dropdown-menu dropdown-menu-dark" aria-labelledby="navbarDarkDropdownMenuLink">
            <li><a class="dropdown-item" href="#">Action</a></li>
            <li><a class="dropdown-item" href="#">Another action</a></li>
            <li><a class="dropdown-item" href="#">Something else here</a></li>
          </ul>
        </li>
      </ul>
    </div>
  </div>
</nav>

expected output

#

actual output

#

the thing doesnt dropdown

#

from bootstrap btw

limpid python
#

The html without the JavaScript

meager anchor
#

also, your STATIC_ROOT setting

limpid python
#

I get a 200 error

dense slate
#

200 is success

quartz yacht
#

Hoping there are a couple django masters here because Im having an issue with my form. My goal is to present a form to the end user which asks for a name, an ip and cidr. I want to then take the name, use it to create a digital ocean droplet via doctl, and return the public IP and the droplet id. My code, will go as far as creating the droplet and even returns to success (the home dashboard) but it doesn't ever save to the model.

Here is the code of my view:

#
def LighthouseCreateView(request):
    if request.method == 'GET':
        form = CreateDroplet()
    else:
        form = CreateDroplet(request.POST)
        
        if form.is_valid():
            try:
                post = form.save(commit=False)
                lighthouseName = form.cleaned_data['lighthouseName']
                droplet_id = []
                whats_the_ip = []
                create_droplet = subprocess.run(
                    ["doctl", "compute", "droplet", "create", "--image", "ubuntu-20-04-x64", "--size", \
                     "s-1vcpu-1gb", "--region", "nyc1", lighthouseName, "--wait", "--format", "ID",
                     "--no-header"], capture_output=True, text=True
                    )  # stdout=subprocess.PIPE, text=True),

                for line in create_droplet.stdout.splitlines():
                    droplet_id.append(line)

                droplet_id.append(create_droplet.stdout)

                get_the_ip = subprocess.run(["doctl", "compute", "droplet", "get", droplet_id[0], \
                                             "--format", "PublicIPv4", "--no-header"], capture_output=True, text=True)

                whats_the_ip.append(get_the_ip.stdout)
                publicIP = whats_the_ip[0]
                dropletID = droplet_id[0]
                ipv4 = form.cleaned_data['ipv4']
                cider_size = form.cleaned_data['cider_size']
                
                post.customer = request.user
                
            except BadHeaderError:
                return HttpResponse('Invalid header found.')
            return redirect('success')
    return render(request, 'pages/droplet_create.html', {'form': form})
quartz yacht
#

Another question I have is how do I troubleshoot this problem, how do I figure out where the view is failing?

quartz yacht
#

nvm, just realized I was missing the save command. sorry if I wasted anyone's time.

cerulean badge
#

what error should i raise if someone tries to visit checkout url when no order exists or there is not in stock products in order?
is this worth replacing

try:
        order = request.user.orders.get(placed=None)
        items = order.items.filter(product__available=True)
        if not items.exists():
            return redirect('shop:cart')
except Order.DoesNotExist:
        return redirect('shop:cart')

this?

order = get_object_or_404(Order, user=request.user, placed=None)
items = order.items.filter(product__available=True)
if not items.exists():
        raise Http404()
#

is it neccesary to write extra code for that or the later i provided is just fine?

native tide
#

I have a domain in google domains. I don't know how to point the domain to my vps.

#

This is my record thing

#

I don't understand it honestly

#

I just want to host my website with my vps with the domain dyabot.io

#

anyone know how to do this

proper hinge
#

You need to add an A record. The host name can be @ for the root and it should direct to the IP address of your VPS

#

If you want to also support the www subdomain then after you add the A record, you can add a CNAME record with www as the hostname and pointing it to @, the root.

native tide
#

Can you give an example in this order that the screen shot is like

proper hinge
#

I don't have any domains on google domains so I don't know what exactly the interface looks like for A records

native tide
#

@proper hinge I sent a screenshot of what it looks like

proper hinge
#

That's a CNAME, not an A record

native tide
#

ok

#

@proper hinge

#

If I dm you my server information

#

can you setup my website

#

I'll send your the host, username, password and port then you can setup the website cause I'll also send you the files

proper hinge
#

No I do not help anyone over DMs. Also I'm not just gonna do everything for you, sorry. If you need help that's fine to ask, but asking to have it all done for you is another story.

native tide
#

ok

proper hinge
#

Did you get the IP of your VPS?

native tide
#

Is this good

proper hinge
#

If you only want it to work with www then yes. If you want it to work with or without the www. then you'd need to do it differently.

native tide
proper hinge
#

Then leave the first field blank. It should then show "dyabot.io" underneath.

native tide
#

then the rest is fine?

#

can I make the ttl like 120

proper hinge
#

The default is fine.

native tide
#

ok

#

ok

#

how long till it connects to my vps

proper hinge
#

I'm not sure.

native tide
#

what would be the normal time

proper hinge
#

I don't know; I never really paid attention to it. I don't ever remember it taking too long.

native tide
#

@proper hinge how do I check if the domain is connected to the vps IP

#

nvm figured it out

#

mark how do I host it now

proper hinge
native tide
#

nvm,

lavish prismBOT
calm cairn
#
from kivy.app import App
#

check the example usage

buoyant star
#

hi

#

can anyone help me with selenium

#

im assuming this is the best place

brittle crag
inland oak
calm cairn
vagrant star
#

hello

#
 Model.objects.filter(is_completed=1, created_date__range = [firstday_quarter, lastdate__quarter]).annotate(quarter=TruncQuarter("user__created_date"), year=TruncYear("user__created_date")).filter(created_date__quarter= F('quarter'), created_date__year= F('year')).values_list("user", flat=True).distinct().count()
#

Purpose is to filter out user created in the same quarter of the model instance created. I am not sure why it is not working. thanks

inland oak
#
Model.objects.filter(
    is_completed=1, created_date__range=[firstday_quarter, lastdate__quarter]
).annotate(
    quarter=TruncQuarter("user__created_date"), year=TruncYear("user__created_date")
).filter(
    created_date__quarter=F("quarter"), created_date__year=F("year")
).values_list(
    "user", flat=True
).distinct().count()
#

this will be a bit more readable. Black is good formater.

vagrant star
#

aye thanks. I am not used to here.

inland oak
lavish prismBOT
#

Here's how to format Python code on Discord:

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

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

inland oak
#

Black is a python library, which I use in my IDE to auto format the code on the file save

vagrant star
#

oh. I was using shell to validate the query. sadly did not work

thorny quartz
#

is it possible to use foreign key without drop down list

#

I have a student table and i have another table of their marks so i don't want to choose student every time to put their marks I have a button in every row of student list to add marks

rotund perch
#

Hello, is it possible to create a django api and host it while doing CRUD with an external front end ? (front end files not included with the project). Most tutorials just make the front end inside the django app. But making it external will work perfect?

dusk portal
#
@csrf_exempt
def signup(request):
    if request.method=='POST':
        try:
            data=JSONParser().parse(request)
            form=RegisterForm(data.POST)
            if form.is_valid():
                form.save()
                token = Token.objects.create(user=form)
                return JsonResponse({'token':str(token)},status=201)
        except IntegrityError:
            return JsonResponse({'error':'That username has already been taken. Please choose a new username'}, status=400)``` this is my view for signup i want when the user makes an acc it generates a token itself automatically instead i use drf_create_token user
#
File "C:\Users\91834\PycharmProjects\dj_todoapp\TODO\api\views.py", line 45, in signup
    data=JSONParser().parse(request)
  File "C:\essentials\python\lib\site-packages\rest_framework\parsers.py", line 67, in parse
    raise ParseError('JSON parse error - %s' % str(exc))
rest_framework.exceptions.ParseError: JSON parse error - Expecting value: line 1 column 1 (char 0)```
native tide
#

django resources pls

craggy laurel
#
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys


def main():
    """Run administrative tasks."""
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_test.settings')
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    execute_from_command_line(sys.argv)


if __name__ == '__main__':
    main()
#

What's the problem?

dense slate
#

I was wondering why I couldn't get it working with my Python. I totally forgot about Black.

inland oak
green prairie
#

Man, I cannot figure out what frontend framework to use. I kinda wanna migrate to Svelte, but my current webapp uses React

modest hazel
#

Anyone know what this is called?

    f"""
    $------WebKitFormBoundarymTDDwARBcp485hke\r\n
    Content-Disposition: form-data; name', '"coverPhoto"; filename="picture.jpg"\r\n
    Content-Type: image/jpeg\r\n\r\n
    
    {img}\r\n    
    ------WebKitFormBoundarymTDDwARBcp485hke--\r\n    
    """
#

Like, what type of data transfer this is

#

the {img} here would be bytes or base64 encoded bytes

neat tide
#

Guys I need help, how do i further my knowledge in python, i did the basics but i can only code in the IDE, any roadmaps or advice?

barren stratus
#

i need help with django orm
here is my model


class Post(models.Model):
    id = models.AutoField(primary_key=True)
    content = models.TextField()
    images = models.ManyToManyField(to='Image')
    user = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return 'Post {} - \'{}...\' by {}'.format(self.id, self.content[:5], self.user.username)


class Image(models.Model):
    id = models.AutoField(primary_key=True)
    image = models.ImageField(upload_to='images')

how can i fetch images dynamic lazy (as in sqlalchemy) while querying posts

ionic raft
# neat tide Guys I need help, how do i further my knowledge in python, i did the basics but ...

I have mostly only coded in PyCharm. I tried VSCode and atom. In the end my using PyCharm hasn't slowed me down, but that learning style works for me. I benefit from seeing suggestions I missed and researching what and why was suggested.
The road map I would suggest for learning comes down to building projects and learning new concepts to solve new problems that come from solving different problems. Of course, that works for me. Your own learning style preferences will apply 🙂

proper hinge
fast lava
#

hi guys

proper hinge
#

Though I don't know in what context that string needs to be used in

fast lava
#

I'm trying to make a request and get certification error
I have checked the correct certification on google chrome padlock next to url, exported and added to my request but still getting the same error

proper hinge
#

I guess in practice it would actually have to be a bytes object rather than a str

fast lava
#
url = 'https://internaltool.com'
response = requests.get(url, verify='cert.cer')
#
SSLError: HTTPSConnectionPool(host='internaltool.com', port=443): Max retries exceeded with url: / (Caused by SSLError(SSLError(136, '[X509: NO_CERTIFICATE_OR_CRL_FOUND] no certificate or crl found (_ssl.c:4265)')))
hot eagle
#

if i use flask for back end what front end library should i use

opaque rivet
#

hey guys, why do we actually use docker? I understand docker containers vs virtual machines and why it has some advantages.
however, if we are migrating a project from 1 computer to another, why not just setup fresh venv and install the contents of requirements.txt? What is the advantage of using docker?

inland oak
# opaque rivet hey guys, why do we actually use docker? I understand docker containers vs virtu...

a) we aren't polluting main server with our dependencies.
b) we can run multiple containers that require same things in simplified manner
It's lightweight replacement for running multiple virual machines, which is not increasing the cost with each new container(at least not considerably)
c) inside the container we can keep specific linux distro we need for the service, simplifying installation of our app to different distros
d) essentially we keep server configuration in dockerfile as part of the code, which is kept version controlled with git. Hello infrastructure as code principles.

#

e) later can be comfortably scaled into huge infratructure/hundreds servers with ansible/kubernetes (which operates with containers too)

opaque rivet
#

a) venv does that
b) docker containers > virtual machines, I can see that
c) yeah I guess it's a benefit you can run bash scripts from one docker-compose file... helps keep things in one place.
d) same as c really but could just be env variables in settings.py

#

Thanks for the help.

#

Say I had my app dockerized, with nginx and all, what would be my next stop? Do you know the AWS service I should be interested in?

inland oak
opaque rivet
#

HA database?

inland oak
#

Anyway... it depends on what u a missing

inland oak
#

Triple database with replication between them for example is probably in this field

opaque rivet
#

Like copies of the same db?

inland oak
#

I did not read the book yet about this topic

#

So not sure about details with 100%

inland oak
#

Literally a can of worms

opaque rivet
#

yea I can imagine. lol

#

Devops is enough worms for me

#

It's confusing enough

weary remnant
#

heya

#

so do you guys build lots of small projects to get experience

#

i'm trying to get back into programming after graduating so i'm gunna try to make a project with the MEAN stack

dense slate
#

None of those sound python related. 😄

#

But sounds like fun!

weary remnant
#

yeah I got into python recently so I could scrape stuff for a project and now I'm wondering if I should try django or something

#

but uhhh i don't really know anything about python web stuff

dense slate
#

Same idea. Django/Flask as a backend with any front end you want to use.

#

Does Node have an ORM or is it just straight SQL?

late igloo
weary remnant
#

ah man i think this is why i have such bad decision paralysis haha

proper hinge
opaque rivet
#

Yeah that's true didn't think about that. Like packages downloaded from apt

modest hazel
#

I'm just confused on how to upload to aws s3 bucket directly

#

it requires that multipart thing

#

but everything I do fails

proper hinge
#

I'm not familiar with S3, sorry

#

I know boto3 is a library for a lot of AWS features. Have a look at that to see if it helps your use case.

fallen knoll
#
[2021-08-24 23:29:23,510] ERROR in app: Exception on request GET /dashboard
Traceback (most recent call last):
  File "C:\Users\King\AppData\Roaming\Python\Python38\site-packages\aiohttp\connector.py", line 969, in _wrap_create_connection
    return await self._loop.create_connection(*args, **kwargs)  # type: ignore  # noqa
  File "C:\Program Files\Python38\lib\asyncio\base_events.py", line 1025, in create_connection
    raise exceptions[0]
  File "C:\Program Files\Python38\lib\asyncio\base_events.py", line 1010, in create_connection
    sock = await self._connect_sock(
  File "C:\Program Files\Python38\lib\asyncio\base_events.py", line 924, in _connect_sock
    await self.sock_connect(sock, address)
  File "C:\Program Files\Python38\lib\asyncio\proactor_events.py", line 702, in sock_connect
    return await self._proactor.connect(sock, address)
  File "C:\Program Files\Python38\lib\asyncio\windows_events.py", line 808, in _poll
    value = callback(transferred, key, ov)
  File "C:\Program Files\Python38\lib\asyncio\windows_events.py", line 595, in finish_connect
    ov.getresult()
ConnectionRefusedError: [WinError 1225] Der Remotecomputer hat die Netzwerkverbindung abgelehnt

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Program Files\Python38\lib\site-packages\quart\app.py", line 1467, in handle_request
    return await self.full_dispatch_request(request_context)
  File "C:\Program Files\Python38\lib\site-packages\quart\app.py", line 1492, in full_dispatch_request
    result = await self.handle_user_exception(error)
  File "C:\Program Files\Python38\lib\site-packages\quart\app.py", line 968, in handle_user_exception
    raise error
  File "C:\Program Files\Python38\lib\site-packages\quart\app.py", line 1490, in full_dispatch_request
    result = await self.dispatch_request(request_context)
  File "C:\Program Files\Python38\lib\site-packages\quart\app.py", line 1536, in dispatch_request
    return await self.ensure_async(handler)(**request_.view_args)
  File "D:\TPBot\TPBOT\backend\main.py", line 46, in dashboard
    guild_count = await ipc_client.request("get_guild_count")
  File "C:\Users\King\AppData\Roaming\Python\Python38\site-packages\discord\ext\ipc\client.py", line 97, in request
    await self.init_sock()
  File "C:\Users\King\AppData\Roaming\Python\Python38\site-packages\discord\ext\ipc\client.py", line 61, in init_sock
    self.multicast = await self.session.ws_connect(self.url, autoping=False)
  File "C:\Users\King\AppData\Roaming\Python\Python38\site-packages\aiohttp\client.py", line 754, in _ws_connect
    resp = await self.request(
  File "C:\Users\King\AppData\Roaming\Python\Python38\site-packages\aiohttp\client.py", line 520, in _request
    conn = await self._connector.connect(
  File "C:\Users\King\AppData\Roaming\Python\Python38\site-packages\aiohttp\connector.py", line 535, in connect
    proto = await self._create_connection(req, traces, timeout)
  File "C:\Users\King\AppData\Roaming\Python\Python38\site-packages\aiohttp\connector.py", line 892, in _create_connection
    _, proto = await self._create_direct_connection(req, traces, timeout)
  File "C:\Users\King\AppData\Roaming\Python\Python38\site-packages\aiohttp\connector.py", line 1051, in _create_direct_connection
    raise last_exc
  File "C:\Users\King\AppData\Roaming\Python\Python38\site-packages\aiohttp\connector.py", line 1020, in _create_direct_connection
    transp, proto = await self._wrap_create_connection(
  File "C:\Users\King\AppData\Roaming\Python\Python38\site-packages\aiohttp\connector.py", line 975, in _wrap_create_connection
    raise client_error(req.connection_key, exc) from exc
aiohttp.client_exceptions.ClientConnectorError: Cannot connect to host localhost:20000 ssl:default [Der Remotecomputer hat die Netzwerkverbindung abgelehnt]

@proper hinge Could you please help me?

mystic wyvern
#

user.save(using=self._db) why i cant just make it user.save()

proper hinge
fallen knoll
#

Wait

jade lark
nova pewter
#

Are class based views the go-to for django web development?

vestal hound
#

just a tool

nova pewter
#

also a super dumb question, how do you work on the files from git? do i work directly on the same directory in my code editor or just copy and paste the files to the git folder after working?

vestal hound
#

Git should track (almost) everything in your project folder

#

in general, small and frequent commits are good

nova pewter
#

thanks

violet dock
#

how to run something like discord bot in my flask app?

#
from quart import Quart, request, redirect, render_template, abort
from bot import client
from panel import *
import asyncio
import json


app = Quart(__name__,template_folder='template')

@app.route("/edit", methods=["POST"])
async def edit():
    data = dict(request.form.items())
    buy, sell = (
        {"keys": int(data["buy_keys"]), "metal": float(data["buy_metal"])},
        {"keys": int(data["sell_keys"]), "metal": float(data["sell_metal"])},
    )
    await client.update_price(data["name"], buy, sell)
    return redirect("/prices")


if __name__ == "__main__":
    asyncio.run(app.run_task(), client.run("username", "password", shared_secret="shared_secret"))``` Here is my code
manic frost
dusk portal
manic frost
dusk portal
#

Django Rest Framework

manic frost
#

Do you want to post form data or json?

dusk portal
#

I can make post form

#

I just wanna Jsonify my Signup functionality

manic frost
native tide
#

how can I host my website with my vps

#

I connected the domain to the server

#

just can't run it

#

People have tried helping me just

#

isn't working

near bison
#

I have heard that Heroku removes static files automatically. what files are considered static and how are they identified ?

grave raft
#

any advice on how to handle search in large csv files in django, I can't design the flow should I use dramatiq or should I use channel and http long polling and how should I return response

lucid marsh
#

does anybody here know what's the javascript equivalent of max() in python?

lucid marsh
#

ok, thanks

#

it worked*

manic frost
#

On large arrays, you should use reduce, as the documentation says

lucid marsh
#

ok

marble pulsar
#

so the framework I'm using, Odoo 14, is creating meta tags with links like:
<meta property="og:url" content="http://localhost:8014/shop/product-3"/>
this seems like a bug? All meta urls for my page should be relative, like
<meta property="og:url" content="/shop/product-3"/>
right? This is more of a question for generic meta tag than for framework

finite canyon
#

Hi, guys
I've been working on a Django learning project from Eric Matthes book. And there said that I need to do a migration. All I need is to add attribute public = False at the end of this model:

    text = models.CharField(max_length=200)
    date_added = models.DateTimeField(auto_now_add=True)
    owner = models.ForeignKey(User, on_delete=models.CASCADE)
    public = false  - THIS LINE

    def __str__(self):
        return self.text```

After I added the line to the model and tried to makemigrations Django says that no changes detected in app.

Why can't I migrate it?
Note: migrations work properly when I add new models
marble pulsar
marble pulsar
finite canyon
dusk portal
#

why can't i render my ajax files

#

plz help it's a basic problem but mostly i face problems while handling static files

#

@marble pulsar

marble pulsar
dusk portal
marble pulsar
dusk portal
#

ohk fixed that

#

sorry to disturb

opaque rivet
finite canyon
opaque rivet
#

e.g. if path was /shop and you were on URL http://mysite.com/product/1, you would be redirected to http://mysite.com/shop instead of http://mysite.com/product/1/shop/ (relative)

finite canyon
opaque rivet
#

I guess technically it would be a relative path.

#

but whichever you choose there shouldn't be a problem. absolute paths would be best for troubleshooting

opaque rivet
lavish prismBOT
#

Here's how to format Python code on Discord:

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

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

finite canyon
opaque rivet
#

yeah, that's how you'd highlight it

#

have py infront of the first 3 backticks

unreal bolt
#

does someone know how to change the "windows search the web" to search via google instead of bing?

rustic wing
unreal bolt
rustic wing
#

oh, sry hahah

unreal bolt
#

just to ensure, so when i'll search something on windows it will redirect it to google chrome, or to google search engine? those are 2 different things @rustic wing

rustic wing
#

first of all, you need to make chrome your default app

rustic wing
#

is it working rn?

unreal bolt
#

not yet

#

but

#

i mean, when i'll search on windows search it will open google chrome + google search engine
or
edge chromium + google search engine?

rustic wing
#

it should open google chrome and google engine

unreal bolt
#

okay

#

i wanted to open edge, but is fine like that aswell

#

thanks!!

#

u can reask ur question bro

rustic wing
opaque rivet
#

hey... a bit confused on staticfiles. client is making requests to:
http://127.0.0.1:8000/_next/static/chunks/webpack-715970c8028b8d8e1f64.js

STATIC_ROOT = os.path.join(BASE_DIR, 'frontend', '.next', 'server', 'static')
STATIC_URL = '/static/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'frontend', '.next', 'server', 'static', 'chunks'),
    os.path.join(BASE_DIR, 'frontend', '.next', 'server', 'css'),
    os.path.join(BASE_DIR, 'frontend', '.next', 'server', 'image')
]

I put all of the dirs where I think my frontend might want staticfiles in STATICFILES_DIRS. But these don't correspond to _next/static/...

#

like I'm just confused. linking django with next.js static files

#

Or should STATIC_ROOT be something like /static/? Then I collectstatic and django will compile all the staticfiles in STATICFILES_DIRS and then I can somehow serve them?

#

This seems like a pain and there isn't much online... next.js ships with its own node server, do I just deploy my backend and frontend seperately? (so django just acts as an API and does not render any templates)?

rotund perch
# opaque rivet This seems like a pain and there isn't much online... next.js ships with its own...

Yes I see seperating it would be the best. Dont forget

  1. pip install django-cors-headers

INSTALLED_APPS = [

...

'corsheaders',

...

]

3.```py
MIDDLEWARE = [
  'django.middleware.security.SecurityMiddleware',
  ...
  'django.middleware.clickjacking.XFrameOptionsMiddleware',
  'corsheaders.middleware.CorsMiddleware',
]

CORS_ORIGIN_ALLOW_ALL = True #to allow all URLS (so it can access ur api)

OR
```py
CORS_ORIGIN_ALLOW_ALL = False
CORS_ORIGIN_WHITELIST = (
  'http://localhost:8000',
) #to make localhost (react app) can only access django api
opaque rivet
#

yeah I've got cors sorted, thanks

rotund perch
#

np.

opaque rivet
#

ok so say I had gunicorn on port 8000 and my frontend (nodejs server) on port 3000 which makes API calls to my API on port 8000. I have nginx route the user's request to my frontend server and have it serve the staticfiles. Do I need to do anything else?

rustic wing
#

did you change the allowed host in settings?

#
ALLOWED_HOSTS = [' IP address ', 'localhost']```
#

and this is how you map your static file:

 # os.path.join(BASE_DIR, "static/"),
 # ]
 STATIC_ROOT = os.path.join(BASE_DIR, 'static/')```
opaque rivet
#

anyone deployed next.js with django? do I try to serve pages from my django server or let the nodejs server handle it?

tidal garden
#

how do i get users social account uid in view function using allauth

rotund perch
rustic wing
tidal garden
#

well i figured out this way

#
social_account = SocialAccount.objects.filter(user=request.user)
uid = social_account[0].uid
#

ty anyways

rustic wing
tidal garden
#

ty tho

rustic wing
#

you are welcome

severe urchin
cerulean badge
#

(context django) i have a payment_method field with stripe and cod choices should i not set default on them and if i do then stripe or cod?

opaque rivet
#

nginx question

upstream backend {
    server backend:8000;
}

server {
    listen 80;
    location / {
        proxy_pass http://backend;
    }
}

Visiting 0.0.0.0 but getting the nginx welcome message. Shouldn't this be redirecting the request to my backend?

frank shoal
#

What's running in the backend?

frank shoal
#

Did you restart the daemon?

opaque rivet
# frank shoal ?

django container. If I visit 0.0.0.0:8000 then my page is rendered.

frank shoal
#

restart nginx

opaque rivet
#

well, I've restarted the nginx container multiple times if that's what you mean

#

my .conf file is fine right?

frank shoal
#

Looks good. Which file is it you're editing?

#

/etc/nginx/conf.d/default.conf?

opaque rivet
#

yeah, /etc/nginx/conf.d/default.conf

frank shoal
#

Anything in the nginx log?

opaque rivet
#

just 200 status codes after visiting 0.0.0.0

#

I'm gonna look at the filestructure of my nginx container real quick

frank shoal
#

ah, docker.

dense slate
#

shouldn't you be editing the sites-enabled?

frank shoal
#

Isn't that for httpd/apache2?

dense slate
#

It's for nginx

tidal garden
#

y this```py
def add_member_to_guild(self, user_id, guild_id, access_token):
headers = {
'Authorization': "Bot " + BOT_TOKEN,
'Content-Type': 'application/json'
}
data = {
"access_token": access_token,
}
url = f'{self.api_endpoint}/guilds/{guild_id}/members/{user_id}'
r = requests.put(url=url, data=data, headers=headers)
print(r)
print(r.json())

gimme this ```<Response [400]>
{'message': '400: Bad Request', 'code': 0}```
opaque rivet
dense slate
#

Django backend?

opaque rivet
#

yep

frank shoal
#

this is docker

dense slate
#

Even if you don't need it all, you'll get your nginx answers there.

#

Oh!

#

Does that matter?

#

I never used Docker

frank shoal
#

For one thing:

opaque rivet
#

strangely, I followed a guide exactly. They got their result and I'm hanging

#

but I'll try that one.

frank shoal
#

try removing the backend part and just doing proxy_pass http://backend:8000/;

#

What's the command you're using to start nginx?

opaque rivet
#

nginx

frank shoal
#

I mean the docker command

opaque rivet
#

using docker-compose, here's my Dockerfile

FROM nginx:1.21.1-alpine
COPY ./default.conf /etc/nginx/conf.d/default.conf
RUN nginx
frank shoal
#

and how do you run that image you're building?

opaque rivet
#

sudo docker-compose up

#

I don't have any command line args

frank shoal
#

You don't need an image if you're using docker-compose

#

what is your docker-compose.yaml file?

opaque rivet
#
nginx:
    build: ./nginx
    volumes:
      - ./nginx:/app
    ports:
      - "80:80"

    depends_on:
      - backend
#

the volume is redundant

#

and I checked the contents of the container, files look in the right place (/etc/nginx/conf.d/default.conf) that is

frank shoal
#

try ```yaml
services:
nginx:
image: nginx
volumes:
- ./default.conf:/etc/nginx/conf.d/default.conf:ro
ports: ["80:80"]

#

That way you don't have to rebuild every time you update the default.conf

opaque rivet
#

ah yeah that's a good point. will try now

#

huge image :d

#

oh... wait

#

same issue, think I need to do something with sites-enabled or something, I'll follow the guide but now I've got errors on my backend. I think I rebuilt the image and lot my db data

#

also, on a different note, what's the usual way of serving staticfiles in production?

#

also, on a different note, what's the usual way of serving staticfiles in production?

#

gonna use a S3 bucket but wanted to know what others use

mystic wyvern
#

Hi , i try to make a custom user model when i go to login in admin site he tells me the password or email incorrect why ?

opaque rivet
mystic wyvern
#

yeh i did

#

this is my whole model

#

when i copy the code from documentation it work

opaque rivet
#

did you specify a new AUTH_USER_MODEL?

mystic wyvern
#

@opaque rivet

opaque rivet
#

hmm, check if is_active=True and is_staff=True

frank shoal
mystic wyvern
#

oh wait

#

is_active isn't true

torpid dune
#

Hey, I'm losing my mind over this

#

So I know that in creating an object you had to do Model.objects.create() to make changes to the database but in one project I only used Model() and I didn't even have to use save()

#

Any ideas how this happened?

light cloak
#

You need the username you specified

#

e.g 'admin'

opaque rivet
light cloak
#

At least, this is an issue I ran in to before and found out that this was the problem. Could be something going on behind the scenes

torpid dune
indigo kettle
#

@torpid dune this was with a model that you wrote?

#

you could override the init method to save automatically

#

not a good idea but that would do it

amber ember
#

anyone around that has a solid grasp on Celery?

frank shoal
#

it doesn't work on windows

shut bloom
#

Does SASS support in github.io deployed web page?

torpid dune
sick notch
#

Wonder if someone could help with this problem...I've got a django app running on a digital ocean droplet. Once a day it runs a management command which takes about 4 hours to run and takes the droplet/server load up to 100% for the entire time. I've got a few other sites on the same droplet, it basically kills the web server for 4 hours and effects access to the sites.

I've tried things like setting the lowest possible niceness of the management command, doesn't help. What are my options...only thing I can think of is creating a new droplet/server and have the management command run on that, then when finished swap out the database from this "background" server to the copy of the django app running on the web server. Is there no better way?

#

@amber ember no but if you're using django take a look at django-q, it's lighter and easier to use than celery

wraith drum
sick notch
#

@wraith drum thanks for the reply.

  1. Upgrading the instance size/resources just means it cuts down the time where the instance is using 100%. Even if I doubled the instance resources, it's still going to have 100% load for 1 or 2 hours. This is instance is running nginx so my other sites would still suffer.

  2. Sorry I should have mentioned i'm using Sqlite and so don't have a separate DB server such as postgres. At the moment that would be even more work than just having a front end web server instance and a background server which runs the management commands. (2 servers vs 3). I thought I could just have 2 copies of the sqlite DB, then once the background server has finished it's work swap it out to the live web server? It's messy, I'd still have 1 codebase but two instances of the code on two separate servers. But it's the best I can think of at the moment...

mint flame
#

hello i am currently Developing my own Website and i am wondering if you Guys have any Tips

sick notch
#

@mint flame what type of tips would you like?

mint flame
#

design

#

My site is built with python and Html

#

and i am using the framework (Flask)

sick notch
#

@mint flame so what would you like help with? Front end design? I'd look into using a framework such as bootstrap for rapid front end design, but learn the basics first

mint flame
#

i use bootstrap rn

mellow pasture
#

i have an express js app, I want to host it for free somewhere to use it as the backend for my mern stack app other than heroku. also I heard something about cloud functions that can replace the api endpoints with some other things. If you know about this, please link me to a guide. Also I have no money to host anything but I don't need like any crazy host, any host with limited resources is ok.

#

also I am asking this in the python server as I can't really find anywhere else to ask the same

vocal python
#

i don't know how to link a login page to my file that i have created

#

can someone help me

#

not for a website for a exe file, that i have created. i want it where so everytime i launch my file it goes to a login page. and no one has told me how to do it

alpine nacelle
#

Sure this gets asked often - anyone got some good tutorial recommendations for Django (and to a lesser extent, React)? Not really a web developer beyond some very basic HTML and CSS years ago and I'm looking to get into it as the extent of my Python UI skills is still just printing to the console

#

And I actually need some polished projects I can stick on my CV when I graduate

wraith drum
alpine nacelle
#

Thank you!

wraith drum
# mellow pasture i have an express js app, I want to host it for free somewhere to use it as the ...

AWS https://aws.amazon.com/free/ and Oracle Cloud https://www.oracle.com/cloud/free/ have free tiers you can play with

mellow pasture
ancient scaffold
#

hi

warm minnow
#

could anyone help me with css in dm pls?
not python

versed abyss
#

is anybody familiar with the beuatiful soup library and could help me with something

warm minnow
versed abyss
#

i'm trying to get stock market prices but i'm a little bit stuck

#

here's what i ahve so far

#

have

#

from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup
metals = []
cost = []
url = 'https://markets.businessinsider.com/commodities'
client = uReq(url)
page_html = client.read()
client.close()
page_soup = soup(page_html, "html.parser")

preciousMetals_container = page_soup.findAll("td", {"class": "table__td bold"})
price = page_soup.findAll("div", {"class": ""})

for wrapper in page_soup.findAll("div", {"class": ""}):
print(wrapper.span.text)

warm minnow
#

why not use an api?

versed abyss
#

i'm trying to learn the library so i'm just messing around with it

warm minnow
#

ah, okay

versed abyss
#

so it just returns all the text from any span tag but i want it to only give me the text with prices

#

i'm not sure how to go about doing that

ionic raft
#

Docker question: I've got a docker container deployed successfully, but for one thing. Profile pictures are not showing. This works in development. Am I missing something?

#

In fact, I can't show images from either media sub-directory. I'm wondering if I need to add that explicitly in settings.py...hmmm

olive tiger
vestal hound
olive tiger
vestal hound
#

it's not about the type of content

#

e.g. your CSS and stuff is static

olive tiger
vestal hound
#

but a user's profile pic might or might not exist at that point

vestal hound
olive tiger
#

where do you store it?

olive tiger
#

you can store images in the db

vestal hound
#

This document describes Django’s file access APIs for files such as those uploaded by a user. The lower level APIs are general enough that you could use them for other purposes. If you want to handle “static files” (JS, CSS, etc.), see Managing static files (e.g. images, JavaScript, CSS).

By default, Django stores files locally, using the MEDIA_ROOT and MEDIA_URL settings. The examples below assume that you’re using these defaults.

vestal hound
olive tiger
#

I would not do this, use the db

olive tiger
vestal hound
#

just use Django's APIs

#

it manages files for you

olive tiger
#

if you have a user content, it is in many ways better to use the db for processing then the file system

#

and why should not I store image in the db?

#

you , probably, have a field in your model. DRF has ImageField, if I am not mistaken, which is the direct connection

vestal hound
#

which is why I'm saying

#

use Django's APIs

#

the images are not stored in the database.

#

they are stored on file.

#

(or whatever you configure)

vestal hound
olive tiger
vestal hound
olive tiger
#

my first assumption would be , that you messed up the path

vestal hound
#

or, for that matter, with Django

#

all Django provides is an abstraction around files

#

also, if you want to store raw file data in Django

#

it is more complex

#

than using, say, ImageField or FileField

vestal hound
olive tiger
#

lots of things changed in the postgres, there are modules like DRF, which address lots of django issues

vestal hound
#

and it literally doesn't, in this case

olive tiger
#

I have a little experience with storing images and files, but I have never had problems with it

#

you can check the docs for details

vestal hound
olive tiger
#

I use DRF fields for storing images, and it works

vestal hound
#

or are you just trying to argue for its own sake?

#

Django, and DRF by extension, stores file paths, not images, in the database.

#

which is literally what I have been saying to do this whole time.

vestal hound
olive tiger
#

maybe it does it under the hood, but it is not me, who manages those files

lucid marsh
#

Anybody knows how to do inline for loops in javascript?
for example, in python its like this:
[ord(i) for i in ['a', 'b', 'c']]
how do i do this exact same thing in javascript?

proper hinge
#

JavaScript doesn't have comprehensions like Python (IIRC it was proposed at one point but that fell through). You can do the same thing JS with a normal loop or with Array.map()

lucid marsh
#

ok, thanks

#

ill do it with normal loop

wanton grove
#

I started developing a SocketIO server with Flask the other day and I started to work on it tonight and suddenly my phone will not connect to the server no matter what. I tried switching between 2.4 and 5G networks and changing the host ip to "0.0.0.0" and the local ip of my PC which is what I have been using. I disabled my adblock and still nothing. any reason why my phone suddenly can't connect?

#

my PC (where the server is running) can connect just fine. I have other devices I could test on but I'd rather not get them out if I can help it

#

ok I busted out an old phone and it is also unable to connect so it seems to be an issue with the server itself

wraith drum
#

Are you also connecting to the correct port?

#

Do you have a firewall on your PC that might be blocking the inbound connection?

wanton grove
#

i'm aware

#

checking firewall rn

#

idk why it would have changed tho

#

just windows things ig

wraith drum
#

Also confirm the IP of PC didn't change

wanton grove
#

it didn't. it's static and I checked ipconfig

wraith drum
#

What error are you getting on the phone?

wanton grove
#

just straight up won't connect

#

it tries to for a while then says "could not connect because server stopped responding"

#

something like that

wraith drum
#

Ah ok, so that's a timeout error. I would check firewall

wanton grove
#

working on it rn

#

i'm working in a virtual env. is it possible it's only blocking the .exe for this particular env?

wraith drum
#

Possibly

wanton grove
#

wow that was it

#

I hate windows sometimes

#

I really need to get an SSD for linux

wraith drum
#

Instead of allowing the python exe, you can probably just open up the port in general

wanton grove
#

weird stuff. it was working like 3 days ago so idk why windows suddenly decided to block the .exe

#

alright i'll look into it

#

thanks

wraith drum
#

Maybe you recreated your virtualenv or something. No problem

rigid pivot
#

I'm trying to configure a Django webserver to run with python manage.py runserver, it says development server running on JupyterLab but using requests.get on the URL or going to it in a browser returns a failure

#

I did the virtualenv and the installation already and configured settings, I also tried different ports but it doesn't work. MySQL on the other hand works just fine using localhost

nova pewter
olive tiger
amber current
#

Hi there, someone could assist me with this mistake. I'm new with data transfer between back and front (it's my first time). If you know this mistake please help me

lavish prismBOT
#

:incoming_envelope: :ok_hand: applied mute to @amber current until <t:1629948209:f> (9 minutes and 59 seconds) (reason: attachments rule: sent 7 attachments in 10s).

rigid pivot
#

it was 127.0.0.1:8000, I tested this with MySQL and it seems like JupyterLab literally doesn't even run a server

olive tiger
#

why using it at all?

rigid pivot
#

my local python and powershell things seem to grind to a halt with pip install

olive tiger
rigid pivot
#

the speeds are 16kb/s or it keeps timing out and it never works

olive tiger
#

oh, you are on windows - sorry, can't help there

rigid pivot
#

JupyterLab actually downloads with my native internet speed

olive tiger
#

generally, for web apps, I use docker and docker-compose

rigid pivot
#

I'm just an undergrad student, is JupyterLab a sort of closed system? Where it will say it runs a webserver but because it's virtual it won't actually run anything? I will try docker

olive tiger
#

I do not know what it is. I heard about it a few times and it looks to me like a virtual environment

amber current
olive tiger
nova pewter
worthy lake
#

Docker with a full stack software needed to run on it is twenty times more confusing than the server configuration. Maybe that's just because Im old.

#

It might be easier top not break, but not necessarily easier to get working imo

#

I agree with that mostly but im also old. Maybe it is best to star threre now

royal radish
#

Hello,

I want to see how well did I learn python, so is there any website or set of problems on the web I can do to test myself? (for beginners)

worthy lake
#

I learned by trying to do projects on my own, without looking at what other people were ussing to solve that proble malready.

#

But those days taught me a lot.

final geode
#

How does one compress videos with Django

worthy lake
#

I would use ffmpeg to do it personally., but the command options for ffmpeg can be confusing. But usuaully an automated and effective conversion is possible if you search for the command options

nova pewter
sweet jewel
#

Hi all, how much django does one need to know in order to be dangerous?

unborn holly
#

Hello there

#

Need help buying laptop
Mostly for web dev and AI

nova pewter
unborn holly
nova pewter
#

more than enough but i would suggest getting 16gb ram

vestal hound
#

for example, if you don’t know that your secret key should be kept secret, you might leak the one used in production

#

that would be quite dangerous

vestal hound
#

what?

#

🥴

native tide
#

you type the emoji name in the commit

#

🔥 same as here

vestal hound
#

btw not sure if you know but in case you don't it's generally considered good style to write your commits imperatively

#

shrugs if it's your own project nobody cares though

#

you do you

cerulean badge
#

(context django, stripe) i am using stripe for payment.
i create a checkout session then redirect to its url,
after successful payment it send an event to the webhook
my question is how do i get the order id for which the payment was done?

stark tartan
#

(context django, stripe) i am using stripe for payment.
i create a checkout session then redirect to its url,
after successful payment it send an event to the webhook
my question is how do i get the order id for which the payment was done?

native tide
vestal hound
#
Extract CakeMaker dependency
Fix rounding error in WeighingMachine
Clean up test for Stove
native tide
#

i've been 'sloppy' til now. as you say its my repo. with few other contributers. but i'd like to encourage contributers and up my game as it gets a bit more noticed

vestal hound
#

vs

Extracted CakeMaker dependency
To fix rounding error in WeighingMachine
Stove test needs fixing
#

in general

#

you should be able to take your commit message

#

and put it after "this commit will"

#

and it should be grammatically correct

#

that's a simple rule of thumb

native tide
#

ah ok. ye i like that

#

i think i did learn that once 10 years ago. ill start doing it again

vestal hound
#

also proper capitalisation 🙏

manic frost
#

Why does JS allow awaiting anything at all?

#

I mean, I know that "because it's JS", but is there an actual reason?

thorn igloo
manic frost
thorn igloo
#

js is not python

manic frost
#

in JS await only does anything on promises

#

right?

thorn igloo
#

i guess so

manic frost
#

I mean, a promise is clearly distinguishable from, say, a number

#

actually,await doesn't work just on promises, but all objects that have a then method

#

but why does it not throw an error if it doesn't?

thorn igloo
#

.then is for promises bruh

#

what the

thorn igloo
#

async await is just another way of doing .then

manic frost
#

I understand that. What I'm asking is why await ignores a value if it's not thenable (i.e. just returns it) instead of throwing an error (since it's likely a programmer mistake if a non-thenable thing is awaited).

thorn igloo
#

why would it throw an error when the process completes? it's sort of similar to how you can make anything into a promise, i.e a function that returns a number

raven harbor
#

style="background-image:url('{% static 'img/coffecup.jpg' %}');"
how can i use background-image in django im confused

manic frost
thorn igloo
#

but you're asking why it doesnt throw an error

manic frost
#

I'm asking why it doesn't throw an error when you do await 42, for example

thorn igloo
#

maybe this willl give more insight

#

there is no reason for it to throw an error

#

it's valid syntax if that's what you're asking

#

and here

manic frost
#

I know that it's doing that, I read that page. I'm asking why it converts non-thenable values to promises instead of throwing an error.

As far as I can see there's no reason to await something non-thenable intentionally, so if something non-thenable is awaited, it's probably a result of a programmer mistake.

#

Unless you believe that errors should be silenced as much as possible, so that bugs are harder to find.

opaque rivet
#

I wonder if typescript does the same...

thorn igloo
#

yeah, i guess you'd have to ask whoever wrote this functionality why they wrote it to work like it does

manic frost
thorn igloo
manic frost
#

I was

#

the browser console doesn't use typescript

thorn igloo
#

await 42 will not work if you just write it like that in a script

manic frost
#

hm?

#

await is only allowed in async functions (and in modules) if that's what you're saying

thorn igloo
#

this works in a python console

#

but if i write that in a python script, it will obviously raise an error, that is what im saying

manic frost
#

I don't get what you're saying

thorn igloo
#

i'm saying writing something in a script and running the script is not the same as writing in the console directly

native tide
manic frost
#

in JS, awaiting non-thenable expressions works outside of the console (i.e. everywhere) if that's what you mean

thorn igloo
#

it only works inside something that's async

manic frost
#

I mean... yes, await only works inside async functions, I just don't understand how that relates to my question

thorn igloo
#

you were asking why await 42 doesnt raise an error

#

and the docs explain that it's converted to a resolved promise

manic frost
#

I know that it's converted to a resolved promise. I was asking why that behaviour was chosen over throwing an error.

thorn igloo
#

oh ok

thorn igloo
#

and obviously a backend to handle the functionality

native tide
thorn igloo
#

or the verification process?

native tide
thorn igloo
#

ok, well that shouldn't be that hard to replicate, it just requires a basic understanding of html and css

#

i would suggest at looking at flexbox for centering and stuff

native tide
#

yeah i thought it was html and css ect i just couldnt find any tutorials on yt or anything that are making something simlar

native tide
thorn igloo
#

you don't really need a tutorial for something this basic

native tide
#

oh

mystic vortex
placid smelt
alpine nacelle
#

Assuming it's recommended to have a solid grasp on HTML, CSS and JS before jumping into React?

thorn igloo
mystic vortex
#

@thorn igloo what is JWTs

#

??

thorn igloo
#

json web token

lavish ferry
#

Am I missing something here?

thorn igloo
#

but i misunderstood his question so it's all good now

lavish ferry
#

Oh you were teaching lol. Was going to say I think you would know that xd

opaque rivet
#

hey, trying to request a staticfile: http://127.0.0.1:8000/_next/static/chunks/pages/index-7b94d5719404612c5520.js but getting 404. Any reason why?

My settings:

# Staticfiles show here w/ ./manage.py collectstatic
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')

# Appended to urls when using {% static %} tag
STATIC_URL = '_next/'

# Where to look for staticfiles
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'frontend', 'staticfiles')
]

My dir structure:

| main_project
  | static
    | _next
      | static
        | chunks
          | pages
            |  index-7b94d5719404612c5520.js
#

url pattern for static files:

static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

From this, I'd imagine anything with the name _next/... will be caught by the route and it will be found in the static dir

vernal lotus
#

Hello, I'm new here.
Anyone have idea to create web based server monitoring tool to monitor multiple servers?
What are the model and techniques should I use?

cerulean badge
#

(context django, stripe) how do i refer back to the transaction once its successful? with id?

dusk portal
#

back to home

rustic wing
#

instead of this:

    os.path.join(BASE_DIR, 'frontend', 'staticfiles')
]```
glad patrol
#

hi need some help

opaque rivet
#

@rustic wing the static root can't be in staticfiles_dirs. Static root is where the staticfiles are moved after collectstatic, staticfiles_dirs is the dirs where staticfiles are found. Which is the right dir in my case.

glad patrol
#
<p class="terminal__line"><a href="#">Prog: 25%</a></p>
      <p class="terminal__line"><a href="#">Prog: 50%</a></p>
      <p class="terminal__line"><a href="#">Prog: 70%</a></p>
      <p class="terminal__line"><a href="#">Prog: 100%</a></p>```
#

i am printing these tag

#

they print so fast need to add some sleep in it

opaque rivet
#

@rustic wing doing it that way would mean that the collectstatic command would never detect the staticfiles. It would just regurgitate the same files and not detect changes.

#

@alpine nacelle yes, beginner knowledge of JS is enough.

glad patrol
#

nicky can you help in my problem

lucid marsh
#

do you want to make a new line or just edit the line?

#

If you wanna edit the line, make an element, then edit the innerHTML attribute

glad patrol
#

anythin is fine

#
function test1()
{    
    sleep(3000);
}```
#

i have this dont know how to call

lucid marsh
#

HTML:```html
<p id="prog">Progress: 0%</p>

JS:```js
document.getElementById('prog').innerHTML = 'Progress: 25%';
setTimeout(function(){
  document.getElementById('prog').innerHTML = 'Progress: 50%';
}, 250) // second parameter is how long u wanna wait for next action```
#

if you wanna use a button to start changing it, use a function

glad patrol
#

no a button

#

this is the file i have right now

#
</head>

<body class="demo-11">

  <div id="connecting-dots" class="connecting-dots">
    <canvas id="canvas"></canvas>
  </div>

  <div class="search search--open">

    <div class="terminal">
      <p class="terminal__line">Welcome:<span class="green">
          <</span><span class="green" id="ip"></span><span class="green">></span></p>
      <p class="terminal__line">The Attack is initiating...  <span class="country green"></span>?</p>
      <p class="terminal__line">Please Wait!</p>
      <p class="terminal__line">Crafting Packets</p>
      
      <p class="terminal__line"><a href="#" >Prog: 0% </a></p>  
      <p class="terminal__line"><a href="#">Prog: 25%</a></p>
      <p class="terminal__line"><a href="#">Prog: 50%</a></p>
      <p class="terminal__line"><a href="#">Prog: 70%</a></p>
      <p class="terminal__line"><a href="#">Prog: 100%</a></p>
      <p class="terminal__line"><a href="#">Please Wait...</a></p>
      <p class="terminal__line"><a class="out" href="#">Please Wait...</a></p>
      <p class="terminal__line">Initiating... <span class="console"></span></p>
      <div class="results" onload="receive_data();"></div>
    </div>

</html>```
lucid marsh
#

put the js code on a function, then call it with a button with html <button onclick="startProgressFunction()">Start progress</button>

glad patrol
#

i need to do without button

#

like they print auto after sleep

lucid marsh
#

thats all i can do for now unfortunately coz its night time and i gotta sleep

glad patrol
#

😦

lucid marsh
#

All u need to do is just some optimization on the code

glad patrol
#

i try not working

lucid marsh
#

Did u add the js code?

glad patrol
#

ya

lucid marsh
#

Thats weird

glad patrol
#
<script>
document.getElementById('prog').innerHTML = 'Progress: 0%';
setTimeout(function(){
  document.getElementById('prog').innerHTML = 'Progress: 50%';
}, 250)
</script>

</head>

<body class="demo-11">

  <div id="connecting-dots" class="connecting-dots">
    <canvas id="canvas"></canvas>
  </div>

  <div class="search search--open">

    <div class="terminal">
      <p class="terminal__line">Welcome:<span class="green">
          <</span><span class="green" id="ip"></span><span class="green">></span></p>
      <p class="terminal__line">The Attack is initiating...  <span class="country green"></span>?</p>
      <p class="terminal__line">Please Wait!</p>
      <p class="terminal__line">Crafting Packets</p>
      <p id="prog" class="terminal__line"><a href="#">'Progress: 0% '</a></p>
      <p id="prog" class="terminal__line"><a href="#">'Progress: 10% '</a></p>
      <p class="terminal__line"><a href="#">Please Wait...</a></p>
      <p class="terminal__line"><a class="out" href="#">Please Wait...</a></p>
      <p class="terminal__line">Initiating... <span class="console"></span></p>
      <div class="results" onload="receive_data();"></div>
    </div>```
lucid marsh
#

You need to change the id on document.getElementById

#

To the element u wanna edit

glad patrol
#

its already prog

lucid marsh
#

Make the script on thr bottom

#

It often cannot get element object cuz it didnt exist before the script

glad patrol
#

like this

#
   <p id="prog" class="terminal__line"><a href="#">'Progress: 0% '</a></p>
      <p id="prog" class="terminal__line"><a href="#">'Progress: 10% '</a></p>
      <p class="terminal__line"><a href="#">Please Wait...</a></p>
      <p class="terminal__line"><a class="out" href="#">Please Wait...</a></p>
      <p class="terminal__line">Initiating... <span class="console"></span></p>
      <div class="results" onload="receive_data();"></div>
    </div>

    <form class="search__form" action="">
      <input class="search__input" id="search__input" name="search" placeholder="Command Line" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"></input>
    </form>
  </div><!-- /search -->
</body>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.19.1/easing/EasePack.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.19.1/TweenLite.min.js"></script>
<script>
document.getElementById('prog').innerHTML = 'Progress: 0%';
setTimeout(function(){
  document.getElementById('prog').innerHTML = 'Progress: 50%';
}, 250)
</script>
</html>```
lucid marsh
#

Btw, you have another hyperlink element inside the element with prog id

glad patrol
#

remove that 1 ?

#

<p id="prog" class="terminal__line"><a href="#">'Progress: 0% '</a></p>

#

can you pls edit this line i will do rest

lucid marsh
#

<p class="terminal__line"><a id="prog" href="#">'Progress: 0% '</a></p>

glad patrol
#

1 mint

lucid marsh
#

Im on mobile its kinda hard lol

glad patrol
#

rest the js is fine now?

lucid marsh
#

Its fine

glad patrol
#

i will try 10sec

#

its still go so fst

#

fast

lucid marsh
#

Itll change 250 miliseconds after u start page

glad patrol
#

its miliscond

#

or second

lucid marsh
#

Milisecond

glad patrol
#

can we change it to seconds

lucid marsh
#

Yes,change 250 on the js to 1000 to make it 1 second

#

1 second is 1000 milisec

fossil pond
#

My CSS was not working on my AWS RDP but after doing some digging I found that I have to add this to settings.py:
STATIC_ROOT = "/var/www/example.com/static/"
How do I implement this if I have multiple static files in multiple apps in the same Django project?

opaque rivet
opaque rivet
opaque rivet
fossil pond
#

HTML would still be inside templates right?

opaque rivet
#

also note in production if you have DEBUG=False then Django will not serve the staticfiles anyway

fossil pond
#

I thought I have to set it to false during production

opaque rivet
#

Yeah that's right

fossil pond
#

So my only way out is S3?

opaque rivet
#

Django server can still serve templates. Just serve staticfiles with S3.

#

I'm sure there's other ways, it's just one way about things

#

Django docs give examples on how to serve staticfiles in production

fossil pond
tulip beacon
#

hey guys, why is this happening to the text?

opaque rivet
#

Np, if you do decide to go S3 I've been working with it today so I can help while the knowledge is fresh

opaque rivet
fossil pond
tulip beacon
opaque rivet
tulip beacon
opaque rivet
# fossil pond I read the django docs and I feel I should go with S3

Ok, here's some resources:
https://www.youtube.com/watch?v=ahBG_iLbJPM
and go with this package:
https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html

whenever you collectstatic all of the staticfiles that it collects in your STATIC_ROOT will be uploaded to S3 automatically.
One thing I didn't understand today is how my backend has access to my S3 files but if I visit the file in my browser I don't 🤷‍♂️

In this Django tut we look at the media and static files, configuring then within a development environment. We create a small project to showcase the media folder and using static files in Django then go ahead to serve Django files from the AWS S3 service. This tutorial assumes you are new to AWS and provides instruction on how to get started w...

▶ Play video
tulip beacon
#

@opaque rivet shall I send the css file?

opaque rivet
#

your input is probably taking too much width

#

leaving not enough horizontal space for the text

tulip beacon
#
.post-span{
    position: absolute;
    left: 800px;
    top:100px;
    color: rgb(100, 38, 38);
    font-size: 20px;
}
#

this is the css if it helps

opaque rivet
fossil pond
#

Damn that's a long video

opaque rivet
#

and what about the container of the text

opaque rivet
tulip beacon
opaque rivet
#

div

#

something that contains the text

#

then what did you say had width: 100%? The container of the whole page? 😂

tulip beacon
#

oh k

#
.post{
    background-image: linear-gradient(rgb(152, 197, 214), rgb(128, 100, 204));
    width: 100%;
    height: 1850px;
}
opaque rivet
#

and what's post?

cerulean badge
#

what should i save in db after a successful payment in stripe when checkout.session.completed webhook is recieved?

tulip beacon
lavish prismBOT
#

Hey @tulip beacon!

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

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

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

https://paste.pythondiscord.com

opaque rivet
#

I know that it's a class... I want to know what it actually is

#

the background?

tulip beacon
#

yeah

opaque rivet
#

ok, well scrap all the absolute elements, and position them with flexbox

tulip beacon
#

shall I send the js code?

tulip beacon
#

I actually, positioned most of the elements with absolute😅

fossil pond
opaque rivet
#

ngl I don't even know what STATIC_URL does

opaque rivet
opaque rivet
#

I use tailwindcss (like bootstrap) and have responsive classes. Nice n easy

fossil pond
tulip beacon
opaque rivet
tulip beacon
opaque rivet
tulip beacon
arctic adder
mild stump
#

Hello friends. I am new in Django

I need a help related to forign key.
Here i have 2 tables.

class Product_type(models.Model):
product_name = models.CharField(max_length=200)
def str(self):
return self.product_name

class Product_details(models.Model):
product_type = models.ForeignKey(Product_type, blank=True, null=True, on_delete=DO_NOTHING)
company_name = models.CharField(max_length=200)
description = models.TextField(blank=True)
price = models.IntegerField(default=0)
photo = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True)
memory = models.CharField(max_length=100, blank=True)
display = models.CharField(max_length=100, blank=True)
camera = models.CharField(max_length=100, blank=True)
battery = models.CharField(max_length=100, blank=True)
processor = models.CharField(max_length=100, blank=True)

def str(self):
return self.company_name

I want to save data in Product_details table

p = Product_details(product_type = __________________,
company_name = Name[k].get_text(),
photo = filename,
description = Name[k].get_text(),
price = Price[k].get_text().replace("₹",'').replace(",",'').strip(),
memory = Ram[i].get_text(),
display = Ram[i+1].get_text(),
camera = Ram[i+2].get_text(),
battery = Ram[i+3].get_text(),
processor = Ram[i+4].get_text())

p.save()

fill the blanks ______________

🙂

sudden steeple
#

Does anyone know how long one should make a session last?

#

I'm just using the built in flask permanent_session_lifetime

lavish prismBOT
#

Here's how to format Python code on Discord:

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

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

worn zenith
#

I've been waiting for 30 minutes to install Django. Is this normal?

worn zenith
#

Can I just ctrlc + c it and try to install it again?

versed python
#

How are you installing it?

#

Yeah

worn zenith
versed python
#

Maybe also restart your pc

#

And clear pip cache

worn zenith
versed python
#

Don't remember the exact command

#

Just search it up

worn zenith
#

k

#

ty

fossil pond
opaque rivet
#

you gave the css files the right src right?

#

to the S3 bucket

#

@fossil pond

fossil pond
opaque rivet
#

so... is that a yes? What is the href of your link tags in the html page?

fossil pond
opaque rivet
#

right, go to your html file, what is the href of your link tags

fossil pond
#

{% static 'main/base.css' %}

opaque rivet
#

okay, well that's not going to work because that points locally

#

it has to point to the s3 bucket

fossil pond
#

I thought the static tag would do it

#

That's how I did it as well as the guy in the vid

opaque rivet
#

I'm not entirely sure on what the static template tag does. It might be linked with STATIC_URL so you could change it to your s3 bucket URI and see what the href is then.

fossil pond
#

This is the static url 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION)

opaque rivet
#

In your templates, use the static template tag to build the URL for the given relative path using the configured STATICFILES_STORAGE.

#

okay so it builts the URL for staticfiles

#

so, go to your html file in the browser, inspect the DOM and see what the href is

fossil pond
#

I got access denied when i tried to access the STATIC_URL via the browser. I had it printed.

fossil pond
opaque rivet
#

yeah but surely your django project serves a template?

fossil pond
#

lemme see

opaque rivet
#

even if it's local

#

I just want to see the href of the link tag

fossil pond
opaque rivet
#

ok, so the path is correct?

opaque rivet
#

inspect element > network
refresh the page see the http status code of those files

fossil pond
#

(i changed the name a bit for security hehe)

opaque rivet
#

also... did you setup permissions for your s3 bucket?

opaque rivet
#

hmm...

#

S3FullAccess?

fossil pond
fossil pond
#

i am getting 404 but those are from firebase integrations that i need to remove xD

#

nothing from css

#

[26/Aug/2021 18:19:58] ?[m"GET / HTTP/1.1" 200 5738?[0m

#

this is the only one that I'm getting that might be of any relevance

opaque rivet
#

press the "all" tab

#

to see all requests

fossil pond
#

In postman?

opaque rivet
#

I use firefox, might be different, but there should be a tab somewhere so you can see all the requests

#

also @fossil pond do you have this in settings.py?
AWS_DEFAULT_ACL = 'public-read'

#

if it still doesn't work, I'd remake a new bucket, ensure you have a group to that bucket and a user with S3FullAccess permissions.

#

ensure that the right credentials are in settings.py, re-collectstatic and it should... work

rare lagoon
#

What is Flask used for? I know that is like a web server? But why would you host a web server instead of the webpage's files?

quick cargo
rare lagoon
#

So Js basically gives the functionality to make so the pages does something? Say for example, connect to a web framework?

sick notch
#

Flask "builds" the web page

quick cargo
#

well thats a small part of flask with it's templating system

loud cipher
#

anyone know how im able to compile different react apps to multiple html pages and then use them with a web framework such as flask or fast api

#

maybe using webpack

fossil pond
opaque rivet
#

@loud cipher next.js has that feature

fossil pond
#

Yeah maybe issue with bucket

#

If the request is being hit

#

Does the link look legit to you?

fossil pond
#

Like the static link

opaque rivet
#

Looks legit to me. You can double check by going into your bucket and checking the URI of a resource

thorn igloo
#

it will generate static files in the build directory

ionic raft
#

Is anyone familiar with docker here?

quick cargo
ionic raft
# quick cargo whats up

I have a bit of a problem with my container. it's on an app server that I've rebuilt. The postgres DB is on another server. However, when I run docker-compose logs I get

django.core.exceptions.ImproperlyConfigured: "'django.db.backends.postgresql_psycopg2'" isn't an available database backend or couldn't be imported. Check the above exception. To use one of the built-in backends, use 'django.db.backends.XXX', where XXX is one of:
web_1    |     'mysql', 'oracle', 'postgresql', 'sqlite3'```
At the end of the trackback...
quick cargo
#

thats not a docker thing

ionic raft
#

The problem started with a 500 Server Error on the front end when logging in as a superusert

quick cargo
#

your django config is invalid as it says

#

your set django backend is currently 'django.db.backends.postgresql_psycopg2'

#

but thats incorrect

ionic raft
#

Oh dear...
but nothing has changed since the last build...now it doesnt work

quick cargo
#

it needs to be 1 of 'mysql', 'oracle', 'postgresql', 'sqlite3'

#

e.g. django.db.backends.postgresql

quick cargo
#

and your docker container is on Django 3

ionic raft
#

No. Both latest version. Thjis build is days old

quick cargo
#

cant work on your dev version then

ionic raft
#

Ill have to wait for the guy who helped me. This is absolutely hosed as is

quick cargo
#

cuz that config option (postgresql_psycopg2) as a Django 1 thing and has been depreciated since 2 and removed since 3

ionic raft
#

I can't get to the postgres to setup a new superuser. And the signin to the superuser in returns a 500.

quick cargo
#

yes

#

because the backend is invalid

#

postgresql_psycopg2 isnt a thing anymore

#

its just postgresql

ionic raft
#

So maybe try the following:
DB_ENGINE='django.db.backends.postgresql'

quick cargo
#

try it and see

ionic raft
quick cargo
#

whats the error now

ionic raft
# quick cargo whats the error now

Only made a change to the .env file (I'm a bit out of my depth on this)....web_1 | django.core.exceptions.ImproperlyConfigured: "'django.db.backends.postgresql'" isn't an available database backend or couldn't be imported. Check the above exception. To use one of the built-in backends, use 'django.db.backends.XXX', where XXX is one of: web_1 | 'mysql', 'oracle', 'postgresql', 'sqlite3' web_1 | [2021-08-26 13:25:13 -0700] [9] [INFO] Worker exiting (pid: 9) web_1 | [2021-08-26 20:25:13 +0000] [7] [INFO] Shutting down: Master web_1 | [2021-08-26 20:25:13 +0000] [7] [INFO] Reason: Worker failed to boot.

quick cargo
#

what are the logs above that message

ionic raft
quick cargo
#

you gotta send all the logs

ionic raft
#

!paste

lavish prismBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

ionic raft
ionic raft
ionic raft
quick cargo
#

whats the code

#

this is in a env right?

ionic raft
quick cargo
#

are you aware that you dont wrap it in ''

ionic raft
#

That's not changed

quick cargo
#

cuz to the program it will be literally look like "'foo'"

ionic raft
#

I don't understand how suddenly the single quote wrap now breaks

quick cargo
#

shrug Idk how the original stuff even ran if you wernt on Django 2

#

in the env

quick cargo
#

so do you pass this via the config

#

or via the env

ionic raft
fossil pond
lucid marsh
ionic raft
#

OK. Are there any suggestions on the most straight forward approach to deploy a Django website? I've tried Apache. Didn't go well. I had a lot of help on a Docker install. But the process is broken and I don't know why.

I would love to have an staging server for the application and a DB server on Postgres (to separate DB). I need to be able to continue to develop and push to the staging server while I work through the alpha versions.

What recommendations are there? I am thinking NGinx/Postgres/Gunicorn on Ubuntu 20.04 may be the way to go. I really wanted Docker to work. The concept is brilliant. My experience with execution however has been less than ideal.

On the plus side, I know a bit more about Ubuntu 20.04. I have a Linode snapshot up and running for the staging server.

rustic sky
#

Does anyone here know how to change the location of the static files for the ADMIN dashboard in Django?

proper hinge
ionic raft
# proper hinge Well yeah I'd say the most straight forward way is Docker/Docker compose. Provis...

Well, I was using the front-end, testing. And suddenly, I got a 500 Server Error when signing in as the superuser. I could still signup/in as any other user.
After search in vain I ended up wiping the staging server and rebuilding the container. However, it's now not connecting as it was before. Since that 500 Server Error I've been locked out of the DB.
I've been able to get into the DB behind the scenes, but unfortunately, only one container of 2 appears to be up. So, I can't get in to the DB from the staging server

#

In effect, the container that worked perfectly before that 500 Server Error is now not working

#

I cannot for the life of me understand how the 500 error came up for the superuser while testing the front end

#

The rest of the DB functionality was working flawlessly btws

proper hinge
#

Were you using compose for that

ionic raft
#

HEre is the requirements.txt file that the docker-compose.ywl file EXPLICTLY calls

certifi==2021.5.30
charset-normalizer==2.0.4
Django==3.2.5
django-admin-honeypot==1.1.0
django-bootstrap-datepicker==1.4.0
django-ckeditor==6.1.0
django-cors-headers==3.7.0
django-crispy-forms==1.12.0
django-filter==2.4.0
django-js-asset==1.2.2
gunicorn==20.1.0
idna==3.2
Pillow==8.3.1
python-dotenv==0.15.0
pytz==2021.1
requests==2.26.0
six==1.16.0
sqlparse==0.4.1
stripe==2.60.0
urllib3==1.26.6```
#

So when the log tells me there is no django when there is, then the log looks like a red-herring to me.
It's the DB side of things that has me most puzzled.. That bloody 500 Server Error while testing....alarming to be honest

proper hinge
#

I think it's just a misleading error. The actual problem is the lower traceback

ionic raft
#

When I get a 500 Server Error for a superuser sign in, and can still signup/signin as another user? And ALL other DB functionality works?

proper hinge
#

Do you have the logs for the 500 error

ionic raft
# proper hinge Do you have the logs for the 500 error

Unfortunately no. Because a cascade of errors led me to simply figure, I'll rebuild the server and the container right...
Nope...wrong. Because since that rebuild...the staging server apparently cannot connect to the DB server. I've validated that the DB account in the .env.prod file is on the DB

ionic raft
proper hinge
#

And you can't reproduce cause now the service won't even come up?

ionic raft
#

I now get this on docker-compose logs: https://paste.pythondiscord.com/ovimagoxaw.sql

And bear in mind, this is after a completely fresh install of the server. I clone the git repo, and then apt install docker-compose docker-compose up --build -d docker-compose logs (check it is running)

#

And I've rebuilt the staging server 3 times. Same log errors.

Unfortunately, I can open a postgres session on the DB server. But I can't find the _web container to open the DB from there and try to connect. But the logs appear consistent with that in that they appear to say that the DB can't be connected to

#

I'm gutted to be frank.

#

a 500 Server Error on a superuser signin? I mean...what. the. actual. F...

proper hinge
#

The immediate error doesn't seem difficult to fix. You just need to correct the engine in your Django settings

ionic raft
#

Right. Except the .env.prod settings are unchanged. The DB server has the same IP.

proper hinge
#

What's the configured engine?

#

The error leads me to believe it is django.db.backends.postgresql_psycopg2

ionic raft
#

So I'm not sure what to correct. The docker-compose.yml and dockerfile did not change because of the 500 SE.

ionic raft
proper hinge
#

But quick research shows that it has been deprecated since django 2.0 and was completely removed in Django 3.0

ionic raft
manic warren
proper hinge
#

It shouldn't have, if you were using 3.0. It was somehow not running the correct version of Django I guess. I am not sure why it was working, but it's not like you need it to be postgresql_psycopg2 instead of postegresql. You can spend hours trying to figure it why it used to work but that ultimately seems like a waste of time

ionic raft
#

That also fails

#

Same error

manic warren
#

tell me i am doing django for 0.5 years

proper hinge
#

Same as in, it still says postgresql_psycopg2 isn't available despite you explicitly setting the engine to postgres? Or does it now say postgres is unavailable?

ionic raft
#

No, the error message changes. It says that postgres isn't available. Which is laughable as an error traceback

manic warren
#

whats your problem

ionic raft
#

It literally says...postgres isn't available after having postgres in the call

proper hinge
#

I misspelled it it's supposed to be postgresql. More specifically, ```py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',

ionic raft
ionic raft
proper hinge
#

But it's still the same error

#

?

#

If that's the case then yeah I would be stumped

manic warren
#

did you change the django default db

ionic raft
manic warren
ionic raft
# manic warren did you change the django default db

The settings file calls on the .env.prod file, and it's configured to use the postgres:

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

Have you isolated this issue to Docker? Does it work outside of Docker? I don't think it has anything to do with DB corruption considering it cannot even load the mechanism used to establish a connection to the DB

ionic raft
#

Which calls env.prod```
DB_ENGINE='django.db.backends.postgresql_psycopg2'

DB_ENGINE='django.db.backends.postgresql'

DB_NAME='lanesflow'
DB_USER='lanesflow'
DB_HOST='HIDDEN'
DB_PORT='5432'```

#

^ I've changed the above to remove the _psycopg2 and get the same error but matching that name

#

It literally says, can't find postgresql when I have 'django.db.backends.postgresql' in env.prod

#

None of that code changed. Then, 500 Server Error. Now, after rebuild...completely broken deployment

#

500 Server Error on a superuser signin, when all other aspects of DB are working...mystifying

manic warren
#

you should change db back to sql

ionic raft
ionic raft
#

But if that works, it would only prove that the Postgres DB is somehow broken

#

Which does not excite me in the slightest

proper hinge
#

Ah you know what I think the ModuleNotFoundError: No module named "'django" shouldn't be ignored after all. I think what's going on is it wants to load the backend, so it has to import it. But for some reason it fails to even import django? Not sure why though.

ionic raft
#

This is a 2 day old deployment btw...a broken DB so quickly...

manic warren
#

no db.sqlite3 is auto genrated

ionic raft
manic warren
#

did you create models

#

in django

ionic raft
manic warren
#

now go to /admin

ionic raft
#

that's the problem...this is not a simple Django web application

proper hinge
manic warren
#

enter your superuser detail

ionic raft
ionic raft
# proper hinge Might be some environment issue with how dependencies are being installed or how...

ENV PYTHONUNBUFFERED 1
ENV PYTHONDONTWRITEBYTECODE 1

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

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

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

COPY . .
# RUN python manage.py migrate

EXPOSE 8000
# RUN python manage.py collectstatic -c --noinput
RUN mkdir -p build/static
RUN python3 manage.py collectstatic -c --noinput

RUN chmod 777 $APP_HOME

CMD gunicorn Lanesflow.wsgi -b 0.0.0.0:8000
manic warren
#

first activate you enviroment

ionic raft
manic warren
#

there is no python venv

#

and you using django

#

how

ionic raft
#

Docker doesn't need a venv. It's an isolated container

#

Docker concept is BRILLIANT.

#

Implementing it....apparently a PITA

proper hinge
#

So, I don't immediately see any problems but I can try to mess around with it and see if I can find something.

#

Can't say I ever experienced this sort of problem when deploying stuff with Docker

ionic raft
#

The part that saddens me...for a glorious day...it was working BEAUTIFULLY.

#

It was SO FAST

proper hinge
#

As for your original question, yeah you can set up nginx and postgres directly without Docker but I don't quite know how to configure all of that. I use the Docker containers cause I'm a simpleton that likes the abstraction

ionic raft
#

And now...back to school I think. I'm going to have to learn how to build CI/CD from the ground up. I want to be bloody coding...not DevOps. But I won't get this application out there without working it out

#

Someone brilliant really needs to solve the problem of making deploying Django web apps accessible. These hoops....brutal

manic warren
#

you should not create django app in docker

proper hinge
#

Why not?

ionic raft
#

I would pay money to have this deployment process simplified. What I'm going through...the time I am wasting...

dusk portal
#

@ionic raft hey r u up?

proper hinge
#

@ionic raft lol I figured out the problem. It was in the traceback all along. The problem is that your env file uses quotes, but these quotes are read literally and included in the value. env files don't actually need quotes for strings

ionic raft
proper hinge
#

Yes but still use the lower one cause the upper is at least deprecated and at worst completely gone from django 3

ionic raft
proper hinge
#

Remove quotes from everything

ionic raft
inland oak
#

huh. in linux it works with '

proper hinge
#

Maybe some stuff works with quotes and others doesn't

#

I don't think it's needed for anything though

ionic raft
inland oak
#

no quotations is allowed too though

ionic raft
proper hinge
#

We don't know what library is actually being used to load the .env file

#

docker-compose is a Python app so it could be using that, but from testing I saw that it preserved the quote at least for the engine

inland oak
#

or may be some older docker compose version did not support ' quotations for environments

#

that is where could have arraised the problem

ionic raft
lapis stratus
#

Hello, I'm using ReactJS in the Front-End, the backend is django and I want to fetch a data from POSTMAN but whenever I do post request I get this error POST http://127.0.0.1:8000/auth/users net::ERR_CONNECTION_REFUSED

ionic raft
#

So...somehow it's coming down to password authentication error...Which is astonishing given that I'm using a password manager...

#

OK. If I open a postgres session I can change the password for a user correct?

ionic raft
#

I'm currently have a session open...

#

But that's not the user table...

inland oak
ionic raft
#

Why I'm getting a 500 Server Error on a password fail...first question...
Second question, password fail on password manager???

#

shakes head This whole business....astonishing

proper hinge
inland oak
#

how many times I should repeat 😉

#

and just check a detailed error

ionic raft
inland oak
#

good

ionic raft
#

However, HOW a failed password gives 500 Server Error....that is astonishing

#

That can't be right...at any rate..testing