使用ajax发布formdata在django中有csrf错误

时间:2017-03-19 09:23:16

标签: jquery ajax django form-data

我是ajax和django的新手,我正在尝试使用formdata和ajax发送一个表单中的文件,但我得到csrf令牌丢失错误,我搜索了很多,但无法解决这个问题。我应该使用cookies吗?如果是的话,怎么样?我真的需要帮助。我的代码在这里:

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 个答案:

答案 0 :(得分:2)

我使用的一个解决方案是将@csrf_exempt添加到您的ajax方法中(可能会降低安全性):

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def upload_ebook_ajax(request):
    # your code

答案 1 :(得分:2)

data: $(this).serialize(); 在您的表单中放入一个隐藏的html输入,因此如果您只是带有原始输入的表单,它应该可以正常工作。

{{1}}

答案 2 :(得分:0)

序列化数据字段,令牌将与其一起发布

data: frmdt.serialize(), 

请阅读此SO post页面了解更多信息,您的答案可能就在那里

答案 3 :(得分:0)

我只是需要这个:

data:  new FormData(this)

现在可行。

感谢此链接: http://phppot.com/php/php-ajax-image-upload/