使用ReactJS的Django表单

时间:2017-02-17 12:08:55

标签: django reactjs django-rest-framework

对不起,如果这看起来像一个愚蠢的问题,但我花了很多时间在这上面,无法找到理想的方法来做到这一点。

我使用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']

1 个答案:

答案 0 :(得分:12)

首先,我认为您需要检查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()),
]