我不能创建一个类,我不知道为什么。我对你不太熟悉
我正在学习这个项目,我为我自己设置,所以请帮助我工作了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应用程序,有两种方法可以做到这一点:您可以通过添加一个呈现给定模板的函数来实现这一点(我假设是一个应用程序)
然后,您的HTML文件可以如下所示:
然后您只需挂载您的组件
create-react-app
的样板文件你可以通过
create-react-app
来完成“繁重的工作”,这将是开箱即用的。它为你处理很多事情,因此你可以更专注于开发;这意味着它的成本有点“黑箱”以及一些额外的管理,因为你的前端应用程序将在幕后由webpack“服务”(默认情况下在端口3000上)稍后可能需要通过在package.json上定义代理,甚至使用反向代理(如nginx)来协调以下是有关上述备选方案的一些更深入的教程:
相关问题 更多 >
编程相关推荐