Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.1k views
in Technique[技术] by (71.8m points)

python - Write contents of ace.js editor to file in Django

I am playing around with the idea of editing my Django templates from the server. I know this is a far shot from that but I wrote this bit of code:

def editor(request):
  handle=open(os.path.join(settings.BASE_DIR, 'app/code/test.html'), 'r+')
  var=handle.read()
  context = {
    "message": "editor",
    "code": var
  }
  return render(request, 'app/editor.html', context)

That reads a file and passes it's contents to the template where ace.js displays it in the editor.

  <div id="editor-container">
    <div id="editor">{{code}}</div>
  </div>

It displays just fine and I can edit the text, but if I wanted to save my edits, writing them to the file, the button would need to go to a save route because I'm not using ajax, but how would I pass the new version of the document to the view to be written to the file?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

To make this work you need to have an hidden input. Whenever the contents of the editor are updated, the input is also update. Saving the contents is just now a matter of submitting the form. Here is what I came up with.

First is the html template where the editor is.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ace editing</title>
    <style type="text/css" media="screen">
        #editor {
            position: absolute;
            top: 0;
            right: 0;
            bottom: 0;
            left: 0;
        }
        
        .editor-container {
            position: relative;
            height: 300px;
            width: 100%;
        }
    </style>
</head>

<body>
    <div class="editor-container">
        <div id="editor">
            {{code}}
        </div>
    </div>
    <form method="POST">
        {% csrf_token %} {{form.as_p}}
        <button type="submit">Save</button>
    </form>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.12/ace.js"></script>
    <script>
        var editor = ace.edit('editor');
        editor.setTheme("ace/theme/monokai");
        editor.session.setMode("ace/mode/html");
        editor.on('change', function() {
            code_hidden_input = document.querySelector('#id_code');
            code_hidden_input.value = editor.getValue();
            console.log(editor.getValue())
        })
    </script>
</body>

</html>

Now in your views.py the code will be like the following.

from django.shortcuts import render
from .forms import MyForm
import os
from django.conf import settings

# Create your views here.
def index(request):
    form = MyForm()
    handle = open(os.path.join(settings.BASE_DIR, 'core/templates/core/test.html'))
    code = handle.read()
    if request.method == "POST":
        form = MyForm(request.POST)
        if form.is_valid():
            print(form.cleaned_data['code'])
            # This is the part where you save the code you have
            # edited to some file
    context = {
        'form': MyForm(),
        'code': code
    }
    return render(request, "core/index.html", context)

In your forms.py file create a class called My Form like below

from django import forms

class MyForm(forms.Form):
    code = forms.CharField(max_length=10000, widget=forms.HiddenInput())

That's all, note when submiting html using forms you need to sanitize your input.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...