Package: ellar-django-module
Ellar - Python ASGI web framework for building fast, efficient and scalable RESTful APIs and server-side application.IntroductionA simple way to add use Django ORM with EllarInstallationpipinstallellar-django-moduleSetupIf you are starting from scratch, then you need to scaffold a new project with ellar-cli as shown below:ellarnewmy_projectScaffolded project structuremy_project/
├─ my_project/
│  ├─ apps/
│  ├─ core/
│  ├─ domain/
│  ├─ config.py
│  ├─ root_module.py
│  ├─ server.py
│  ├─ __init__.py
├─ tests/
├─ pyproject.toml
├─ README.mdAfter scaffolding our ellar application, we need to set upDjangoModuleinmy_project/root_module.py# my_project/root_module.pyfromellar.commonimport(Module,exception_handler,IExecutionContext,JSONResponse,Response,)fromellar.coreimportModuleBasefromellar.samples.modulesimportHomeModulefromellar_djangoimportDjangoModule@Module(modules=[HomeModule,DjangoModule.setup(settings_module="my_project.config")])classApplicationModule(ModuleBase):@exception_handler(404)defexception_404_handler(cls,ctx:IExecutionContext,exc:Exception)->Response:returnJSONResponse(dict(detail="Resource not found."))TheDjangoModulesetup requires a string import of djangosettings.pyor any file that contains django settings.
This is important for django models definitions and django admins views to work properly. But for now, we have used path to ellar config file to avoid some django errors.It's also important to note thatDjangoModuleas added a wrapper around django cli tool. To verify this, still on your terminal, run the code below:ellardjango--helpThis should show you the result below:Usage:Ellar,PythonWebframeworkdjango[OPTIONS]Ellarwillalwaysinterceptandcommandwith'--help'.Soifyouwanttogethelponanydjangocommand,simplywrapthecommandand--helpinquotesForexample:ellardjango'migrate --help'Options:--helpShowthismessageandexit.Scaffolding Django ProjectNow that django cli works, we need to scaffold a django project. why?
Because we needsettings.pyandurl.pyprovided by djangostartprojectcommand but if you can create these files yourself and link them,
then I don't think you need this section.On the same terminal, run the command below:ellardjangostartprojectwsgi_django.In the command above, we specified.as the current directory to avoid creating a nested directory.
Also, we need to deletemanage.py,wsgi.py,asgi.pyand leave onlysettings.pyandurl.pyCurrent project structuremy_project/
├─ my_project/
│  ├─ apps/
│  ├─ core/
│  ├─ domain/
│  ├─ config.py
│  ├─ root_module.py
│  ├─ server.py
│  ├─ __init__.py
├─ tests/
├─ wsgi_django/
│  ├─ settings.py
│  ├─ urls.py
│  ├─ __init__.py
├─ pyproject.toml
├─ README.mdUpdate DjangoModuleSetupNow, we have asettings.pywith all required django settings inwsgi_django.settings. So lets apply that toDjangoModulesetup.fromellar.commonimport(Module,exception_handler,IExecutionContext,JSONResponse,Response,)fromellar.coreimportModuleBasefromellar.samples.modulesimportHomeModulefromellar_djangoimportDjangoModule@Module(modules=[HomeModule,DjangoModule.setup(settings_module="wsgi_django.settings",path_prefix='/-django-example')])classApplicationModule(ModuleBase):@exception_handler(404)defexception_404_handler(cls,ctx:IExecutionContext,exc:Exception)->Response:returnJSONResponse(dict(detail="Resource not found."))Django Database MigrationIt's about time to create some database. So as usual, we use djangomigratecommandellardjangomigrateOutput:Operationstoperform:Applyallmigrations:admin,auth,contenttypes,sessions
Runningmigrations:Applyingcontenttypes.0001_initial...OKApplyingauth.0001_initial...OKApplyingadmin.0001_initial...OKApplyingadmin.0002_logentry_remove_auto_add...OKApplyingadmin.0003_logentry_add_action_flag_choices...OKApplyingcontenttypes.0002_remove_content_type_name...OKApplyingauth.0002_alter_permission_name_max_length...OKApplyingauth.0003_alter_user_email_max_length...OKApplyingauth.0004_alter_user_username_opts...OKApplyingauth.0005_alter_user_last_login_null...OKApplyingauth.0006_require_contenttypes_0002...OKApplyingauth.0007_alter_validators_add_error_messages...OKApplyingauth.0008_alter_user_username_max_length...OKApplyingauth.0009_alter_user_last_name_max_length...OKApplyingauth.0010_alter_group_name_max_length...OKApplyingauth.0011_update_proxy_permissions...OKApplyingauth.0012_alter_user_first_name_max_length...OKApplyingsessions.0001_initial...OKStart ServerNow, that we have everything setup, we can start the serverellarrunserver--reloadIn the above example, we added/-django-exampleas path prefix. This is important because we need to group all django admin views
with a prefix and also to avoid unnecessaryPage Not Founderrors.We can visithttp://localhost:8000/-django-example/adminto see django Admin UI.Serving Django Static FilesIf you visited the Django Admin view, you will notice the css and javascript files all returned 404 error.
To fix this we need to installwhitenoisepackage.pipinstallwhitenoiseAfterward, we update the django settings with whitenoise middleware as shown blown...MIDDLEWARE=["django.middleware.security.SecurityMiddleware","whitenoise.middleware.WhiteNoiseMiddleware",...]...So when you visithttp://localhost:8000/-django-example/adminagain, the page should be functional.Creating a SuperuserAs you can see, we need to login to access the admin view. A quick way to do this is by creating
a superuser usingcreatesuperusercommand. So lets do this below:ellardjangocreatesuperuserFollow the prompts and use the created credentials to log in to django admin panel.