Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 23, 2021 10:20 am GMT

Laravel Livewire for Django? Say hello to Unicorn!

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.pyfrom django_unicorn.components import UnicornViewfrom django import formsclass 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


Original Link: https://dev.to/ericchapman/laravel-livewire-for-django-say-hello-to-unicorn-1fo7

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To