我使用Django模板呈现Django表单.现在,我想向其中一个表单字段添加一个React组件(从长远来看,可能还会向多个字段添加).

根据我到目前为止读到的内容,最好不要将Django模板与React呈现混合使用,让Django仅作为后端API发送JSON数据以进行React,而React将接管整个表单呈现.所以我现在试图完全通过React来重新呈现我的形体.

而不是形式.我现在已经创建了序列化程序.py定义要发送哪些数据以做出react ,并在我的环境中设置Django Rest框架.现在我正试图弄清楚如何将这些数据发送到各个领域.有一些很好的在线教程(以及其他帖子)讨论了如何将Django/DRF与React集成,但还没有找到一个通过React和DRF进行端到端表单渲染的示例.

更新:

from .models import Entity
from rest_framework import serializers


class EntitySerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Entity
        fields = ['name', 'role', 'location']
      

推荐答案

首先,我认为你需要判断related React documentation个有多个输入的表单.它为你提供了一个基本的概念,让你知道事情应该如何在react 端组织起来.

关于从服务器获取数据,您可以在componentDidMount中try 以下操作:

componentDidMount() {
    // Assuming you are using jQuery,
    // if not, try fetch().
    // Note that 2 is hardcoded, get your user id from 
    // URL or session or somewhere else.
    $.get('/api/profile/2/', (data) => {
        this.setState({
            formFields: data.fields // fields is an array
        });
    });
}

然后,您可以使用以下方法在render方法中创建html输入元素:

render () {
    let fields = this.state.formFields.map((field) => {
        return (
            <input type="text" value={field.value} onChange={(newValue) => {/* update your  state here with new value */ }} name={field.name}/>
        )
    });
    return (
        <div className="container">
            <form action="">
                {fields}
                <button onClick={this.submitForm.bind(this)}>Save</button>
            </form>
        </div>
    )
}

以下是你的submitForm种方法:

submitForm() {
    $.post('/api/profile/2/', {/* put your updated fields' data here */}, (response) => {
       // check if things done successfully.
    });
}

Update:

以下是您的DRF视图的untested-but-should-work个示例:

from rest_framework.decorators import api_view
from django.http import JsonResponse
from rest_framework.views import APIView


class ProfileFormView(APIView):
    # Assume you have a model named UserProfile
    # And a serializer for that model named UserSerializer
    # This is the view to let users update their profile info.
    # Like E-Mail, Birth Date etc.

    def get_object(self, pk):
        try:
            return UserProfile.objects.get(pk=pk)
        except:
            return None

    # this method will be called when your request is GET
    # we will use this to fetch field names and values while creating our form on React side
    def get(self, request, pk, format=None):
        user = self.get_object(pk)
        if not user:
            return JsonResponse({'status': 0, 'message': 'User with this id not found'})

        # You have a serializer that you specified which fields should be available in fo
        serializer = UserSerializer(user)
        # And here we send it those fields to our react component as json
        # Check this json data on React side, parse it, render it as form.
        return JsonResponse(serializer.data, safe=False)

    # this method will be used when user try to update or save their profile
    # for POST requests.
    def post(self, request, pk, format=None):
        try:
            user = self.get_object(pk)
        except:
            return JsonResponse({'status': 0, 'message': 'User with this id not found'})

        e_mail = request.data.get("email", None)
        birth_date = request.data.get('birth_date', None)
        job = request.data.get('job', None)

        user.email = e_mail
        user.birth_date = birth_date
        user.job = job

        try:
            user.save()
            return JsonResponse({'status': 1, 'message': 'Your profile updated successfully!'})
        except:
            return JsonResponse({'status': 0, 'message': 'There was something wrong while updating your profile.'})

这是该视图的相关url:

urlpatterns = [
    url(r'^api/profile/(?P<pk>[0-9]+)/$', ProfileFormView.as_view()),
]

Reactjs相关问答推荐

更新数据时有关CQR和更新UI的问题

如何实现黑暗模式 map ?

有没有方法覆盖NextJS 14中的布局?

REACTJS:在Reaction中根据路由路径更改加载器API URL

获取点击的国家/地区名称react 映射

梅X折线图无响应

如何在NextJS中仅在刷新页面和页面淡出页面过渡时添加全屏加载器

React Router:在没有手动页面刷新的情况下,路由不会更新内容

我如何在不被 destruct 的情况下将导航栏固定在顶部?

从 MongoDB createAt 字段中分割精确时间

是否可以直接在 jsx 标签上使用 CSS 定义的 colored颜色 ?

字段是必需的,当它没有定义时

无法在 KeyDown 上调用 useCallback 函数

如何从 React Redux store 中删除特定项目?

如何将我的 ID 值传递给下一个组件?

Cypress - 替换 React 项目中的变量

Mui CardMedia 的图片组件

当父组件重新渲染时做出react ,我失go 了子状态.我错过了什么?

axios post方法中的请求失败,状态码为500错误

如何从另一个切片中的不同切片获取状态并对其进行处理?