This content originally appeared on DEV Community and was authored by Eric Chapman
Hi,
Django community, it's time to celebrate! Something great is happening! A new Django tool is born and it's name Unicorn
What is Unicorn?
Unicorn is to Django what Livewire is to Laravel: A full stack framework that allow to build feature-rich-reactive UI with no API and no javascript only Django and python.
To make thing clear, I am not associated with Unicorn in any way. I am just a fan of their work.
Real world example
Let say you want to build a Todo list but you dont want to refresh the browser when adding or removing a task. Normally you will reach to javascript to implement this kind of functionality. Not with Unicorn!
Unicorn allow to create a Django template and a Django view that can do just that.
Here are sample Django template:
<!-- unicorn/templates/unicorn/todo.html -->
<div>
<form unicorn:submit.prevent="add">
<input type="text"
unicorn:model.defer="task"
unicorn:keyup.escape="task=''"
placeholder="New task" id="task"></input>
</form>
<button unicorn:click="add">Add</button>
<button unicorn:click="$reset">Clear all tasks</button>
<p>
{% if tasks %}
<ul>
{% for task in tasks %}
<li>{{ task }}</li>
{% endfor %}
</ul>
{% else %}
No tasks ?
{% endif %}
</p>
</div>
As you can see unicorn:model link the input to the task var and unicorn:click="add" call the component function name 'add'
Django view component:
# unicorn/components/todo.py
from django_unicorn.components import UnicornView
from django import forms
class TodoForm(forms.Form):
task = forms.CharField(min_length=2, max_length=20, required=True)
class TodoView(UnicornView):
task = ""
tasks = []
def add(self):
if self.is_valid():
self.tasks.append(self.task)
self.task = ""
As noted the python code is regular Django code easy to understand and write.
Excited?
I am! Unicorn can literarily change the spectre of what we can do with a Django template. It give you the power of a SPA without leaving the comfort of Django.
If you want more info you can check a visual example on their web site:
https://www.django-unicorn.com/
You can also check the git hub repo and give a Star to the project.
https://github.com/adamghill/django-unicorn
This content originally appeared on DEV Community and was authored by Eric Chapman
Eric Chapman | Sciencx (2021-04-23T10:20:29+00:00) Laravel Livewire for Django? Say hello to Unicorn!. Retrieved from https://www.scien.cx/2021/04/23/laravel-livewire-for-django-say-hello-to-unicorn/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.