Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django CreateView with AJAX

I want to create, update and delete objects through generic views and modals using AJAX in Django. The official documentation of Django talk about AjaxableResponseMixin and show this code:

from django.http import JsonResponse
from django.views.generic.edit import CreateView
from myapp.models import Author

class AjaxableResponseMixin:
    """
    Mixin to add AJAX support to a form.
    Must be used with an object-based FormView (e.g. CreateView)
    """
    def form_invalid(self, form):
        response = super().form_invalid(form)
        if self.request.is_ajax():
            return JsonResponse(form.errors, status=400)
        else:
            return response

    def form_valid(self, form):
        # We make sure to call the parent's form_valid() method because
        # it might do some processing (in the case of CreateView, it will
        # call form.save() for example).
        response = super().form_valid(form)
        if self.request.is_ajax():
            data = {
                'pk': self.object.pk,
            }
            return JsonResponse(data)
        else:
            return response

class AuthorCreate(AjaxableResponseMixin, CreateView):
    model = Author
    fields = ['name']

(I have a model which looks like this) However I don't understand how to implement it in a modal. I do have this form that I'm currently using but it's a web page, not a modal:

  <form method="post" novalidate>
    {% csrf_token %}
    {% include 'includes/form.html' %}
    <button type="submit" class="btn btn-success">AJouter</button>
  </form>

Is there a simple way to implement it in a modal using some ajax and jquery?

like image 752
Gug Avatar asked Nov 08 '22 10:11

Gug


1 Answers

I use fetch instead of Ajax. This use promises in the new ES6 from javascript. This is my code

async function saveMateriaPrima(event) {
  console.log('Guardando producto');

  event.preventDefault();
  let dataForm = new FormData(formMatPrima)
  let url = formMatPrima.action

  fetch(url, {
    method: 'POST',
    body: dataForm
  })
  .then(function(response){
    console.log(response);

    if(response.ok){
      let producto = document.getElementById('id_nombre').value
      console.log(`${producto} guardado correctamente.`);

      document.getElementById('id_nombre').value = ''
      $('#modal-crearmateriaprima').modal('hide')

    }else{
      throw "Error en la llamada Fetch"
    }
  })
  .catch(function(err){
    console.log(err);    
  })
}

It works with your code but I can't get the new object's pk. I hope this helps you, and can improve this code to get the pk data.

like image 157
Jose Luis Quichimbo Avatar answered Nov 15 '22 07:11

Jose Luis Quichimbo