Anu*_*pam 22 django django-rest-framework reactjs
对不起,如果这看起来像一个愚蠢的问题,但我花了很多时间在这上面,无法找到理想的方法来做到这一点.
我有使用Django模板渲染的Django表单.现在我想在其中一个表单字段中添加一个React组件(并且可能在长期内添加到多个字段).
根据我到目前为止所读到的内容,最好不要将Django模板与React渲染混合,并且让Django仅作为后端API将JSON数据发送到React,而React接管整个表单渲染.所以我现在正试图通过React重新渲染我的表单.我现在已经创建了serializers.py来定义将哪些数据发送到React并在我的环境中设置Django Rest Framework,而不是forms.py.现在我想弄清楚如何发送这些数据.有一些很好的在线教程(和SO帖子)谈到将Django/DRF与React集成,但还没有找到通过React和DRF进行端到端表单渲染的单个示例.具体来说,任何人都可以让我知道在我的视图中我真正写了什么,然后对于试图获取表单数据的React的GET请求有用吗?一个网络参考或只需要广泛的步骤就足以让我开始(并深入挖掘文档).
更新:此处还添加了serializers.py代码的简化版本:
from .models import Entity
from rest_framework import serializers
class EntitySerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Entity
fields = ['name', 'role', 'location']
Run Code Online (Sandbox Code Playgroud)
ali*_*lix 13
首先,我认为您需要检查有关具有多个输入的表单的相关React文档.它为您提供了关于如何在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
});
});
}
Run Code Online (Sandbox Code Playgroud)
然后你可以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>
)
}
Run Code Online (Sandbox Code Playgroud)
这是你的submitForm
方法:
submitForm() {
$.post('/api/profile/2/', {/* put your updated fields' data here */}, (response) => {
// check if things done successfully.
});
}
Run Code Online (Sandbox Code Playgroud)
更新:
以下是untested-but-should-work
DRF视图的示例:
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.'})
Run Code Online (Sandbox Code Playgroud)
这是此视图的相关网址:
urlpatterns = [
url(r'^api/profile/(?P<pk>[0-9]+)/$', ProfileFormView.as_view()),
]
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7485 次 |
最近记录: |