Should I use forms for API endpoint to be exposed to Javascript?

I have an html/javascript calendar being used as a date picker. When a user selects a date, I want to send a POST to an api endpoint to store the new date in the user’s session.

I’d prefer to skip creating a form, as there is nothing to be rendered, and just send the data via ajax to an url endpoint, and then in the view update the session. In this case, does Django give a way to sanitise input?

Otherwise I suppose I would have to create a form, render but hide it in the html and then update fields and submit on clicks in the javascript, which seems quite long winded for what I want.

Hey there!
You don’t actually need to render a form on html to use a form. A form validates a data, this data is a dictionary (key-value pairs) and on “normal” views this comes from the browser via the form submission, but it does not need to be, the form only expects a valid python dict (And that’s when Django comes into play, it takes this form-data submitted and transforms into a valid python-dict that you can use later on your view with request.POST).

But, if you’re using JS to do the request, you can send this data without a form rendered on the page, on your view you can take the data from the POST (Or from the url, query parameters, with a GET method. Although, in this case since you’re modifying some stuff, the convention is to use a POST method), pass that to the form, let it validate it, and use the cleaned value.

An example python shell session:

from django import forms

class MyForm(forms.Form):
  reason = forms.CharField()  # required defaults to True

f = MyForm(data={})
# outputs: False

f = MyForm(data={"reason": "Lorem ipsum"})
# outputs: True
# outputs: "Lorem ipsum"

Hope i could get myself clear on the explanation!
Have a nice week!

Ahh this makes a lot of sense! Thanks very much for the explanation, I felt for sure I was missing something!

1 Like