Django + Svelte = Best Dev Experience (DX) 
Tags: django, svelte, devops
Published: 2021-02-16 17:14:50

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u13olse765201t6vql0i.PNG)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/msuid0xfnno22am1n4lx.PNG)

clone this project....

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

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5f6bim8ngy0b2von1ac0.PNG)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q7xnsbcmphqqrnfqwkns.PNG)

##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 this command in your terminal will create if new and activated virtual environment.
You should be able to see something like this....

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jmjwai9vvvqdswuvov3u.PNG)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mutakxmazxlrawl26fge.PNG)

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 

```python
pip install coderedcms
```
to 

```python
pipenv install coderedcms
```

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hpfhk8vizpebj8gbnhz6.PNG)


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

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7sen32wqpeiiu16thsy6.PNG)


##5. Lets start a CoderedCMS project

The command for this would be 

```
coderedcms start < project name >
```

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

```
coderedcms start Django_Svelte
```

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0u9y8kyp6oi1h903mc87.PNG)

looked at your directory now, it should change to

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/32cm2yqwvczricjntfwp.PNG)

##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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o166stgaovg7svahw3o7.PNG)

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

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5j6a7tyvioj2dtwhmld8.PNG)

once you are in the new terminal, change directory to

To change directory to Django_Svelte, the command is 

```
cd Django_Svelte
```

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

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pg13qjrch3as0mifciaw.PNG)

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

```
mkdir Svelte
```

mkdir is the command to make directory

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/919hvamgob4wqrn8z7tp.PNG)

check the dir again 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/864nbeb3vbbfw6xabfng.PNG)

now lets change directory to Svelte with 

```
cd Svelte
```
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y76n3uj3p6jakdxsjv4z.PNG)

 we can now clone the Routify project with the command 

```
npx @roxi/routify init
```

we need to wait for a while yeah 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hojt0brcz6kh79fg121u.PNG)

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


![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hq94ly7qeqgo7859byxd.PNG)

##7. Lets check if the Routify installation was successful

to run a dev server for Routify(Svelte) is 

```
npm run dev
```

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5ftlaphggx3dffg90og3.PNG)


lets see it activated in chrome,

the url for this would be 

http://localhost:5000

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xdtqu2jr8qxms5wghud5.PNG)

Amazing so far,

Routify also included an example page with the url

http://localhost:5000/example

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q0an7o0pm7krvh8m6c7s.png)
 
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
```

now we can start a new app call example  with 

```
python manage.py startapp example
```

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6jax0l85wvx9b6z7vwbt.png)
 


look at your directory now

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t9iyzelkwuxl24u2dwku.png)
 
so far not bad right....

let create a new file name urls.py 

the directory should look like this 

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gxjvgz9jp61xkpbauim3.png)


 inside example/urls.py

add the code below

```python 
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"))
]
```

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/is7iiwd7v86zfm53pdxh.png)
 
now lets open the directory Django_Svelte/Setting/base.py

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b1ol03xk8jb41wy8t062.png)


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

 ```python
INSTALLED_APPS = [
    # all the other already install app,
    'example',
]
```

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x5unrkj5435g9735ehgw.png)
 
now  lets edit the Templates setting to this

```python
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',
            ],
        },
    },
]
```

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pwvntf75uysryvrnvsof.png)
 
now lets add STATICFILES_DIRS into base.py

```python
STATICFILES_DIRS = [
    BASE_DIR + '/Svelte/dist',
] 
```
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b00glrtb2frzk9fgiyee.png)
 
Now lets change the Django_Svelte/urls.py file

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h8whlwsaa8iytd10mjmx.png)
 
add this line in the urlpatterns list

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

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l9pyg86pczbkuiwy6lyr.png)
 
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
```

lets wait for the migrations work its magic touch

then lastly you would see this

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qcjdrp87bep73pd616nk.png)
 

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v32vtw65dm2cjh7yum8w.png)
 

well remember we had also register example as our link?

try going to 

http://localhost:8000/example

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hw5d3hog0ht05rklh9ir.png)


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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ctpn8k2dhl56v7uzdvn1.png)

now lets make this changes to the file

```html
{% 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>
```

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rgto4b7tire02qtwvgki.png)
 
 
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bmahg802wfkn4m2bistg.png)

type Y 

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oyw8c7pkjvpyc2z9xkbg.png)
 
now your node server is done.

type this 

```
npm run build
```

you will see something like this

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/83upwfhekiiuob8cc0wg.png)

check if your python dev server is still running
 
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gwrscy1ggcyylaf2fuk6.png)


lets go back to chrome and check if django can server the link
 
http://localhost:8000/example

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l5ytz911dnnz5lkrq3ig.png)
 
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
```

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zo9kiby0ypp49aqd5qmk.png)

 ![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/76w3f47a7862t79epss7.png)

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

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/56ott9ywxo6l6ijlbd3m.png)

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

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e67js06iuuhbq0hj7cyr.png)
 
then on the keyboard click 

ctrl + enter

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ewho2my0luys09v25cyj.png)

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

now you need to push to github.com

 ![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kij0fdqfwcovify6udjg.png)
 
this will sync between your local git to your github account

lets check 

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pidrl4jzncooqxi9f3o9.png)
 
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