0

I have a Django project on which I am uploading files to a sql server. I would want to show only a text message when the operation has been succeded, without refreshing the page

I did not succeed to corelate the view with the AJAX and HTML form.

views.py:

def upload(request):
    if request.method == "POST":
        try:
            form = UploadFileForm(request.GET, request.FILES["excel_file"])
            file =  request.FILES['excel_file']
            Import_Resource = resources.modelresource_factory(model=item)()
            dataset =  tablib.Dataset()
            if not file.name.endswith('.xlsx'):
                messages.error(request, 'This is not a excel file!')
            if filename1 in file.name:
                imported_data = dataset.load(file.read(), format='xlsx')
                item.objects.filter(input_type = 'traitement').delete()
                for row in dataset:
                    ITEM2 = item()
                    ITEM2.input_type = 'traitement'
                    ITEM2.no_incident = row[1]
                    ITEM2.action = row[2]
                    ITEM2.week = row[4]
                    ITEM2.status = row[5]
                    ITEM2.assigned_by_group = row[6]
                    ITEM2.description = row[0]
                    ITEM2.previous_group = row[7]
                    if isinstance(row[3], float):
                        ITEM2.date_action = datetime.fromordinal(datetime(1900, 1, 1).toordinal() + int(row[3]) - 2)
                    else:
                        ITEM2.date_action = row[3]
                    if isinstance(row[8], float):
                        ITEM2.date_end = datetime.fromordinal(datetime(1900, 1, 1).toordinal() + int(row[8]) - 2)
                    else:
                        ITEM2.date_end = row[8]
                    ITEM2.save()
    data = {
        'file': file.name
    }
    return JsonResponse(data)

urls.py: url(r'^input/$', views.inputprocess, name='inputprocess'), html file:

    <form action="{% url "upload" %}" method="POST" enctype="multipart/form-data" class="form-inline" style="margin-left: 50px">
        <div class="form-group mb-2">
            {% csrf_token %}
            <input type="file" name="excel_file" id="excel_file" required="True">
        </div>
        <div class="form-group mb-2">
            <button class="btn btn-primary" id="likebutton2"> <span class="glyphicon glyphicon-upload"></span>Upload</button>
        </div>
        <div>
            {% if messages %}
            {% for message in messages %}
                {{ message }}
            {% endfor %}
            {% endif %}
        </div>
    </form>
      <script type="text/javascript">
    $('.likebutton').click(function(){
    var catid;
    catid = $(this).attr("data-catid");
    $.ajax(
    {
        type:"GET",
        url: "/upload",
        dataType: 'json',
        success: function(data) 
        {
            alert(data.filename);
        }
     })
});
</script>

Now, it returns a blank page with the file name. I would like it to return an alert with the file name, without refreshing the page. Any help would be mostly appreciated.

Alex Bran
  • 403
  • 1
  • 8
  • 18
  • The problem is because you've not called `preventDefault()` to stop the form submission. Also note that there is no `.likebutton` element in your HTML, and the closest one, `#likebutton2` has no `data-catid` attribute. You also need to send the form data in a POST request. At the moment you're sending no data in a GET request so it will not actually do anything at all – Rory McCrossan Nov 07 '19 at 08:57
  • I'd suggest you read [this answer](https://stackoverflow.com/a/8758614/519413) as it covers how to upload a file through jQuery AJAX – Rory McCrossan Nov 07 '19 at 08:59
  • thanks! the name errors are due to the fact that i got code from different sources and am not trying to figure out how to correlate everything. I have managed to link a button to a AJAX operation including a view, but I do not know how to get the file from the upload form there. Any help, please? – Alex Bran Nov 07 '19 at 09:22
  • Yep, that information is all in the answer I linked to in the second comment. – Rory McCrossan Nov 07 '19 at 09:24

0 Answers0