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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…