gpt4 book ai didi

Django 表单与 ReactJS

转载 作者:行者123 更新时间:2023-12-03 13:02:45 25 4
gpt4 key购买 nike

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

根据我到目前为止所读到的内容,似乎最好不要将 Django 模板与 React 渲染混合在一起,让 Django 仅作为后端 API 发送 JSON 数据到 React,而 React 接管整个表单渲染。所以我现在尝试完全通过 React 重新渲染我的表单。

我现在创建了serializers.py来定义要发送到React的数据,而不是forms.py,并在我的环境中设置Django Rest Framework。现在我想弄清楚如何发送这些数据。有一些很好的在线教程(和 SO 帖子)讨论了将 Django/DRF 与 React 集成,但还没有找到通过 React 和 DRF 进行端到端表单渲染的单个示例。具体来说,任何人都可以让我知道我在 View 中真正写了哪些内容,这些内容对于来自 React 的尝试获取表单数据的 GET 请求有用?网络引用或所需的广泛步骤应该足以让我开始(并深入研究文档)。

更新:还在这里添加了serializer.py代码的简化版本:

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中尝试类似的操作:

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

更新:

以下是 DRF View 的未经测试但应该有效示例:

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.'})

这是此 View 的相关网址:

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

关于Django 表单与 ReactJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42297614/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com