首页 > 解决方案 > 如何使用 django 传递 pk 并做出反应

问题描述

我想通过对 django 的反应来传递 pk

只使用 django 时像这样 <a class="btn btn-default" href="{% url 'blog:comment' pk=blog.pk %}">Add comment</a>

但我不知道如何使用反应模板传递 pk !

这是我的 django models.py

from django.db import models

# Create your models here.
class Meeting(models.Model):
    title = models.CharField(max_length=50)
    topic = models.TextField()
    writer = models.CharField(max_length=30)
    parties = models.TextField()
    meeting_date = models.DateTimeField()
    date = models.DateTimeField(auto_now=True)
    file = models.FileField('media/')

    def __str__(self):
        return self.title

class Result(models.Model):
    meeting = models.OneToOneField(
        Meeting,
        on_delete=models.CASCADE,
        primary_key=True,
    )
    script = models.TextField()
    keyword = models.TextField()
    summary = models.TextField()

这是我的models.py

from django.shortcuts import render, get_object_or_404, redirect
from .models import Meeting, Result
from .stt import *

def resultCreate(request, pk):
    meeting = get_object_or_404(Meeting, pk=pk)
    result = Result()
    audio = meeting.file[22:]
    if __name__ == '__main__':
        res = ClovaSpeechClient().req_upload(file=audio, completion='sync')
        data = res.text
        result.script = data["text"]
        result.save()
    
    return redirect('/result/' + str(meeting.id))

这是Detail.js(前端)

import React from "react";
import Footer from "../component/Footer";
import Header from "../component/Header";

import { Box, Heading, Table, Text, Button } from "gestalt";
import "gestalt/dist/gestalt.css";
class Detail extends React.Component {
  componentDidMount() {
    const { location, history } = this.props;
    if (location.state === undefined) {
      history.push("/");
    }
  }
  createResult() {
    window.location.href = "http://127.0.0.1:8000/testapp/api/result/create";
  }
  render() {
    const { location } = this.props;
    if (location.state) {
      return (
        <div>
          <Header />
          <Box
            display="flex"
            padding={10}
            marginStart={-3}
            marginEnd={-3}
            marginBottom={-3}
            marginTop={-3}
            wrap
            width="100%"
            direction="column"
          >
            <Box
              flex="grow"
              paddingX={3}
              paddingY={4}
              borderStyle="shadow"
              rounding={3}
              color="white"
            >
              <Heading size="md" color="midnight">
                Title: {location.state.title}
              </Heading>
            </Box>
            <Box height={50}></Box>

            <Table>
              <Table.Row>
                <Table.Cell>
                  <Text color="midnight" weight="bold">
                    제목
                  </Text>
                </Table.Cell>
                <Table.Cell>
                  <Text>{location.state.title}</Text>
                </Table.Cell>
              </Table.Row>
              <Table.Row>
                <Table.Cell>
                  <Text color="midnight" weight="bold">
                    회의 안건
                  </Text>
                </Table.Cell>
                <Table.Cell>
                  <Text>{location.state.topic}</Text>
                </Table.Cell>
              </Table.Row>
              <Table.Row>
                <Table.Cell>
                  <Text color="midnight" weight="bold">
                    작성자
                  </Text>
                </Table.Cell>
                <Table.Cell>
                  <Text>{location.state.writer}</Text>
                </Table.Cell>
              </Table.Row>
              <Table.Row>
                <Table.Cell>
                  <Text color="midnight" weight="bold">
                    참석자
                  </Text>
                </Table.Cell>
                <Table.Cell>
                  <Text>{location.state.parties}</Text>
                </Table.Cell>
              </Table.Row>
              <Table.Row>
                <Table.Cell>
                  <Text color="midnight" weight="bold">
                    게시일
                  </Text>
                </Table.Cell>
                <Table.Cell>
                  <Text>{location.state.date.substring(0, 10)}</Text>
                </Table.Cell>
              </Table.Row>
              <Table.Row>
                <Table.Cell>
                  <Text color="midnight" weight="bold">
                    회의 날짜
                  </Text>
                </Table.Cell>
                <Table.Cell>
                  <Text>{location.state.meeting_date.substring(0, 10)}</Text>
                </Table.Cell>
              </Table.Row>
            </Table>

            <Button
              type="button"
              onClick={this.createResult}
              text="Result 결과"
              inline
            />

            <Box height={100}></Box>
          </Box>
          <Footer />
        </div>
      );
    } else {
      return null;
    }
  }
}
export default Detail;

当我单击按钮时,我想在 views.py 中执行 resultCreate 但这会导致错误 resultCreate() 缺少 1 个必需的位置参数:'pk'

……我能为此做些什么?!

标签: pythonreactjsdjango

解决方案


在类组件中,您可以通过添加constructor和访问 ID 来访问 ID props,例如

export class PostDetail extends React.Component {
  
  constructor(props) {
    super(props);
    console.log(this.props.match.params.id)
    this.state = {
      data: [],
      loaded: false,
      placeholder: "Loading"
    };
  }

  render(){
    return(<h1>Post Detail</h1>);
  }
}

而不是你可以将它存储在变量中并在你的方法detailId = this.props.match.params.id中访问它。render()

更新

你必须URL像这样传递 idfetch('http://127.0.0.1:8000/post_detail/'+detailId+'/') 你可以使用反引号我不能用反引号做,因为它将它转换为代码

并且您必须检查URL您的 Django 应用程序中是否有相同的内容,例如。

urlpatterns = [
  path('post_detail/<id>/', PostDetail.as_view(), name="post_detail"),
]

PostDetailView喜欢这样

class PostDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = Post.objects.all()
    serializer_class = serializers.PostSerializer

这是一个示例代码,您必须放置您的代码而不是我的代码,我刚刚给了您一个蓝图,您可以如何从前端访问 Django 中的 id。


推荐阅读