简体   繁体   English

我在 react.js 中收到 400 响应错误我知道后端没问题但客户端我不确定我不熟悉反应

[英]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 天,我不知道为什么会这样。

this is my view i know this one is working这是我的观点,我知道这是有效的

 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
                )

serializer串行器

 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',)
     

models楷模

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
    # )

This is a component i have problem with这是我遇到问题的组件

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,
            },
        });
    }

i wrote two method but none of them work i seperate this to see better this is countinue of code above我写了两种方法,但它们都不起作用我将它分开以更好地查看这是上面的代码计数

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 应用程序,有两种方法可以做到这一点:

  1. Use a Django template to serve the HTML where the react component will be mounted later on.使用 Django 模板为稍后将安装反应组件的 HTML 提供服务。

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);
  1. Use a boilerplate like 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:以下是上述替代方案的一些更深入的教程:

  1. React + Django template tutorial: https://www.valentinog.com/blog/drf/#django-and-react-together React + Django 模板教程: https://www.valentinog.com/blog/drf/#django-and-react-together
  2. React + Django create-react-app tutorial: https://www.digitalocean.com/community/tutorials/build-a-to-do-application-using-django-and-react React + Django create-react-app 教程: https://www.digitalocean.com/community/tutorials/build-a-to-do-application-using-django-and-react

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从 React.js 中的 @material-ui/pickers 选择日期后出现错误 - i am getting error after i selecting the date from @material-ui/pickers in React.js 我正在尝试通过单击使用 React.js 的按钮来更改图像,但出现错误 - I am trying to change image by clicking buttons using React.js but getting error 当获取 url 没问题时,为什么我会收到错误 400? - Why am I getting the error 400, when the fetch url is ok? 我是新手,我不确定如何在我的 app.js 中实现条纹元素 - I am new to react and I'm not sure how to implement the stripe Elements in my app.js 当我将函数传递给React.js的子组件时,为什么会出现未捕获的TypeError? - Why am I getting an uncaught TypeError when I pass a function to a child component in React.js? 我无法在 react.js 中动态渲染组件, - I am unable to render components dynamically in react.js, 我无法在 react.js 的标头中发送 JWT 令牌 - I am not able to send JWT token in headers in react.js React JS:为什么我在 componentdidMount() 中出错? - React JS: Why am I getting error at componentdidMount()? 在运行以下简单的react.js应用程序时,我遇到的错误很少。 - I am getting few errors while running following simple react.js application .. any idea? 为什么我在 Apollo Client 中出现 400 错误 - Why am I getting a 400 error in mutation in Apollo Client
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM