0

I know how to save the form in Django using AJAX, but don't know how to retrieve the form object from Django and inject the form inside HTML.

I need to retrieve the form data through return HttpResponse(jhjson, {'content_type' : 'application/json'}) instead of return render(request, 'task/mobileInventory.html', {'form': form})

View.py

def get_try(request, sid):
    print (sid)
    member = get_object_or_404(TaskMaster, pk=sid)
    form = CreateTaskMaster(instance=member)
    return render(request, 'task/mobileInventory.html', {'form': form})
3
  • It is unclear to me what you are asking. Are you wondering how to send data from a form using an ajax request instead of passing it with a form, or are you wanting to know how to receive the request, or is it something else entirely? Commented Dec 21, 2017 at 7:22
  • i want to know to get form data from django to ajax Commented Dec 21, 2017 at 7:46
  • do you mean, how to get JSON data from django? Commented Dec 21, 2017 at 8:21

1 Answer 1

1

Creating Django Form Objects

First, you need to create a Django Form object.

from django import forms

class SomeForm(forms.Form):
    some_field = forms.CharField(label='Some Field', max_length=100)

Rendering Django Forms

After creating a form object, you can render it inside HTML as follows.

from django.shortcuts import render

def form_view(request):
    # import your form here
    form = SomeForm()
    # you are rendering your form object as some_form inside an html
    return render(request, 'your_html_file', {'some_form': form})

Using Django Forms Inside HTML

Finally, you can inject your form using Django template language's double bracket notation.

<form action="your_ajax_call">
    {{ some_form }}
    <input type="submit" value="Submit" />
</form>
Sign up to request clarification or add additional context in comments.

3 Comments

It may sound silly but I am very new to programming I would like to know how we handle the ajax and HTML part
And also I am getting an error that form cannot be serializable
I just updated my answer. And also you should read the documentation first. docs.djangoproject.com/en/2.0/topics/forms

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.