deploy app django digitalocean

Correct. You pick which you want to use.

so after I install and run this command, I get this little error

uvicorn OrderLine1.asgi:application --host 0.0.0.0 --port 8080

Traceback (most recent call last):
  File "/home/wahab/apporder/env/bin/uvicorn", line 8, in <module>
    sys.exit(main())
  File "/home/wahab/apporder/env/lib/python3.10/site-packages/click/core.py", line 1130, in __call__
    return self.main(*args, **kwargs)
  File "/home/wahab/apporder/env/lib/python3.10/site-packages/click/core.py", line 1055, in main
    rv = self.invoke(ctx)
  File "/home/wahab/apporder/env/lib/python3.10/site-packages/click/core.py", line 1404, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "/home/wahab/apporder/env/lib/python3.10/site-packages/click/core.py", line 760, in invoke
    return __callback(*args, **kwargs)
  File "/home/wahab/apporder/env/lib/python3.10/site-packages/uvicorn/main.py", line 404, in main
    run(
  File "/home/wahab/apporder/env/lib/python3.10/site-packages/uvicorn/main.py", line 569, in run
    server.run()
  File "/home/wahab/apporder/env/lib/python3.10/site-packages/uvicorn/server.py", line 60, in run
    return asyncio.run(self.serve(sockets=sockets))
  File "/usr/lib/python3.10/asyncio/runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "/usr/lib/python3.10/asyncio/base_events.py", line 646, in run_until_complete
    return future.result()
  File "/home/wahab/apporder/env/lib/python3.10/site-packages/uvicorn/server.py", line 67, in serve
    config.load()
  File "/home/wahab/apporder/env/lib/python3.10/site-packages/uvicorn/config.py", line 474, in load
    self.loaded_app = import_from_string(self.app)
  File "/home/wahab/apporder/env/lib/python3.10/site-packages/uvicorn/importer.py", line 21, in import_from_string
    module = importlib.import_module(module_str)
  File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 883, in exec_module
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "/home/wahab/apporder/./OrderLine1/asgi.py", line 18, in <module>
    from myapp.routing import websocket_urlpatterns
  File "/home/wahab/apporder/./myapp/routing.py", line 3, in <module>
    from . import consumers
  File "/home/wahab/apporder/./myapp/consumers.py", line 2, in <module>
    from myapp.models import *
  File "/home/wahab/apporder/./myapp/models.py", line 3, in <module>
    from django.contrib.auth.models import User
  File "/home/wahab/apporder/env/lib/python3.10/site-packages/django/contrib/auth/models.py", line 3, in <module>
    from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
  File "/home/wahab/apporder/env/lib/python3.10/site-packages/django/contrib/auth/base_user.py", line 48, in <module>
    class AbstractBaseUser(models.Model):
  File "/home/wahab/apporder/env/lib/python3.10/site-packages/django/db/models/base.py", line 108, in __new__
    app_config = apps.get_containing_app_config(module)
  File "/home/wahab/apporder/env/lib/python3.10/site-packages/django/apps/registry.py", line 253, in get_containing_app_config
    self.check_apps_ready()
  File "/home/wahab/apporder/env/lib/python3.10/site-packages/django/apps/registry.py", line 136, in check_apps_ready
    raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

but before I had an error that I had to define DJANGO_SETTINGS_MODULE, so I did

export DJANGO_SETTINGS_MODULE=OrderLine1.settings

and the error disappeared but now I have another error (above), I do not know where it comes from

When trying to diagnose a traceback, the best place to start is any references to code that you’ve written.

There’s a block of four lines in here that appears to fit:

Now, generally speaking, this error is frequently caused by doing something at the module level that should be done inside a function. But what that something is isn’t necessarily obvious.

I like to start from the bottom up, because it is what has actually triggered the error. (The root cause may be higher up in the call stack, but we don’t know that yet.

Let’s start with your models.py - say the first 10 lines. (The exception is thrown on line 3, so it’s really unlikely for the cause to be past that.)

Then, post roughtly the first 10 lines of your consumers.py. (Looking for everything up to and including the first class definition.)

Then you might as well post your routing.py and asgi.py files. They should be small enough to post in their entirety.

if I understood correctly I should show you the code,

so here is my model.py*

from distutils.command.upload import upload
from django.db import models
from django.contrib.auth.models import User


# Create your models here.

class OrderLine1UserProfil(models.Model):
    ascount = models.OneToOneField(
        User, on_delete=models.CASCADE, null=True, blank=True)
    phone = models.CharField(max_length=255, blank=True)

my consumers.py

from typing import Generic
from myapp.models import *
from .serializers import HubriseOrderSerializer
from djangochannelsrestframework import permissions
from djangochannelsrestframework.generics import GenericAsyncAPIConsumer
from djangochannelsrestframework.mixins import ListModelMixin
from djangochannelsrestframework.observer import model_observer

class HubriseOrderConsumer(ListModelMixin, GenericAsyncAPIConsumer):

routing.py

from django.urls import re_path
from . import consumers

# websocket_urlpatterns = [re_path(r"^ws/$", consumers.PostConsumer.as_asgi())]
websocket_urlpatterns = [
    re_path(r"^ws/$", consumers.HubriseOrderConsumer.as_asgi())]

my asgi.py

import os

from django.core.asgi import get_asgi_application

from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
from channels.security.websocket import AllowedHostsOriginValidator

from myapp.routing import websocket_urlpatterns

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'OrderLine1.settings')

os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true"

testapp = get_asgi_application()

application = ProtocolTypeRouter({
    "http": testapp,
    "websocket": AllowedHostsOriginValidator(
        AuthMiddlewareStack(
            URLRouter(websocket_urlpatterns),
        )
    ),

})

In your asgi.py file, move the from myapp.routing import ... line to after the testapp = get_asgi_application() line. (See the example at Routing — Channels 4.0.0 documentation and the example in the tutorial at Tutorial Part 2: Implement a Chat Server — Channels 4.0.0 documentation)

Also, more as a “style / best-practices” issue and not a definite “problem” issue, I would suggest that you replace this line with specific references to the models being explicitly referenced in the consumer(s)

e.g. from myapp.models import Model1, Model2, Model3

so I did as you told me but there is always this error

my asgi.py

import os

from django.core.asgi import get_asgi_application
from channels.auth import AuthMiddlewareStack
from channels.security.websocket import AllowedHostsOriginValidator

from myapp.routing import websocket_urlpatterns

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'OrderLine1.settings')

os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true"

testapp = get_asgi_application()
from channels.routing import ProtocolTypeRouter, URLRouter

application = ProtocolTypeRouter({
    "http": testapp,
    "websocket": AllowedHostsOriginValidator(
        AuthMiddlewareStack(
            URLRouter(websocket_urlpatterns),
        )
    ),

})

(env) wahab@django411:~/apporder$ uvicorn OrderLine1.asgi:application --host 0.0.0.0 --port 8080


Traceback (most recent call last):
  File "/home/wahab/apporder/env/bin/uvicorn", line 8, in <module>
    sys.exit(main())
  File "/home/wahab/apporder/env/lib/python3.10/site-packages/click/core.py", line 1130, in __call__
    return self.main(*args, **kwargs)
  File "/home/wahab/apporder/env/lib/python3.10/site-packages/click/core.py", line 1055, in main
    rv = self.invoke(ctx)
  File "/home/wahab/apporder/env/lib/python3.10/site-packages/click/core.py", line 1404, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "/home/wahab/apporder/env/lib/python3.10/site-packages/click/core.py", line 760, in invoke
    return __callback(*args, **kwargs)
  File "/home/wahab/apporder/env/lib/python3.10/site-packages/uvicorn/main.py", line 404, in main
    run(
  File "/home/wahab/apporder/env/lib/python3.10/site-packages/uvicorn/main.py", line 569, in run
    server.run()
  File "/home/wahab/apporder/env/lib/python3.10/site-packages/uvicorn/server.py", line 60, in run
    return asyncio.run(self.serve(sockets=sockets))
  File "/usr/lib/python3.10/asyncio/runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "/usr/lib/python3.10/asyncio/base_events.py", line 646, in run_until_complete
    return future.result()
  File "/home/wahab/apporder/env/lib/python3.10/site-packages/uvicorn/server.py", line 67, in serve
    config.load()
  File "/home/wahab/apporder/env/lib/python3.10/site-packages/uvicorn/config.py", line 474, in load
    self.loaded_app = import_from_string(self.app)
  File "/home/wahab/apporder/env/lib/python3.10/site-packages/uvicorn/importer.py", line 21, in import_from_string
    module = importlib.import_module(module_str)
  File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 883, in exec_module
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "/home/wahab/apporder/./OrderLine1/asgi.py", line 16, in <module>
    from myapp.routing import websocket_urlpatterns
  File "/home/wahab/apporder/./myapp/routing.py", line 3, in <module>
    from . import consumers
  File "/home/wahab/apporder/./myapp/consumers.py", line 2, in <module>
    from myapp.models import HubriseOrder
  File "/home/wahab/apporder/./myapp/models.py", line 3, in <module>
    from django.contrib.auth.models import User
  File "/home/wahab/apporder/env/lib/python3.10/site-packages/django/contrib/auth/models.py", line 3, in <module>
    from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
  File "/home/wahab/apporder/env/lib/python3.10/site-packages/django/contrib/auth/base_user.py", line 48, in <module>
    class AbstractBaseUser(models.Model):
  File "/home/wahab/apporder/env/lib/python3.10/site-packages/django/db/models/base.py", line 108, in __new__
    app_config = apps.get_containing_app_config(module)
  File "/home/wahab/apporder/env/lib/python3.10/site-packages/django/apps/registry.py", line 253, in get_containing_app_config
    self.check_apps_ready()
  File "/home/wahab/apporder/env/lib/python3.10/site-packages/django/apps/registry.py", line 136, in check_apps_ready
    raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

Please reread my previous response and the referenced docs and examples.

I need my websocket to be directly in my asgi? and not in my routing.py

What specifically did I recommend as the change to make in my earlier response?

to move

from channels.routing import ProtocolTypeRouter, URLRouter

after

testapp = get_asgi_application()

and also specify the model names to use when importing

oh my, I was wrong …

so thank you very much i don’t have this error anymore, but i just have a small question how do i see the error here, when I make this command

(env) wahab@django411:~/apporder$ sudo systemctl start gunicorn.socket

Job failed. See "journalctl -xe" for details.

because it tells me to type this command journalctl -xe, but then it sends me this back

Nov 13 15:13:56 django411: wahab : TTY=pts/0 ; PWD=/home/wahab/apporder ; USER=root ; COMMAND=/usr/bin/systemctl start gunicorn.socket
Nov 13 15:13:56 django411: pam_unix(sudo:session): session opened for user root(uid=0) by root(uid=1000)
Nov 13 15:13:56 django411: pam_unix(sudo:session): session closed for user root

, without giving me any details

Usually, when a systemd process fails, the error message identifies two commands that can be run to show information.

However, it is possible that if the systemd file is sufficiently malformed, that there’s no way for systemd to provide any useful information.

First step then is to examine your gunicorn.socket file carefully.

(Note, since you’re using either daphne or uvicorn and not gunicorn, you probably want to pick a different name for your service.)

yet in this documentation it uses gunicorn.socket

That’s their choice. I merely offered that note as a recommendation.

ah ok thanks, but then the error would come from gunicorn.socket, yet I think I followed the documentation well

(env) wahab@django411:/etc/systemd/system$ cat gunicorn.socket

[Unit]
Description=gunicorn socket

[Socket]
ListenStream=/run/gunicorn.sock

[Install]
WantedBy=sockets.target

apparently there was no change to add

i have a question

[Unité]
Description=gunicorn daemon
Requires=gunicorn.socket
After=network.target

[Service]
Utilisateur=wahab
Groupe=www-data
WorkingDirectory=/home/wahab/apporder
ExecStart=/home/wahab/apporder/env/bin/gunicorn \
          --access-logfile - \
          -k uvicorn.workers.UvicornWorker \
          --workers 3 \
          --bind unix:/run/gunicorn.sock \
          orderline1.asgi:application

[Installer]
WantedBy=multi-user.target

here it is well the file which contains the settings.py, asgi.py …, that one must put ?

orderline1.asgi:application

This has been a learning experience for me, too.

Regarding the gunicorn.socket file, I’m seeing the same behavior on my test system.

The journalctl -xe command yields the following:

Nov 13 16:58:43 docchan systemd[1]: gunicorn.socket: Socket service gunicorn.service not loaded, refusing.
Nov 13 16:58:43 docchan systemd[1]: Failed to listen on gunicorn socket.
░░ Subject: A start job for unit gunicorn.socket has failed
░░ Defined-By: systemd
░░ Support: http://www.ubuntu.com/support
░░ 
░░ A start job for unit gunicorn.socket has finished with a failure.
░░ 
░░ The job identifier is 17558 and the job result is failed.

which is the same error message as what’s showing up in syslog.

This led me down the rabbit hole of systemd docs to understand what’s going on.

Anyway, what I learned from this is that a systemd file named <whatever>.socket must have an associated file <whatever>.service defined as well. (Documented at Ubuntu Manpage: systemd.socket - Socket unit configuration among numerous other locations.)

Creating your gunicorn.service file resolves this issue.

but still I create them look

wahab@django411onubuntu2204-s-1vcpu-1gb-amd-ams3-01:/etc/systemd/system$  ls
cloud-final.service.wants                   emergency.target.wants  mdmonitor.service.wants         rescue.target.wants     snap-snapd-17336.mount            sshd-keygen@.service.d
cloud-init.target.wants                     final.target.wants      multi-user.target.wants         sleep.target.wants      snap.lxd.activate.service         sshd.service
dbus-org.freedesktop.ModemManager1.service  getty.target.wants      multipath-tools.service         snap-core20-1518.mount  snap.lxd.daemon.service           sudo.service
dbus-org.freedesktop.resolve1.service       graphical.target.wants  network-online.target.wants     snap-core20-1695.mount  snap.lxd.daemon.unix.socket       sysinit.target.wants
dbus-org.freedesktop.timesync1.service      gunicorn.service        open-vm-tools.service.requires  snap-lxd-22923.mount    snap.lxd.user-daemon.service      syslog.service
default.target.wants                        gunicorn.socket         paths.target.wants              snap-lxd-23541.mount    snap.lxd.user-daemon.unix.socket  timers.target.wants
droplet-agent.service                       iscsi.service           redis.service                   snap-snapd-16292.mount  sockets.target.wants              vmtoolsd.service

And you’re still getting the error?

What are the messages you get when you try to start the gunicorn.socket service?

What are the messages showing in syslog? (Or the complete message from journalctl -xe)

What are the current and complete contents of the gunicorn.socket and gunicorn.service files?