Reputation: 2412
I want to send a modelform to my template using through json response(I've no idea if it's possible or not).
Actually in my template I have a list of objects from a model, and when i click them i send a post request to my view through ajax or axios with the object id, then in view I'm creating the model form of that object and I want to send that the model form of instance object back to template.
to summarize it up how can i send an model form through json response.(If not possible how to )
updated!
this is my forms.py
...
class UpdateMedicalRecordForm(forms.ModelForm):
class Meta:
model = MedicalRecords
fields = ("title", "file", "doctor", "doctor_access", "general_access")
widgets = {
"title": forms.Textarea(attrs={"rows": "", "class": "form-control", "placeholder": "Optional"}),
"file": forms.FileInput(attrs={"class": "form-control"}),
"doctor": forms.Select(attrs={"class": "form-control"}),
}
labels = {
"title": "Description (Optional)",
"general_access": "General Access For Record",
"doctor_access": "Doctor Access For Record",
}
then in views.py
i'm getting the medicalrecord, ID
through the ajax and make a UpdateMedicalRecordForm()
modelform for that instance as
from_instace = UpdateMedicalRecordForm(
request.POST, request.FILES,
instance=get_object_or_404(MedicalRecords, id=request.POST.get("file-id"))
)
here i don't know how to send my response back to template, to use it as form.as_p or loop through that.
...
JsonResponse({
"form": ??
})
Upvotes: 0
Views: 1195
Reputation: 1659
you can use django-remote-forms like this :
from django_remote_forms.forms import RemoteForm
from django.forms.models import model_to_dict
####
form = UpdateMedicalRecordForm(
request.POST, request.FILES,
instance=get_object_or_404(MedicalRecords, id=request.POST.get("file-id"))
)
form['instance']=model_to_dict(form['instance'])
remote_form = RemoteForm(form)
remote_form_dict = remote_form.as_dict()
response = HttpResponse(
json.simplejson.dumps(remote_form_dict, cls=DjangoJSONEncoder),
mimetype="application/json"
)
# Process response for CSRF
csrf_middleware.process_response(request, response)
return response
then you can parse the response in you js
Upvotes: 1