首先,我认为你需要检查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视图中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.'})
,这是对这一观点的相关网址:
urlpatterns = [
url(r'^api/profile/(?P<pk>[0-9]+)/$', ProfileFormView.as_view()),
]
1给予好评和1下来。很高兴能得到评论支持的downvotes请。我一直在寻找一个很好的解决方案(以及正确的做事方式),但令人惊讶的是甚至找不到通过React呈现的Django表单的一个例子。 DRF有一个很好的文档,但是(如果我理解正确的话),我没有看到表单数据正在被发送的一个很好的例子(即,用户获得一个空白表单,填充它,提交回来 - 所有的Django只作为一个后台在前端的API和React渲染)我猜应该是一个非常常见的用例 – Anupam