简体   繁体   中英

Cannot parse FormData into django backend

hope you all are doing well I have been working on a custom form that I want to send to django backend via ajax request, the only problem that I am encountering is I am wrapping the form into FormData it works well on the frontend site but on the backend it shows a querydict with some strane data in it and making it much harder to parse the data, if there can be a way to easily get the data out.

Any leads or any response is much appreciated

Following is my code of the javascript function that sends the data to the backend

Javascript

function Edit_Content(e){
    
    var form_data=new FormData(document.querySelector("#edit-form"))
    let csrftoken=getCookie("csrftoken")
    
    $.ajax({
      url:"{% url 'EditPost' %}",
      method:"post",
      datatype:"json",
      processData:false,
      "headers":{
          "X-CSRFToken":csrftoken
        },
      data:form_data,
      success:function (data){
        console.log("Post or idea edited")
      }
    })
    
  }
  

views.py

def Edit(request):
    print(request.POST,request.FILES)
    data=dict(request.POST)
    print(data)
    if data["type"] == "post":
        post=Post.objects.get(pk=data['id'])
        content=data.get("post-content",None)
        media=data.get("media",None)
        post.edit(content,media)
    else:
        idea=Idea.objects.get(pk=data["id"])
        title=data.get("title",None)
        privacy=data.get("privacy",None)
        requirements=data.get("requirements",None)
        category=data.get("category",None)
        content=data.get("idea-content",None)
        media=data.get("media",None)
        idea.edit(requirements,title,privacy,category,content,media)
    return HttpResponse(status=200)

After converting request.POST into dictionary object it it gives

{'------WebKitFormBoundaryW30RtYeVz4cXnUNf\r\nContent-Disposition: form-data; name': ['"type"\r\n\r\nidea\r\n------WebKitFormBoundaryW30RtYeVz4cXnUNf\r\nContent-Disposition: form-data; name="id"\r\n\r\n1\r\n------WebKitFormBoundaryW30RtYeVz4cXnUNf\r\nContent-Disposition: form-data; name="title"\r\n\r\nProgramming is great\r\n------WebKitFormBoundaryW30RtYeVz4cXnUNf\r\nContent-Disposition: form-data; name="privacy"\r\n\r\n public\r\n------WebKitFormBoundaryW30RtYeVz4cXnUNf\r\nContent-Disposition: form-data; name="requirements"\r\n\r\nnothing\r\n------WebKitFormBoundaryW30RtYeVz4cXnUNf\r\nContent-Disposition: form-data; name="category"\r\n\r\nFisica\r\n------WebKitFormBoundaryW30RtYeVz4cXnUNf\r\nContent-Disposition: form-data; name="idea-content"\r\n\r\nProgramming is not for kids\r\n------WebKitFormBoundaryW30RtYeVz4cXnUNf\r\nContent-Disposition: form-data; name="media"; filename=""\r\nContent-Type: application/octet-stream\r\n\r\n\r\n------WebKitFormBoundaryW30RtYeVz4cXnUNf--\r\n']}

Which is hard to parse with the regex, is there any easier way to do this?

The form is being added dynamically but the basic structure of the form is as follows:

HTML form

<form id="edit-form" enctype="multipart/form-data">
            
</form>

request.POST is a dictionary-like object but is not your standard dictionary.

you can access normal textual data by using this notation.

data = request.POST

title=data.get("title",None)
privacy=data.get("privacy",None)
requirements=data.get("requirements",None)
category=data.get("category",None)
content=data.get("idea-content",None)

alternatively

title = request.POST.get("title", None)

POST does not include file-upload information, so you would need to call a different request property to access them.

request.FILES.get('media')

Solved the problem myself by manually iterating over each input field of the form and serializing it.

The javascript code looks like this

    var form_data=new FormData()
    $("form#edit-form :input").each(function(){
    var input = this; // This is the jquery object of the input, do what you will
    console.log(input)
    if(this.name == "media"){
      form_data.append(this.name,this.files[0])
    }
    else{
      form_data.append(this.name,this.value)
    }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM