Django表单与ReactJS [英] Django Forms with ReactJS

查看:130
本文介绍了Django表单与ReactJS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对不起,如果这似乎是一个愚蠢的问题,但我花了很多时间,无法找出一个理想的方法。

Sorry if this seems like a dumb question but I have spent a lot of time on this and unable to figure out an ideal way to do this.

我有使用Django模板渲染的Django表单。现在我想添加一个React组件到其中一个表单域(也可能是长期的多个字段)。

I have Django forms rendered using Django templates. Now I want to add a React component to one of the form fields (and perhaps to more than one field in the long term).

根据我目前为止所读的内容,它似乎最好不要将Django模板与React渲染进行混合,而Django仅作为后端API将JSON数据发送到React,而反应接管整个表单渲染。所以我现在试图通过React重新渲染我的表单。而不是forms.py,我现在已经创建了serializers.py来定义要发送到React的数据,并在我的环境中设置了Django Rest Framework。现在我试图找出如何发送这个数据。有一些很好的在线教程(和SO帖子)谈论将Django / DRF与React集成,但是没有发现通过React和DRF实现端到端表单渲染的一个例子。具体来说,任何人都可以让我知道我真正写的是什么,然后可以对来自React的GET请求来尝试获取表单数据?网路参考或所需的广泛步骤应足以让我开始(并进一步挖掘文档)。

Based on what I have read so far, its seem best not to mix Django templating with React rendering and have Django serve only as backend API sending JSON data to React, while React takes over the entire form rendering. So I am now trying to re-render my forms entirely through React. Instead of forms.py, I have now created serializers.py to define what data is to be sent to React and have Django Rest Framework setup in my environment. Now I am trying to figure out how to send this data across. There are some good online tutorials (and SO posts) that talk about integrating Django/DRF with React but havent found a single example of end-to-end form rendering through React and DRF. Specifically, can anyone let me know what do I really write in my view that can then be useful for the GET request from React that tries to fetch the form data? A web reference or just the broad steps needed should be enough for me to get started (and to dig in more into the docs).

更新:
另外在这里添加一个简化版本的serializers.py代码:

Update: Also adding a simplified version of the serializers.py code here:

from .models import Entity
from rest_framework import serializers


class EntitySerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Entity
        fields = ['name', 'role', 'location']


推荐答案

首先,我想你需要检查<关于具有多个输入的表单的href =https://facebook.github.io/react/docs/forms.html#handling-multiple-inputs =nofollow noreferrer>相关的React文档。它为您提供了关于如何在React方面构建事物的基本想法。

First, i think you need to check related React documentation about forms with multiple inputs. It gives you base idea about how things should be structured in React side.

关于从服务器获取数据,您可以在 componentDidMount 中尝试类似的内容:

About fetching data from server, you can try something like this in 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输入元素这样的方法:

Then you can create your html input elements in render method with something like this:

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视图的未经测试但应该工作的示例:

Here is an untested-but-should-work example for your DRF view:

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.'})

这是这个视图的相关网址:

And this is related url for this view:

urlpatterns = [
    url(r'^api/profile/(?P<pk>[0-9]+)/$', ProfileFormView.as_view()),
]

这篇关于Django表单与ReactJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆