繁体   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

我无法创建 class 我不知道为什么。 我不熟悉反应这么多。

我正在从我为自己设置的这个项目中学习,所以请帮助我工作了 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;

也许您缺少将组件安装在实际 HTML 页面上的某个位置。 根 React 组件需要注入到已经存在的DOM 节点上,因为你需要使用ReactDOM 对于 Django 应用程序,有两种方法可以做到这一点:

  1. 使用 Django 模板为稍后将安装反应组件的 HTML 提供服务。

您可以通过添加呈现给定模板的 function 来做到这一点(我假设一个应用程序

# ./myapp/views.py:
from django.shortcuts import render

def index(request):
    return render(request, 'myapp/index.html')

然后您的 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>

然后你只需安装你的组件

import { render } from 'react-dom'
import MyComponent from 'path/to/my/component'

const root = document.getElementById("app")
render(<MyComponent />, root);
  1. 使用像create-react-app这样的样板

您可以通过开箱即用的create-react-app来完成“繁重的工作”。 它为您处理了很多事情,因此您可以更专注于开发; 这带来了隐含的成本,它有点像“黑匣子”以及一些额外的管理,因为您的前端应用程序将由 webpack 在幕后“服务”(默认情况下在端口 3000 上),然后您可能需要进行协调稍后通过在 package.json 上定义代理,甚至使用反向代理,例如 nginx。

以下是上述替代方案的一些更深入的教程:

  1. React + Django 模板教程: https://www.valentinog.com/blog/drf/#django-and-react-together
  2. 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM