Home > other >  submitting django crispy form with file field and some other text fields using fetch and then
submitting django crispy form with file field and some other text fields using fetch and then

Time:12-22

I am trying to submit my crispy form using fetch and then methods to django backend. All my fields are submitting to the server. but files are shown as empty fields in the server. below, is my front end from


 {{ photo.media }}
            <form action="" method="post"  enctype="multipart/form-data" id="photo_form"
                onsubmit="">
                {% csrf_token %}
                {{photo|crispy}}
                <input type="submit" value="Add" >
            </form>

Here is the ajax request I made

           <script>
                const photoForm = document.querySelector('#photo_form');

                console.log(photoForm.values);

                photoForm.addEventListener('submit', (event) => {
                    event.preventDefault();

                    const photoFormData = new FormData(photoForm);

                    photoFormData.forEach((value, key) => {
                        console.log(key   ': '   value);
                    });

                    fetch("{% url 'add_photo' %}", {
                        method: 'POST',
                        body: photoFormData,
                        contentType: false,
                        processData: false,
                    })
                        .then((response) => response.json())
                        .then((data) => {

                            console.log(data);

                            if (data.result == 'success') {
                                $('.modal-body').html('Form submission was successful!');
                                $('#modal-dialog').modal('show');
                                photoForm.reset();

                            } else {

                                $('.modal-body').html('There was an error with the form submission.');
                                $('#modal-dialog').modal('show');
                            }

                        });
                });

            </script>

Below, is the model I Made

class Photos(models.Model):
    photo_title = models.CharField(max_length=50, blank=False)
    photo_description = models.CharField(max_length=50, blank=False)
    photo_date = models.DateField(blank=False)
    photo_location = models.CharField(max_length=50, blank=False)
    photo_file = models.ImageField(upload_to='photos', blank=False)

    def __str__(self):
        return self.photo_title

Below, is the view function



""" ajax add photo event to home wall """


def add_photo(request):
    if request.method == 'POST':
        response_data = {}
        photoForm = UploadPhotosForm(request.POST)
        print(photoForm.is_valid())
        print(photoForm.errors)
        if photoForm.is_valid():
            photoForm.save()
            response_data['result'] = 'success'
            print(response_data)
            return HttpResponse(
                JsonResponse(response_data),
            )
    else:
        response_data['result'] = 'error'
        print(photoForm.errors)
        return HttpResponse(
            JsonResponse(response_data),
        )

While I tried to figure out the problem, I got these outputs

from client side

csrfmiddlewaretoken: xDJ7qlvfOgaPta6VXkIH03QlT1AybEQ46xcC2ri09MO4F7DbBPGbeNehMrJa3Rjy
(index):141 photo_title: sadfsf
(index):141 photo_description: sfsfse
(index):141 photo_date: 2022-12-22
(index):141 photo_location: adsafd
(index):141 photo_file: [object File]
(index):144 

POST http://127.0.0.1:8000/manager/add/photo/ 500 (Internal Server Error)
(anonymous) @ (index):144
VM750:1 
        
       Uncaught (in promise) SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON
Promise.then (async)
(anonymous) @ (index):149

from server side

False
<ul ><li>photo_file<ul ><li>This field is required.</li></ul></li></ul>
<ul ><li>photo_file<ul ><li>This field is required.</li></ul></li></ul>
[21/Dec/2022 15:09:10] "POST /manager/add/photo/ HTTP/1.1" 200 19

can someone help me out to figure out the problem?

CodePudding user response:

In your post method, change to:

photoForm = UploadPhotosForm(request.POST,request.FILES)
  • Related