title: Django: Save JSON to database using Fetch/Post
body: <p>In a Django app, I want to save JSON to the database using the fetch/post API. Two issues: (1) I'm having CSRF verification troubles, and (2) I'm unsure about using POST to modify the DB in general.</p>
  
  <p>I have a model "Job" with a field that should hold JSON.</p>
  
  <pre><code>class Job(models.Model):
      job_id = models.IntegerField()
      setup_json = models.CharField(max_length=100000, blank=True, null=True)
  </code></pre>
  
  <p>The JSON is generated thru user interactions on a page. When the press a "save" button I want to write the JSON to the <code>setup_json</code> field of the proper job.</p>
  
  <p>I don't want to use a form, because the JSON is stored in JavaScript and not written anywhere on the page. So I get the CSRF token <a href="https://docs.djangoproject.com/en/2.1/ref/csrf/#acquiring-the-token-if-csrf-use-sessions-or-csrf-cookie-httponly-is-true" rel="nofollow noreferrer">from the template</a> to use directly, like this:</p>
  
  <pre><code>{% csrf_token %}
  &lt;script type="text/javascript"&gt;
    const csrftoken = document.getElementsByName("csrfmiddlewaretoken")[0].value;
  &lt;/script&gt;
  </code></pre>
  
  <p>(Note: in my "settings.py" file I added the line <code>CSRF_USE_SESSIONS = True</code> in order to use this technique.)</p>
  
  <p>Then I have my save button call a function like this:</p>
  
  <pre><code>function onPressSave() {
    fetch(`webapp/api/save-json/${jobId}`, {
      method: "POST",
      headers: {
        "X-Requested-With": "XMLHttpRequest",
        "X-CSRF-Token": csrftoken,
        "Content-Type": "application/json; charset=utf-8",
        Accept: "application/json"
      },
      credentials: "same-origin",
      body: JSON.stringify("test json")
    });
  }
  </code></pre>
  
  <p>I get a "POST 403 (Forbidden)" error in the console. Any help with this would be greatly appreciated!</p>
  
  <p>I'm also a little unsure of what exactly the receiving function should look like. Currently it just looks like this:</p>
  
  <pre><code>def save_json(request, id):
      j = Job.objects.get(job_id=id)
      j.setup_json = json.dumps(dict(name="testing"))
      return HttpResponse("OK")
  </code></pre>
  
  <p>I ultimately want to retrieve the proper JSON from the POST request, but does it look like I'm on the right track with this function?</p>