まず、私はあなたが複数の入力を持つフォームについてrelated React documentationをチェックする必要があると思います。それは、あなたがリアクション側で物事をどのように構成すべきかについての基本的な考え方を与えます。
サーバーからデータをフェッチについて、あなたは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.'})
そして、これは、このビューの関連URLです:
urlpatterns = [
url(r'^api/profile/(?P<pk>[0-9]+)/$', ProfileFormView.as_view()),
]
1 upvoteと1つのダウン。コメントでサポートされている下降音を喜んで聞かせてください。私はこれ(そして正しいことのやり方)に対する良い解決策を探していましたが、驚くべきことに、リアクトを通してレンダリングされたDjangoフォームの例さえ見つけられませんでした。 DRFは良いドキュメントを持っていますが(私が正しく理解していれば)、フォームデータの良い例をまだ見ていませんでした(つまり、ユーザーが空白のフォームを取得して、それを返します。 -end APIとフロントエンドでのリアクションレンダリング)これはかなり一般的な使用例であるはずです – Anupam