-2

I am trying to make Django and React to work together, and although I have a basic knowledge of Django (I can develop a site), I am just starting to learn React.

My project structure is based on this video which is loosely based on this blog in turn.

My API works perfectly fine, I can create, retrieve, update, and delete objects without problems.

Also, on my frontend, I have managed to correctly display a list of the items from my database, by fetching the related API Url.

Just to make it clear, here is the main 'backend' urls.py:

from rest_framework import routers
from .views import AssessmentViewSet

router = routers.DefaultRouter()
router.register('api/assessments', AssessmentViewSet, 'assessments')

urlpatterns = router.urls

Now, from what I see on my API webpage, objects are created and retrieved on the same Url, and namely http://127.0.0.1:8000/api/assessments/, as you can see from this screenshot.

enter image description here

The only difference, I guess, is that when I want to create an object, all I have to do ist to specify inside the fetch function, that I am making a POST request. This is done in my CreateAssessmentForm.jsx file:

import React, { Component } from "react";

class CreateAssessmentForm extends Component {
  state = {
    loading: false,
    title: "",
    is_finished: false,
    created_at: "",
  };

  constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
    let value = event.target.value;
    console.log("Value: ", value);
    this.setState({
      title: value,
    });
  }

  handleSubmit(event) {
    event.preventDefault(console.log("Item:", this.state));
    fetch("http://127.0.0.1:8000/api/assessments", {
      method: "POST",
      headers: {
        "Content-type": "application/json",
      },
      body: JSON.stringify(this.state.title),
    }).then(response => {
      this.setState({
        loading: false,
        title: "",
        is_finished: false,
        created_at: "",
      }).catch(function (error) {
        console.log("ERROR:", error);
      });
    });
  }

  render() {
    return (
      <div>
        {this.state.loading ? (
          <div className="text-center">Loading...</div>
        ) : (
          <form onSubmit={this.handleSubmit} method="POST">
            <h2 className="text-center">Assessment Title</h2>
            <div className="form-group">
              <label htmlFor="Title">Title</label>
              <input
                onChange={this.handleChange}
                type="text"
                className="form-control"
                id="TitleInput"
                value={this.state.title}
                placeholder="E.g. History Quiz"
              />
            </div>
            <button type="submit" className="btn btn-primary">
              Submit
            </button>
          </form>
        )}
      </div>
    );
  }
}

export default CreateAssessmentForm;

When I type something inside the title input, the console logs properly every entry, and when I press the submit button it also logs an object (which as you can see from the code above is my actual state - {this.state}).

The problem is that when submitting, I get a 500 (Internal Server Error) and the object is not saved on the backend database.

Does anyone know what I am doing wrong?

Techoplite
  • 605
  • 9
  • 23

1 Answers1

3

Best shot would be to check what are the django logs as you get Internal Server Error. It should be clear enough of what you are doing wrong, if not, please post the error log.

Damian Busz
  • 1,693
  • 1
  • 10
  • 22
  • How do I check the Django logs? I guess you mean I have to print something... – Techoplite May 14 '20 at 09:46
  • Thanks a lot for that! I was missing the ending slash. the only thing is that I get a 400 (bad request) now. Should I edit the question title or post a new question? (Obviously, the log doesn't show anything now) – Techoplite May 14 '20 at 10:02
  • Ok, I got it fixed. I was handling the onChange in a wrong manner. But thanks for the hit, has been really useful. – Techoplite May 14 '20 at 10:20