[Answered ]-Returning a Crispy Form as response to ajax request

1👍

Django Crispy Forms has a helper render_crispy_form to render a form within python code.

So your views.py:

from django.template.context_processors import csrf
from crispy_forms.utils import render_crispy_form

from django.http import JsonResponse


def ajaxGetData(request):
    pnr = int(request.GET.get('pnr'))
    instance = User.objects.get(pnr=pnr)
    form = User_Form(instance=instance, prefix="Userdata")
    ctx = {}
    ctx.update(csrf(request))
    #           ⬇️⬇️⬇️ 
    form_html = render_crispy_form(form, context=ctx)
    return JsonResponse({"form_html": form_html})

Note that you have to provide render_crispy_form the necessary CSRF
token, otherwise it will not work.

I suggest you to use JsonResponse

jQuery would look like:

$.ajax({
    url: "{% url 'ajaxGetData' %}",
    type: "get",
    data: {
        'pnr': pnr,
    },
    success: function (data) {
        if (data) {
            $('#Userdata-Content').html(data['form_html']);
        }   
    }
});
👤NKSM

0👍

You need install crispy module and later how use crispy forms in django https://django-crispy-forms.readthedocs.io/en/latest/crispy_tag_forms.html

Leave a comment