0

I'm new to ajax and django and I'm trying to send a file in a form using formdata and ajax but I'm getting csrf token missing error and I've searched alot but can't solve this problem.Should I use cookies?if so,how?.I really need help.My codes are here:

urls.py

...

url(r'^administration/library/add_ebook/ajax/$',upload_ebook_ajax, name='upload_ebook_ajax'),

...

forms.py

class EbookForm(forms.ModelForm):
    class Meta:
        model = Ebook
        fields = ('ebook_title', 'ebook_publisher','ebook_publication_date','ebook_Type','ebook_keywords','ebook_preview','ebook_url','ebook_categories', )

views.py

@transaction.atomic()
def upload_ebook_ajax(request):

if request.method == 'POST':
    form = EbookForm(request.POST, request.FILES)
    if form.is_valid():

        form.save()
        data['form_is_valid'] = True

    else:
        data['form_is_valid'] = False
else:
    form = EbookForm()

context = {'form': form}
data['html_form'] = render_to_string('upldebook.html',context,request=request)
return JsonResponse(data)

upldebook.html

{% load crispy_forms_tags %}
{% crispy form %}

add_ebook.html

<div class="c">
                    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
                    <script src="{% static 'js/jquery-file-upload/vendor/jquery.ui.widget.js' %}"></script>
                    <script src="{% static 'js/jquery-file-upload/jquery.iframe-transport.js' %}"></script>
                    <script src="{% static 'js/jquery-file-upload/jquery.fileupload.js' %}"></script>
                <form method="post" enctype="multipart/form-data" action="{% url 'upload_ebook_ajax' %}" class="js-upload-ebook-form">
                    {% csrf_token %}

                    <div class="frmclass"></div>



                <script src="{% static 'uploadebook.js' %}"></script>


                    <button type="submit">Upload</button>
                    </form>
                </div>

uploadebook.js

//for showing form
 $.ajax({
      url: '/administration/library/add_ebook/ajax',
      type: 'get',
      dataType: 'json',
      success: function (data) {
        $(".frmclass").html(data.html_form);
      }
    });
//for form submit
    $(".js-upload-ebook-form").submit( function (e) {
    e.preventDefault();
    var frmdt = new FormData($('form').get(0)); //I don't know what is 'form' :|
    frmdt.append('csrfmiddlewaretoken', '{{ csrf_token }}');
    $.ajax({
    url: $(this).attr('action'),
    type: $(this).attr('method'),
    data: frmdt,
    cache: false,
    processData: false,
    contentType: false,
    dataType: 'json',
    success: function(data) {
        alert("SUCCESS1");
        window.location = "/"
    }

    });
    return false;
    });

4 Answers4

2

One solution I use is to add @csrf_exempt to your ajax methods (it might decrease security):

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def upload_ebook_ajax(request):
    # your code
igo
  • 6,359
  • 6
  • 42
  • 51
2

{% csrf_token %} puts a hidden html input inside your form, so if you just the form with original inputs, it should work.

data: $(this).serialize();
raptiye
  • 58
  • 6
0

Serialize the data field, the token will be posted along with it

data: frmdt.serialize(), 

Read this SO post page for more, your answer could be there

Community
  • 1
  • 1
0

I just needed this:

data:  new FormData(this)

and now it works.

Thanks to this link: http://phppot.com/php/php-ajax-image-upload/