简体   繁体   中英

how to pass pk using django and react

i want to pass pk using react to django

like this when using only django <a class="btn btn-default" href="{% url 'blog:comment' pk=blog.pk %}">Add comment</a>

but i dont know how to pass pk using react template!!

this is my 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()

and this is my 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))

and this is Detail.js (frontend)

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;

when i click button, i want to execute resultCreate in views.py but that makes error resultCreate() missing 1 required positional argument: 'pk'

... what i can do for this?!

In Class Component you can access ID by adding constructor and than access ID from props for example

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

than you can store it in variable like detailId = this.props.match.params.id and access it in your render() method.

UPDATE

you have to pass id in in your URL like this fetch('http://127.0.0.1:8000/post_detail/'+detailId+'/') you can use back ticks i am not able to do with back ticks because it converts it as code

and you have to check that you have same URL in your Django application for eg.

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

and your PostDetailView like this

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

this is an example code you have to put your code instead of mine i just given you a blueprint how you can access id in Django from frontend.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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