Reputation: 2373
Ok, so I have already posted about this, I am now attempting to isolate the issue..
I am trying to simply submit a form and have an alert appear when that is successful (just to verify my code works). I am new to Jquery/JS. When I have my code commented out the uncommented code works:
$(document).ready(function(){
var $myForm = $('.form')
$myForm.addClass('site-yellow')
$('.form').on('submit', function(event){
event.preventDefault();
var form = $(event.target)
var formData = new FormData(form[4]);
alert("Video done!");
// $.ajax({
// type : 'POST',
// url : "{% url 'videos-upload' %}",
// data : {
// data : formData,
// csrfmiddlewaretoken: '{{ csrf_token }}',
// }
// success : function(){
// }
// });
});
});
As soon as I uncomment the code the whole thing breaks.. but I cannot seem to figure it out..
My view:
class VideoUploadView(PermissionRequiredMixin, LoginRequiredMixin, FormView):
form_class = VideoUploadForm
success_url = '/videos'
template_name = 'videos/video_form.html'
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST, request.FILES)
if form.is_valid():
form.save()
# stuff
form.save()
messages.success(self.request, self.success_message)
return redirect(self.success_url)
return render(request, self.template_name, {'form': form})
My HTML:
<form class="form" enctype="multipart/form-data" method="POST">
{% csrf_token %}
<div class="form-row mt-4 mb-4">
<div class="form-group col-md-12 mb-0">
{{ form|as_crispy_field }}
</div>
</div>
<div class="form-row mt-4">
<button class="btn btn-warning" type="submit">Save Video</button>
</div>
</form>
What do I need to do to get the AJAX request to submit the form?
Upvotes: 2
Views: 538
Reputation: 1309
JS:
$.ajax({
type: 'POST',
url: '{% url "upload-videos" %}',
enctype: 'multipart/form-data',
processData: false,
contentType: false,
data: new FormData(this) ,
success: function(data){
alert('Success')
}
In your views.py, you need to receive the json:
if request.method == 'POST':
form = self.form_class(request.POST, request.FILES)
if form.is_valid():
print("done")
Upvotes: 2