0

I would like to know how I can send a parameter value from Django (View, Form, etc) to JavaScript function in js file.

I have a Contact app:

Models.py

class Contact(models.Model):
    firstname = models.CharField(max_length=100, verbose_name='Nombre')
    lastname = models.CharField(max_length=100, verbose_name='Apellidos')
    email = models.EmailField(max_length=100, verbose_name='eMail')
    message = models.TextField(max_length=1000, verbose_name='Mensaje')
    created = models.DateTimeField(auto_now_add=True, verbose_name='Creado')
    updated = models.DateTimeField(auto_now=True, verbose_name='Editado')

    class Meta():
        verbose_name = 'Contacta Mensaje'
        verbose_name_plural = 'Contacta Mensajes'
        ordering = ['-created']

    def __str__(self):
        return str(self.email)

Forms.py

class ContactForm(forms.ModelForm):

    class Meta:
        model = Contact
        fields = ("firstname", "lastname", "email", "message")
        widgets = {
            'firstname': forms.TextInput(attrs={'class':'form-control', 'id': 'id_firstname'}),
            'lastname': forms.TextInput(attrs={'class':'form-control', 'id': 'id_lastname'}),
            'email': forms.EmailInput(attrs={'class':'form-control', 'id': 'id_email'}),
            'message': forms.Textarea(attrs={'class':'form-control', 'id': 'id_message'}),
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

View.py

class ContactView(CreateView):

    form_class = ContactForm
    template_name = 'core/contact.html'

JS function in theme.js

  forms: function () {
    (function() {
      "use strict";
      window.addEventListener("load", function() {
        var forms = document.querySelectorAll(".needs-validation");
        var validation = Array.prototype.filter.call(forms, function(form) {
          form.addEventListener("submit", function(event) {
            if(form.checkValidity() === false) {
              event.preventDefault();
              event.stopPropagation();
            }
            form.classList.add("was-validated");
            if(form.checkValidity() === true) {
              event.preventDefault();
              form.classList.remove("was-validated");
              // Send message only if the form has class .contact-form
              var isContactForm = form.classList.contains('contact-form');
              console.log(isContactForm);
              if(isContactForm) {
                var data = new FormData(form);
                var alertClass = 'alert-danger';
                fetch("", {
                  method: "post",
                  body: data
                }).then((data) => {
                  if(data.ok) {
                    alertClass = 'alert-success';
                  }
                  return data.text();
                }).then((txt) => {
                  var alertBox = '<div class="alert ' + alertClass + ' alert-dismissible fade show"><button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>' + txt + '</div>';
                  if(alertClass && txt) {
                    form.querySelector(".messages").insertAdjacentHTML('beforeend', alertBox);
                    form.reset();
                  }
                }).catch((err) => {
                  console.log(err);
                });
              }
            }
          }, false);
        });
      }, false);
    })();
  },

The JavaScript function has the parameter named 'txt', which set the message in 'contact .html' witch the result of Form Submit.

When the contact form is submitted and saved in database, I want to pass the success message value to the javascript function. And if there is a server error, pass the fail message.

How can I pass this message from Django View or Form to the JavaScript function wrote above.

Thanks. Regards,

0 Answers0