django-markdownx/markdownx/views.py
Aymeric Augustin 7b012db5a5 Make it possible to customize image insertion code. (#20)
* Make it possible to customize image insertion code.

It can be useful to insert more that just a markdown image tag, for
example to provide additional control on the layout of images. Since
there's no convenient way to handle this on the JavaScript side, we
generate the code to insert in Python. Then it can be overridden with
the existing extensibility mechanism, that is, with a custom view.

* Restore backwards-compatibility.

The previous commit is backwards-incompatible for users who pointed
MARKDOWNX_UPLOAD_URLS_PATH to a custom view. This commit restores
backwards-compatibility with the previous API.
2016-05-14 11:58:43 +02:00

37 lines
1.1 KiB
Python
Executable file

from django.conf import settings
from django.http import HttpResponse, JsonResponse
from django.utils.module_loading import import_string
from django.views.generic.edit import View, FormView
from .forms import ImageForm
class MarkdownifyView(View):
def post(self, request, *args, **kwargs):
markdownify = import_string(settings.MARKDOWNX_MARKDOWNIFY_FUNCTION)
return HttpResponse(markdownify(request.POST['content']))
class ImageUploadView(FormView):
template_name = "dummy.html"
form_class = ImageForm
success_url = '/'
def form_invalid(self, form):
response = super(ImageUploadView, self).form_invalid(form)
if self.request.is_ajax():
return JsonResponse(form.errors, status=400)
else:
return response
def form_valid(self, form):
image_path = form.save()
response = super(ImageUploadView, self).form_valid(form)
if self.request.is_ajax():
image_code = '![]({})'.format(image_path)
return JsonResponse({'image_code': image_code})
else:
return response