[英]i`m getting the 400 response error in react.js i know the backendd is ok but the client side i am not sure i am not fimiliar with react
I can't create a class and I don't know why.我无法创建 class 我不知道为什么。 I am not familiar with react so much.我不熟悉反应这么多。
I am learning from this project I set for my self so please help I am working on it for 2 days and i don't know why this is happening.我正在从我为自己设置的这个项目中学习,所以请帮助我工作了 2 天,我不知道为什么会这样。
class CreateClassRoomView(APIView):
serializer_class = CreateClassRoomSerializer
def post(self, request, format=None):
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
ostad = request.data['ostad.name']
lesson = request.data['lesson.name']
day = request.data.get('day')
lesson_obj = Lesson.objects.get(name=lesson)
master_obj = Master.objects.get(name=ostad)
room = ClassRoom.objects.create(
ostad=master_obj,
lesson=lesson_obj,
day=day
)
room.save()
return Response(CreateClassRoomSerializer(room).data, status=status.HTTP_201_CREATED)
else:
return Response(
{
'message': "This is problem"
},
status=status.HTTP_400_BAD_REQUEST
)
from rest_framework import serializers
from .models import (ClassRoom, Lesson, Master)
class StringSerializer(serializers.StringRelatedField):
def to_internal_value(self, value):
return value
class LessonSerializer(serializers.ModelSerializer):
class Meta:
model = Lesson
fields = (
'name',
)
class MasterSerializer(serializers.ModelSerializer):
class Meta:
model = Master
fields = (
'name',
)
class ClassRoomSerializer(serializers.ModelSerializer):
lesson = LessonSerializer()
ostad = MasterSerializer()
class Meta:
model = ClassRoom
fields = (
'id','user',
'code','image',
'ostad', 'lesson',
'slug', 'deadline', 'day'
)
class DetailClassRoomSerializer(serializers.ModelSerializer):
lesson = LessonSerializer()
ostad = MasterSerializer()
class Meta:
model = ClassRoom
fields = (
'code','image',
'ostad', 'lesson',
'slug', 'deadline', 'day'
)
class CreateClassRoomSerializer(serializers.ModelSerializer):
lesson = LessonSerializer(many=False)
ostad = MasterSerializer(many=False)
class Meta:
model = ClassRoom
fields = (
'code',
'ostad', 'lesson',
'day',
)
read_only_fields = ('code',)
from django.db import models
from django.db.models.signals import post_save, pre_save
import string
import random
from datetime import datetime, timedelta
from django.contrib.auth.models import User
def generate_unique_code():
length = 6
while True:
code = ''.join(random.choices(string.ascii_uppercase, k=length))
if ClassRoom.objects.filter(code=code).count() == 0:
break
return code
class ClassRoom(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True)
code = models.CharField(max_length=8, default=generate_unique_code, unique=True)
image = models.ImageField(
blank=True, null=True,
upload_to="classes/"
)
ostad = models.ForeignKey('Master', on_delete=models.CASCADE, default="reza")
lesson = models.ForeignKey('Lesson', on_delete=models.CASCADE, default="reza")
slug = models.SlugField(blank=True, null=True)
answers = models.ManyToManyField(
'Answer',related_name='answered',
blank=True
)
day = models.IntegerField(default=0)
date = models.DateTimeField(default=datetime.today)
deadline = models.DateTimeField(default=datetime.today)
def __str__(self):
return self.code
def pre_save_slug_ref_code(sender, instance, *args, **kwargs):
# if not created:
instance.slug = instance.code
if not instance.code:
day = instance.day
time = timedelta(days=day)
deadline = instance.date + time
instance.deadline = deadline
pre_save.connect(pre_save_slug_ref_code, sender=ClassRoom)
class Lesson(models.Model):
name = models.CharField(max_length=150)
def __str__(self):
return self.name
class Master(models.Model):
name = models.CharField(max_length=150)
def __str__(self):
return self.name
class Answer(models.Model):
# username = models.ForeignKey(User, on_delete=models.CASCADE)
description = models.TextField()
image_answer = models.ImageField(upload_to='answers/')
question = models.ForeignKey('ClassRoom', on_delete=models.CASCADE)
# liked = models.ManyToManyField(
# User, related_name='liked',
# blank=True
# )
import React, { Component } from "react";
import {
BrowserRouter as Router,
Route,
Link,
Redirect,
} from "react-router-dom";
import ReactBootstrap from "react-bootstrap";
import { Form } from "react-bootstrap";
import { Button } from "react-bootstrap";
import "bootstrap/dist/css/bootstrap.min.css";
class CreateClass extends Component {
constructor(props) {
super(props);
this.state = {
items: [],
lesson: [
{
name: "",
},
],
master: [
{
name: "",
},
],
day: 1,
products: {
id: null,
lesson: {
name: "",
},
master: {
name: "",
},
day: 0,
},
};
this.handelDay = this.handelDay.bind(this);
this.handelLesson = this.handelLesson.bind(this);
this.handelOstad = this.handelOstad.bind(this);
this.getMaster = this.getMaster.bind(this);
this.getLesson = this.getLesson.bind(this);
this.fetchData = this.fetchData.bind(this);
this.handelCreate = this.handelCreate.bind(this);
this.handelRoomButtonPressed = this.handelRoomButtonPressed.bind(this);
}
componentDidMount() {
this.getMaster();
this.getLesson();
this.fetchData();
}
getMaster() {
fetch("http://127.0.0.1:8000/api/master/")
.then((res) => res.json())
.then((data) => {
this.setState({
master: data,
});
});
}
getLesson() {
fetch("http://127.0.0.1:8000/api/lesson/")
.then((res) => res.json())
.then((data) => {
this.setState({
lesson: data,
});
});
}
fetchData() {
console.log("fetchiing");
var url = "http://127.0.0.1:8000/api/";
fetch(url)
.then((res) => res.json())
.then((data) => {
this.setState({
items: data,
});
})
.catch((err) => {
// Do something for an error here
console.log("Error Reading data " + err);
});
}
getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== "") {
var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === name + "=") {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
handelOstad(e) {
this.setState({
products: {
...this.state.products,
master: e.target.value,
},
});
}
handelLesson(e) {
this.setState({
products: {
...this.state.products,
lesson: e.target.value,
},
});
}
handelDay(e) {
// console.log("day", e.target.name);
this.setState({
products: {
...this.state.products,
day: e.target.value,
},
});
}
handelRoomButtonPressed(e) {
console.log("item", this.state.products);
e.preventDefault();
var csrftoken = this.getCookie("csrftoken");
var url = "http://127.0.0.1:8000/api/create-class";
try {
fetch(url, {
method: "POST",
headers: {
"Content-type": "application/json",
"X-CSRFToken": csrftoken,
},
body: JSON.stringify(this.state.products),
})
.then((res) => {
this.fetchData();
this.setState({
products: {
id: null,
lesson: {
name: "",
},
master: {
name: "",
},
day: 0,
},
});
})
.then((data) => console.log(data));
} catch (error) {
console.log("catch");
}
}
handelCreate(e) {
console.log("item bad", this.state.products);
e.preventDefault();
var csrftoken = this.getCookie("csrftoken");
var url = "http://127.0.0.1:8000/api/create-class";
fetch(url, {
method: "POST",
headers: {
"Content-type": "application/json",
"X-CSRFToken": csrftoken,
},
body: JSON.stringify(this.state.products),
}).then((res) => {
res.json();
this.fetchData();
});
}
render() {
// console.log("pros", this.state.products);
return (
<Form onSubmit={this.handelCreate}>
<Form.Group>
<Form.Label>Ostad</Form.Label>
<Form.Control
as="select"
onChange={this.handelOstad}
value={this.state.products.master.name}
>
{this.state.master.map(function (master, index) {
return <option key={index}>{master.name}</option>;
})}
</Form.Control>
</Form.Group>
<br />
<Form.Group>
<Form.Label>Lesson</Form.Label>
<Form.Control
as="select"
onChange={this.handelLesson}
value={this.state.products.lesson.name}
>
{this.state.lesson.map(function (lesson, index) {
return <option key={index}>{lesson.name}</option>;
})}
</Form.Control>
</Form.Group>
<br />
{/* <Form.Group>
<Form.File id="exampleFormControlFile1" label="image file " onChange={this.handelChange}/>
</Form.Group>
<br /> */}
<Form.Group>
<Form.Label>days</Form.Label>
<Form.Control
type="text"
placeholder="day"
onChange={this.handelDay}
value={this.state.products.day}
/>
<Button onSubmit={this.handelCreate } type="submit">submit</Button>
</Form.Group>
</Form>
);
}
}
export default CreateClass;
Perhaps you are missing to mount the component somewhere on an actual HTML page.也许您缺少将组件安装在实际 HTML 页面上的某个位置。 A root React component needs to be injected on an already existing DOM node, for that you need to use ReactDOM
.根 React 组件需要注入到已经存在的DOM 节点上,因为你需要使用ReactDOM
。 For a Django application there are 2 ways you can do this:对于 Django 应用程序,有两种方法可以做到这一点:
You can do this by adding a function that renders the given template (I'm assuming an app您可以通过添加呈现给定模板的 function 来做到这一点(我假设一个应用程序
# ./myapp/views.py:
from django.shortcuts import render
def index(request):
return render(request, 'myapp/index.html')
Then your HTML file can look something like this:然后您的 HTML 文件可能如下所示:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>My app with React</title>
</head>
<body>
<div id="app">
<!-- React will load here -->
</div>
</body>
{% load static %}
<script src="{% static "myapp/main.js" %}"></script>
</html>
Then you simply mount your component然后你只需安装你的组件
import { render } from 'react-dom'
import MyComponent from 'path/to/my/component'
const root = document.getElementById("app")
render(<MyComponent />, root);
create-react-app
使用像create-react-app
这样的样板You can do the 'heavy-lifting' through create-react-app
which will work out of the box.您可以通过开箱即用的create-react-app
来完成“繁重的工作”。 It takes care of a lot things for you so you can focus more on development;它为您处理了很多事情,因此您可以更专注于开发; this comes with the implied cost of it being somewhat of a 'black box' as well as some additional management because your frontend app will be 'served' by webpack behind the scenes (by default on port 3000) which you then may need to reconcile later on by defining a proxy on your package.json or even with a reverse-proxy such as nginx.这带来了隐含的成本,它有点像“黑匣子”以及一些额外的管理,因为您的前端应用程序将由 webpack 在幕后“服务”(默认情况下在端口 3000 上),然后您可能需要进行协调稍后通过在 package.json 上定义代理,甚至使用反向代理,例如 nginx。
Here are some more in-depth tutorials for the alternatives above:以下是上述替代方案的一些更深入的教程:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.