Search code examples
djangoajaxdjango-crispy-forms

Returning a Crispy Form as response to ajax request


i am trying to fill a form with data via ajax request. The is my attempt so far:

view.py:

def ajaxGetData(request):
    pnr=int(request.GET.get('pnr',None))
    instance=User.objects.get(pnr=pnr)
    form=User_Form(instance=instance,prefix="Userdata")
    return HttpResponse(form.as_p())

Ajax Code:

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

It does work, but the form is not rendered with crispy-forms. Is there some code like

return HttpResponse(form.as_crispy())

That would return a crispy form?

PS: I am quite new to Django and developing websites in general. I want to do a website where you can select a user from a list at the side of the page and then edit a whole bunch of data about him. From what i read doing a one-page-solution was the way to go for that. Would be quite thankful if someone can give me a hint if this is the right way to go about it.

Greetings!


Solution

  • 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']);
            }   
        }
    });