Last active
September 5, 2018 04:35
-
-
Save jaivikram/03607d7c411d39176ab89ed409ac75e1 to your computer and use it in GitHub Desktop.
Gist to show and sync data between react-sortable-tree and django-treebeard
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
from __future__ import unicode_literals | |
""" | |
Recently I tried showing tree data contained in `django-treebeard` in the backend as tree data in `react-sortable-tree` in the frontend. | |
https://github.com/frontend-collective/react-sortable-tree | |
https://github.com/django-treebeard/django-treebeard | |
The idea was to keep the backend updated when the tree nodes are manipulated visually by the user. | |
I won't say this script is really complex or I am super proud of it, but it's always interesting to play with tree data | |
and keeping tree structures at backend updated with frontend manipulation is all the more interesting. | |
""" | |
import json | |
from collections import OrderedDict | |
from django.db import transaction | |
from django.http import JsonResponse | |
from django.shortcuts import render | |
from .models import Category | |
def index(request): | |
return render(request, 'index.html') | |
def get_data(request): | |
treeData = [] | |
def put_children(n, parent=None): | |
node = {'title': n['data']['name'], 'id': n['id'], 'children': []} | |
if not parent: | |
parent = node | |
treeData.append(parent) | |
else: | |
parent['children'].append(node) | |
parent = node | |
for c in n.get('children',[]): | |
put_children(c, parent) | |
for c in Category.dump_bulk(): | |
put_children(c) | |
return JsonResponse(treeData, safe=False) | |
@transaction.atomic | |
def put_data(request): | |
treeData = json.loads(request.body.decode("utf-8")) | |
def format_node(treeData): | |
for c in treeData: | |
c['data'] = {'name': c.pop('title'), 'id': c.pop('id')} | |
format_node(c['children']) | |
format_node(treeData) | |
Category.objects.filter(depth=1).delete() | |
Category.load_bulk(treeData) | |
return JsonResponse({'status': True}, safe=False) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment