DEV Community

loading...
Cover image for Laravel Livewire for Django? Say hello to Unicorn!

Laravel Livewire for Django? Say hello to Unicorn!

ericchapman profile image Eric Chapman ・2 min read

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>
Enter fullscreen mode Exit fullscreen mode

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 = ""
Enter fullscreen mode Exit fullscreen mode

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

Discussion (1)

Collapse
adamghill profile image
Adam Hill

Thanks for shouting out Unicorn! If you want to read some other articles about the creation of this framework I have a series I wrote on dev.to: dev.to/adamghill/add-some-magic-to....

Forem Open with the Forem app