抱歉,这似乎是一个愚蠢的问题,但我在此问题上花费了很多时间,无法找到理想的解决方法。
我有使用Django模板呈现的Django表单。现在,我想将React组件添加到表单字段之一(从长远来看,可能要添加到多个字段)。
根据我到目前为止所读的内容,最好不要将Django模板与React渲染混合使用,而让Django仅用作将JSON数据发送到React的后端API,而React则负责整个表单渲染。所以我现在正试图完全通过React重新渲染我的表单。现在,我创建了serializers.py而不是forms.py,以定义要发送到React的数据,并在我的环境中设置了Django Rest Framework。现在,我试图弄清楚如何发送这些数据。有一些不错的在线教程(和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']
首先,我认为您需要检查有关具有多个输入的表单的相关React文档。它为您提供了有关在React端应该如何组织事物的基本思路。
关于从服务器获取数据,您可以在中尝试以下操作componentDidMount:
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
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
submitForm() { $.post('/api/profile/2/', {/* put your updated fields' data here */}, (response) => { // check if things done successfully. }); }
更新:
这是untested-but-should-work您的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()), ]