Ryūga
Ryūga

Reputation: 21

I am trying to inject an already rendered Django template into a section of my page using AJAX

I am following by this tutorial on how to get live updates on django without refreshing the page.
The tutorial uses flasks render_template to get the html rendered which is then injected to a page section. I am trying to do the same in Django, But django just directly renders it in the browser... I don't want that. I just want django to send the rendered html response to AJAX which could then inject that to a section on my live page.
Here is the code :

views.py

class ManageView(LoginRequiredMixin, View):
template_name = "dashboard/manage.html"
context = {}

def get(self, request, app_id, folder_id=None):
    app = App.objects.get(pk=int(app_id))
    self.context["app"] = app
    if folder_id:
        try:
            self.context["folder"] = Folder.objects.get(id=folder_id)
        except:
            self.context["folder"] = app.folder
    else:
        self.context["folder"] = app.folder
    return render(request, self.template_name, self.context)

def post(self, request, app_id, folder_id=None):
    try:
        files = request.FILES.getlist('files_to_upload')
        folder_name = request.POST.get("folder")
        master = request.POST.get("master")
        if master:
            master = Folder.objects.get(id=master)
        if folder_name:
            Folder.objects.create(name=folder_name, owner=request.user.customer, folder=master)
        if files:
            for file in files:
                if file.size < settings.MAX_FILE_SIZE:
                    File.objects.create(folder=master, item=file, name=file.name, size=file.size)
        app = App.objects.get(pk=int(app_id))
        self.context["app"] = app
        if folder_id:
            try:
                self.context["folder"] = Folder.objects.get(id=folder_id)
            except:
                self.context["folder"] = app.folder
        else:
            self.context["folder"] = app.folder
        return render(request, 'dashboard/filesection.html', self.context)
    except DatabaseError:
        return render(request, "dashboard/index.html", self.context)

urls.py

urlpatterns = [    url(r'^manage/(?P<app_id>[0-9]+)/(?P<folder_id>.+)', test, name='browse'), ]

dashboard/manage.html

       <div class="modal-body">
            <form id="app-launch" enctype="multipart/form-data" method="post">
                {% csrf_token %}
              <div class="form-row">
                <div class="input-group mb-3">
                  <div class="custom-file">
                    <input type="hidden" value="{{ folder.id }}" name="master">
                    <input type="hidden" value="{{ app.id }}" name="file_app_id">
                    <input type="file" class="custom-file-input" name="files_to_upload" id="file_upload" accept=".py,.js,.json,.txt,.css,.html,.pdf,.htm,.doc,.docx,.log,.ppt,.pptx" multiple>
                    <label class="custom-file-label" for="inputGroupFile02">Choose file</label>
                  </div>
                  <div class="input-group-append">
                    <button class="input-group-text btn btn-primary" id="">Upload</button>
                    <button class="input-group-text btn btn-primary fileButton" id="">Upload</button>
                  </div>
                </div>
              </div>
            </form>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-outline-danger" data-dismiss="modal">Cancel</button>
          </div>
        </div>

app.js AJAX calls

$(document).ready(function() {

    $(document).on('click','fileButton', function(e) {
        e.preventDefault()

    // const axios = require('axios');

    var formData = new FormData();
    var ins = document.getElementById('file_upload').files.length;
    for (var x = 0; x < ins; x++) {
    formData.append("files_to_upload", document.getElementById('file_upload').files[x]);
}
    const csrftoken = getCookie('csrftoken');
    var app_id = $('input[name="file_app_id"]').val();
    var folder_id = $('input[name="master"]').val();
    formData.append('master', folder_id);

    req = $.ajax({
        type: 'POST',
        url: `/manage/${app_id}/${folder_id}`,
        data: formData,
        processData: false,
        contentType: false,
        headers: {
            "X-CSRFToken": csrftoken,
        }
    });
    req.done(function (data) {
        $('#refreshSection').html(data)
    })
});
});

AJAX POST and everything works, it just that the django is refreshing and rendering that section template on the browser which i don't want.

Upvotes: 1

Views: 152

Answers (1)

Ryūga
Ryūga

Reputation: 21

[Solved]

Its was a mistake from my side. I missed e.preventDefault() which is really dumb.

Upvotes: 0

Related Questions