DEV Community

ashrafZolkopli
ashrafZolkopli

Posted on

Django + Svelte = Best Dev Experience (DX)

I been a Django developer for about a year++ now, I'm not saying I am well verse in it or do I intent to claim so... There's so many to learn and each and everyday I learn something new... So much so that I think I could never finish learning the whole Django framework and how much it struck me that no matter what, Django been able to keep me amaze.

Anyway, one thing about Django that I wish I can improve upon is its templating system... Shall I say its a bit too 'static' ? It has the power to become much more with its templating system, changing to Jinja2 really makes it that much more amazing... but to make a modern web application that rival most big website, I definitely think we need a proper Java Script(JS) framework.

My JS framework of choice happen to be the newest kid on the block (at the time of this writing) Svelte. I cant even begin to tell you how amazing this framework have been for me. Imagine how easy it is to have someone with minimum exposure to JS to quickly help get an app ready in a matter of minutes.

That said, I kinda have issues with getting both Django and Svelte to work together, I think this also applies to any other framework.
The solution I see online had been mostly involve getting 2 separate server (one for Node.js via Sapper/Routify (both consider as a good Svelte server solution) and Django as the API server) to communicate via API.

The fact is, I still haven't found a way to make it work via Django Templating system. So for the last 2 weeks I been experimenting with integrating both this wonderful framework and getting the best of both world.

If you ask me, what I'm gonna present here may not be the best solution, and some may say that this might not even be consider worth the effort. I honestly dont know or cant see if there is any issue that may arise from this, but time will tell if its the right path to take.

For those who just stumble upon this post due to svelte tag and didn't know about Django, I would like to elaborate what I like about Django ( mind you that I have no experience with other framework... I repeat Non.. So I'm not comparing with other and you may comment how other framework fair compare to Django).

Honestly, Django have this amazing tagline ( The Web Framework for perfectionist with datelines)... I have to say for the year that I been using Django its been holding up to its name. I had receive a task on a Friday evening, work on it on the weekends and still manage to deliver on the Monday morning. Mind you this is not some random toy project. Its a proper production ready project that is currently being use internally in the company that I work at right now. Some might argue that if its for internal use I might skim through some detail... such as securities and also proper audit... this project is being host on cloud, due to confidentiality of the information being kept on the web app, the web app being pentested and when to trial significantly before its being put to production. On a side note I think this web app is one of my proudest project.. I guess what I'm trying to say here is that battery included framework such as Django really help to speed up the project from an idea to finish product in a weekend. I know, I know, "What... you work on a weekend"... well as a dev sometime you need to make such sacrifice right?

Enough bragging about how awesome Django is for me right,
here's the part of the show and tell.

I would first make a disclaimer, I been an avid user of CoderedCMS. CoderedCMS as its name is, is a Content Management System (CMS) created by Codered. It is an extension of Wagtail CMS which is a framework build upon Django. I think the solution I would propose here would work with Django without much issue, but if you follow the project from start to end, I think you may be surprise at how powerful this solution really is.

For this solution to work also, I think, depending on your preference of frontend JS routing solution the experience might be different but take the propose solution here as a guideline not something that have been set in stone but I definitely prefer to Routify route. Honestly since Svelte3 is still a relatively new framework, there's isn't many tutorial yet compare to Angular, React or even Vue but that doesn't make it any less of a powerful framework. I would even bet that if many took the time to try this framework, you'll be surprise at how great the DX is.... sorry for bragging again.

1. Get your git ready

Alt Text

For this project I decide to make it public so you guys can just pull the project if you just wanna make use of it later.

2. Pull the project into your computer

Honestly, I might get a lot of burn here but I honestly been lazy with git command, so I been relying on GitHub desktop all this while...

Alt Text

clone this project....

now you can just open in your fav IDE, As for me its VS Studio.

Alt Text

just click on the open in VS Code.

btw this is the right time to check if your clone the repo right

compare your directory is similar to mine....

Alt Text

3. Lets setup a Virtual Environment for Python First

I been using pipenv but you may use any other virtual environment too though.. For me its just easier with pipenv....

pipenv shell
Enter fullscreen mode Exit fullscreen mode

enter this command in your terminal will create if new and activated virtual environment.
You should be able to see something like this....

Alt Text

Actually the important part is seeing that "( )" in the beginning of the line. It means now your virtual environment is activated.

now check too if your directory have change

Alt Text

as you can see there's a new pipfile... so if you follow this much once you clone this application, I would suggest you activate your pipenv virtual environment in the directory that you see pipenv is in.

4. Installing Codered CMS in the pipenv virtual environment

The only thing different with pipenv and pip is installing any python library is to change the

pip install coderedcms
Enter fullscreen mode Exit fullscreen mode

to

pipenv install coderedcms
Enter fullscreen mode Exit fullscreen mode

as you can see its the same command, just append env at the end of pip.. Hack I can usually copy the command to install any package and just append env at the end... talk about convenient . I read somewhere actually while in virtual environment you can actually use pip directly but I haven't try it and if I'm wrong hope someone could correct me.

Alt Text

actually if this is the first python you install in the library, the pipenv will create a new pipfile.lock file

Alt Text

5. Lets start a CoderedCMS project

The command for this would be

coderedcms start < project name >
Enter fullscreen mode Exit fullscreen mode

so for me, since I'm gonna name this project Django_Svelte ... No shit right, no creativity at all....

coderedcms start Django_Svelte
Enter fullscreen mode Exit fullscreen mode

Alt Text

looked at your directory now, it should change to

Alt Text

6. Lets change directory and Install Routify project template

Now since Routify (Svelte ) is a Node project, I would suggest you to open a new terminal to make it easier to change between python and Node

press the plus sign

Alt Text

notice now that you change the pipenv terminal to cmd...

Alt Text

once you are in the new terminal, change directory to

To change directory to Django_Svelte, the command is

cd Django_Svelte
Enter fullscreen mode Exit fullscreen mode

btw quick tip, type cd then space then the first latter, then just press tap for autocomplete....

Alt Text

once in the directory, we have to make a new directory, I will name this directory Svelte,

mkdir Svelte
Enter fullscreen mode Exit fullscreen mode

mkdir is the command to make directory

Alt Text

check the dir again

Alt Text

now lets change directory to Svelte with

cd Svelte
Enter fullscreen mode Exit fullscreen mode

Alt Text

we can now clone the Routify project with the command

npx @roxi/routify init
Enter fullscreen mode Exit fullscreen mode

we need to wait for a while yeah

Alt Text

now check for the ever increasing size of your directory....

Alt Text

7. Lets check if the Routify installation was successful

to run a dev server for Routify(Svelte) is

npm run dev
Enter fullscreen mode Exit fullscreen mode

Alt Text

lets see it activated in chrome,

the url for this would be

http://localhost:5000

Alt Text

Amazing so far,

Routify also included an example page with the url

http://localhost:5000/example

image

now that we know that the Routify(Svelte) portions works, lets make changes to Django so we change make Django Serve the application.

8. Django changes to serve Svelte

To simplify this show and tell, we could start with an app call example.

change back to terminal 1.pipenv

if you haven't change to Django_Svelte directory just type

cd Django_Svelte
Enter fullscreen mode Exit fullscreen mode

now we can start a new app call example with

python manage.py startapp example
Enter fullscreen mode Exit fullscreen mode

image

look at your directory now

image

so far not bad right....

let create a new file name urls.py

the directory should look like this

image

inside example/urls.py

add the code below

from django.urls import re_path
from django.views.generic import TemplateView
from . import views

urlpatterns = [
    re_path(r'^.*$', TemplateView.as_view(template_name="example/index.html"))
]
Enter fullscreen mode Exit fullscreen mode

image

now lets open the directory Django_Svelte/Setting/base.py

image

in the file base.py, first register example as one of the install app

INSTALLED_APPS = [
    # all the other already install app,
    'example',
]
Enter fullscreen mode Exit fullscreen mode

image

now lets edit the Templates setting to this

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'APP_DIRS': True,
        'DIRS': [
            BASE_DIR + '/Svelte/dist',
            BASE_DIR + '/templates',
        ],
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'wagtail.contrib.settings.context_processors.settings',
            ],
        },
    },
]
Enter fullscreen mode Exit fullscreen mode

image

now lets add STATICFILES_DIRS into base.py

STATICFILES_DIRS = [
    BASE_DIR + '/Svelte/dist',
] 
Enter fullscreen mode Exit fullscreen mode

image

Now lets change the Django_Svelte/urls.py file

image

add this line in the urlpatterns list

path('example/', include('example.urls')),
Enter fullscreen mode Exit fullscreen mode

image

I guess for now lets try starting the python dev server
since we havent actually try the server previously,
enter this command in the terminal

python manage.py makemigrations
python manage.py migrate
python manage.py runserver
Enter fullscreen mode Exit fullscreen mode

lets wait for the migrations work its magic touch

then lastly you would see this

image

lets open the link now

http://127.0.0.1:8000

btw quick tip, 127.0.0.1 have an alias of localhost

so

http://localhost:8000

works too

image

well remember we had also register example as our link?

try going to

http://localhost:8000/example

image

django throw us an error that Template does not exist...

now we have to make a bit of changes to our Routify(Svelte) part of the project

9. Configure Svelte to work with Django

first find the file Svelte/assets/__app.html

image

now lets make this changes to the file

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset='utf-8'>
    <meta name='viewport' content='width=device-width,initial-scale=1'>

    <title>Svelte app</title>

    <meta name="theme-color" content="#E938C2">
    <link rel="apple-touch-icon" href="images/touch-icons/logo-192.png">

    <link rel="manifest" href="/manifest.json">
    <link rel='icon' type='image/png' href="/favicon.png">
    <link rel='stylesheet' href="/build/bundle.css">
    <link rel="modulepreload" href="/build/main.js" />

    <script type="module" src="/build/main.js"></script>

    <link rel="apple-touch-icon" href="{% static 'images/touch-icons/logo-192.png' %}">

    <link rel="manifest" href="{% static '/manifest.json' %}">
    <link rel='icon' type='image/png' href="{% static '/favicon.png' %}">
    <link rel='stylesheet' href="{% static '/build/bundle.css' %}">
    <link rel="modulepreload" href="{% static '/build/main.js/' %}">

    <script type="module" src="{% static '/build/main.js' %}"></script>
</head>

<body>
    <noscript>Please enable Javascript for best experience.</noscript>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

image

once this is done

please check your terminal if your node dev server is still runnning if yes, we need to kill it first...

click on your keyboart ctrl+c

image

type Y

image

now your node server is done.

type this

npm run build
Enter fullscreen mode Exit fullscreen mode

you will see something like this

image

check if your python dev server is still running

image

lets go back to chrome and check if django can server the link

http://localhost:8000/example

image

perfect....

ok now for some caveat... if you need to make changes to the front end,

every time you wanna make changes to the page and want to be served by django,

please remember to build the application with

npm run build
Enter fullscreen mode Exit fullscreen mode

while your node server is running, django will not able to find the template so yeah that something to keep in mind.

I guess this is the right time to start a git commit so what you may clone my repo

10. Git Commit

I think this is the part where you should click on the source control tab on VS Code

image

image

as you see theres 126 changes that I havent commit to git

image

click on the stage plus (+) sign to commit all changes.... and add a title

image

then on the keyboard click

ctrl + enter

image

now this is been to committed to your local git...

now you need to push to github.com

image

this will sync between your local git to your github account

lets check

image

Your Are Done...

Phewww that was a long post... Honestly I didn't expect it to be this long it took me like 4 hours to write this pose hope it helps guys...

feel free to comment on this post if It help or you are requesting some help... Ill try to reply as soon as possible.

Thanks for making it up to this part.... I hope you enjoy this post as much as I enjoy writing it...

BTW before I forget, heres the repo

https://github.com/ashrafZolkopli/Django_Svelte

Thanks guys

Discussion (6)

Collapse
nathanael71 profile image
Nathanael

Hi Ashraf,
Thank you for this article. It is very informative and enjoyable to follow.
If I may, I want to ask about the routing part.

On project-level url pattern list, you add:

path('example/', include('example.urls'))

I want to serve the svelte-part on root url so I tried to adapt with:

path('', include('example.urls'))

My all urlpatterns are:

    path('admin/', admin.site.urls),
    path('', include('example.urls')),
Enter fullscreen mode Exit fullscreen mode

but when I build-run-open in browser: localhost:8000/admin,
The app seems to ignore my 'admin/' urlpattern and got handled by routify instead (which then show 404 error page because there's no 'admin/' routes configured on routify).

My question is: is it possible to let django serve svelte-routify on root url without ignoring other urlpattern rules on django's urls.py?

Thanks in advance

Collapse
ashraf_zolkopli profile image
ashrafZolkopli Author

Hi,

I received an answer from the Discord already.

Alt Text

with this, I made some changes to the configurations, and found that it is indeed possible to have Django server the request to admin page.

Alt Text

currently my url are as above.

then what I did was change the url to become

Alt Text

what I found was that the root was serve by Routify

Alt Text

while admin is being serve by django

Alt Text

I hope this helps...

Collapse
ashraf_zolkopli profile image
ashrafZolkopli Author

First of all sorry, for the late reply. I haven't been checking up with Dev.to in a while.

Honestly, I don't know. I haven't try it that way yet.
I will try to investigate if its possible to force the browser to stop SPA mode and make a request to the Django Server

Collapse
ashraf_zolkopli profile image
ashrafZolkopli Author

I asked the Routify Discord first if they have any idea on how to do it. If any update I will reply to this comment and/or update the tutorial

Collapse
max_dobeck profile image
Max

Thanks for the breakdown! πŸ‘This helped me get an similar example up and running, gitlab.com/mdpb/svelte-django-example

Collapse
ashraf_zolkopli profile image
ashrafZolkopli Author

Hey welcome.
Awesome Bro... I will looked into your app closely and learn from you too