0

Hola todos he pensado guardar en una variable en javascript un dato y luego enviarlo a una vista de django para usar ese dato, en este caso la variable formatSelected, aclaro q el codigo de javascript está en un template de django, O que opciones tengo para lograrlo?

Script de javascript

<script>
  $(document).ready(function() {
    $(".formato-button").on("click", function() {
      const formatSelected = $(this).parent().parent().parent().find(".formato-title").text();
      let height = 0;
      let width = 0;
      if (formatSelected == "A4") {
        width = 2480;
        height = 3508;
      } else if (formatSelected == "Facebook") {
        width = 1200;
        height = 630;
      } else if (formatSelected == "Instagram") {
        width = 1080;
        height = 1080;
      }
      localStorage.setItem("width", width);
      localStorage.setItem("height", height);
    })
  });

vista django

class FondoView(LoginRequiredMixin, TemplateView):
    template_name = 'fondo.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        all_records = Image.objects.filter(format="variable javascript")
        filtered_records = None
        filter_category = int(self.request.GET.get('search_tipo')) if self.request.GET.get('search_tipo') else 1
        filter_name = self.request.GET.get('search_fondo')
        if (not filter_category and not filter_name):
            image_json = serializers.serialize('json', all_records)

1 respuesta 1

0

Para enviar una variable desde javascript puedes utilizar una petición fetch y enviar por método post la variable, por ejemplo:

var myFormatSelected = 'dato';
fetch('/your_url/',{
     method: 'POST,
     headers: {'Content-Type': 'applicatiom/json'},
     body: JSON.stringify({formatSelected: myFormatSelected})
})
.then(response => {
    console.log(response);
})
.catch(error => {
    console.log(error);
});

Luego en tu views.py:

from django.http import JsonResponse
def my_view(request):
    if request.method == 'POST':
        my_var = request.POST.get('formatSelected')
        print(my_var)
        return JsonResponse({'status': 'ok'})
2
  • Gracias Kenner lo usare asi. miro como me va. aunque me habian comentado de guardarlo como cookie
    – dani ruiz
    el 5 mar. a las 22:43
  • Sí, puedes guardarlo como una Cookie y enviarlo. Yo por ejemplo utilizo una cookie para almacenar el token de un usuario y lo mando por fetch cada vez que necesite hacer una petición. el 7 mar. a las 16:14

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.