[Answered ]-Django edit static content on live site

2👍

If you want to achieve editing of the layout files of the site like WordPress does it for themes, you are going to need to implement an app to do that yourself, I’m not aware of any existing project that allows you to do that, in Django or in Flask.

In a nutshell, you need to pick out what files you want to expose and have a view where you load up the text file open(file), display it in a Django Form in a textarea, and save it back to the file again.

If you’re editing css files, depending on your setup, you might need to trigger a collectstatic command on form save, so that the file goes where it is needed.

You could also use Ace Editor for easier code editing.

This is a stripped down example of what I used in a previous project for achieving this:

  class EditFileView(FormView):
    template_name = "file_edit_form.html"
    form_class = EditFileForm

    ALLOWED_ROOTS = ["%s/" % DISPLAY_TEMPLATES_DIRECTORY, ]

    def get_allowed_roots(self):
        return self.ALLOWED_ROOTS

    def dispatch(self, request, *args, **kwargs):
        if "file_name" not in request.GET:
            raise Http404

        file_name = request.GET['file_name']

        exists = False
        for root in self.get_allowed_roots():
            exists = os.path.exists(os.path.join(root, file_name))
            if exists:
                self.file_path = os.path.join(root, file_name)
                self.file_name = file_name
                self.root = root
                break

        if not exists:
            logger.debug(u"EditFileView: Could not find file to edit - %s" % file_name)
            raise Http404()

        return super(EditFileView, self).dispatch(request, *args, **kwargs)

    def form_valid(self, form):
        try:
            f = open(self.file_path, "wt")
            f.write(form.cleaned_data['file_contents'])
            f.close()
        except Exception, e:
            pass

        return HttpResponseRedirect(self.get_success_url())

    def get_initial(self):
        initial = super(EditFileView, self).get_initial()
        with open("%s" % self.file_path, "r") as f:
            initial['file_contents'] = f.read()
        initial["file_path"] = self.file_path
        return initial

    def get_success_url(self):
        return reverse("edit_file") + "?file_name=%s" % self.file_name


    def get_context_data(self, **kwargs):
        current = super(EditFileView, self).get_context_data(**kwargs)
        current.update({"file_name": self.file_path[len(self.root):].replace("//", "/")})
        return current

Leave a comment